🔌
diff --git a/docs/guides/build-time-verification.md b/docs/guides/build-time-verification.md
index 44221724..8278aa3a 100644
--- a/docs/guides/build-time-verification.md
+++ b/docs/guides/build-time-verification.md
@@ -2,7 +2,7 @@
> [English](build-time-verification.md) | [Русский](build-time-verification.ru.md)
-Gradle plugin verifies that flag keys used in code exist in Flagent (via API or local file).
+Gradle plugin verifies that flag keys used in code exist in Flagent (via API or local file). Optionally, strict mode allows only keys from generated constants or `@FlagKey` annotations.
## Installation
@@ -20,7 +20,18 @@ plugins {
}
```
-## Configuration
+## Scenario A: Verify only (keys must exist in Flagent)
+
+Plugin scans `src/**/*.kt` and `src/**/*.java` for:
+
+- `@FlagKey("key")` — annotation
+- `isEnabled("key")` — call
+- `evaluate("key", ...)` — call
+- `evaluateBatch(..., listOf("key1", "key2"), ...)` — string literals in the list
+
+All found keys are checked against Flagent (API or `flagsFile`). If a key is not found and `failOnUnknown = true`, the build fails.
+
+### Configuration
```kotlin
plugins { id("com.flagent.verify-flags") }
@@ -33,27 +44,172 @@ flagent {
}
```
-## Scanning
+### Local file instead of API
-Plugin scans `src/**/*.kt` and `src/**/*.java` for:
+If `flagsFile` is set, plugin reads keys from YAML/JSON:
-- `@FlagKey("key")` — annotation
-- `isEnabled("key")` — call
-- `evaluate("key", ...)` — call
+```yaml
+flags:
+ - key: new_checkout
+ description: "..."
+ - key: dark_mode
+```
-## Run
+### Run
```bash
./gradlew verifyFlags
```
-## Local file instead of API
+---
-If `flagsFile` is set, plugin reads keys from YAML/JSON:
+## Scenario B: Strict mode (only FlagKeys.* or @FlagKey)
-```yaml
-flags:
- - key: new_checkout
- description: "..."
- - key: dark_mode
+For teams that want to forbid raw string literals in `isEnabled("...")` / `evaluate("...")`, use:
+
+1. **Artifact `flagent-annotations`** — declare keys in code with `@FlagKey`, and/or
+2. **Task `generateFlagKeys`** — generate `FlagKeys.kt` from API or `flagsFile`
+3. **Option `allowOnlyGeneratedOrAnnotated = true`** — build fails if any raw string is used
+
+### Step 1: Annotations (optional)
+
+Add dependency and declare keys:
+
+```kotlin
+// build.gradle.kts
+dependencies {
+ compileOnly("com.flagent:flagent-annotations:0.1.6") // use project version
+}
+```
+
+```kotlin
+// src/main/kotlin/AppFlags.kt
+package myapp
+
+import com.flagent.annotations.FlagKey
+
+object AppFlags {
+ @FlagKey("new_checkout_flow")
+ const val NEW_CHECKOUT_FLOW = "new_checkout_flow"
+
+ @FlagKey("dark_mode")
+ const val DARK_MODE = "dark_mode"
+}
```
+
+Then use `client.isEnabled(AppFlags.NEW_CHECKOUT_FLOW, entityId, context)`.
+
+### Step 2: Generate FlagKeys.kt
+
+Configure the plugin to generate an object or enum from Flagent (API or file):
+
+```kotlin
+plugins { id("com.flagent.verify-flags") }
+
+flagent {
+ baseUrl = "https://api.flagent.example.com"
+ apiKey = providers.environmentVariable("FLAGENT_API_KEY").getOrElse("")
+ flagsFile = file("flags.yaml") // or use API when flagsFile is not set
+
+ // Generation
+ flagKeysOutputDir = layout.buildDirectory.dir("generated/sources/flagent/flagKeys")
+ flagKeysFormat = "object" // or "enum"
+ flagKeysPackage = "myapp.flags"
+
+ failOnUnknown = true
+ allowOnlyGeneratedOrAnnotated = true // strict mode
+}
+```
+
+Add the generated directory to Kotlin source sets so the compiler sees `FlagKeys.kt`:
+
+```kotlin
+kotlin {
+ sourceSets["main"].kotlin.srcDirs(layout.buildDirectory.dir("generated/sources/flagent/flagKeys"))
+}
+```
+
+Run generation (runs automatically before `compileKotlin`):
+
+```bash
+./gradlew generateFlagKeys
+```
+
+Generated file example (`flagKeysFormat = "object"`):
+
+```kotlin
+package myapp.flags
+
+object FlagKeys {
+ const val DARK_MODE: String = "dark_mode"
+ const val NEW_CHECKOUT_FLOW: String = "new_checkout_flow"
+}
+```
+
+Use in code: `client.isEnabled(FlagKeys.NEW_CHECKOUT_FLOW, entityId, context)`.
+
+### Step 3: Enable strict mode
+
+Set `allowOnlyGeneratedOrAnnotated = true`. The build will fail if any raw string appears in `isEnabled("...")` or `evaluate("...")` (or in `evaluateBatch(..., listOf("..."), ...)`). Only keys from generated `FlagKeys` or from `@FlagKey` constants are allowed.
+
+### Full example (Scenario B)
+
+```kotlin
+// build.gradle.kts
+plugins {
+ kotlin("jvm")
+ id("com.flagent.verify-flags")
+}
+
+dependencies {
+ compileOnly("com.flagent:flagent-annotations:0.1.6")
+ implementation("com.flagent:kotlin-enhanced:0.1.6")
+}
+
+flagent {
+ baseUrl = "https://api.flagent.example.com"
+ apiKey = providers.environmentVariable("FLAGENT_API_KEY").getOrElse("")
+ flagsFile = file("src/main/resources/flags.yaml")
+ failOnUnknown = true
+ flagKeysOutputDir = layout.buildDirectory.dir("generated/sources/flagent/flagKeys")
+ flagKeysFormat = "object"
+ flagKeysPackage = "myapp.flags"
+ allowOnlyGeneratedOrAnnotated = true
+}
+
+kotlin {
+ jvmToolchain(17)
+ sourceSets["main"].kotlin.srcDirs(layout.buildDirectory.dir("generated/sources/flagent/flagKeys"))
+}
+```
+
+```kotlin
+// Usage: only FlagKeys.* or constants with @FlagKey
+client.isEnabled(FlagKeys.NEW_CHECKOUT_FLOW, "user1", null)
+```
+
+---
+
+## Reference: extension properties
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `baseUrl` | String | `http://localhost:18000` | Flagent API base URL |
+| `apiKey` | String | `""` | X-API-Key header |
+| `flagsFile` | File | (none) | YAML/JSON file with list of `{ key: "..." }` instead of API |
+| `failOnUnknown` | Boolean | `true` | Fail build if code references a key not in Flagent |
+| `flagKeysOutputDir` | Directory | `build/generated/sources/flagent/flagKeys` | Where to write generated `FlagKeys.kt` |
+| `flagKeysFormat` | String | `"object"` | `"object"` or `"enum"` |
+| `flagKeysPackage` | String | `"flagent.generated"` | Package of generated class |
+| `allowOnlyGeneratedOrAnnotated` | Boolean | `false` | If true, raw strings in isEnabled/evaluate are forbidden |
+
+## Tasks
+
+- **verifyFlags** — scan sources, check keys against API/file; if strict mode, fail on raw strings.
+- **generateFlagKeys** — generate `FlagKeys.kt` from API or `flagsFile`; runs before `compileKotlin` when plugin is applied.
+
+## See also
+
+- Full spec (strict mode) — see internal/private docs.
+- [samples/kotlin](../../samples/kotlin) — Kotlin sample
+- [samples/kotlin-strict-flags](../../samples/kotlin-strict-flags) — minimal project with generateFlagKeys and allowOnlyGeneratedOrAnnotated
diff --git a/docs/guides/compatibility.md b/docs/guides/compatibility.md
index cde20cee..88dc7521 100644
--- a/docs/guides/compatibility.md
+++ b/docs/guides/compatibility.md
@@ -143,6 +143,11 @@ Supported operators for segment constraints:
4. **SDK integration** – Use Flagent SDKs (Kotlin, Java, JavaScript, Swift, Python, Go) or direct HTTP calls.
+5. **OpenFeature-style client** – For Kotlin Multiplatform you can use the
+ `kotlin-openfeature` module, which exposes an OpenFeature-like API and
+ internally talks to the same `/api/v1/evaluation` endpoint via the
+ generated Kotlin client.
+
### Example: cURL Evaluation
```bash
@@ -162,3 +167,19 @@ curl -X POST http://localhost:18000/api/v1/evaluation \
- [OpenAPI Specification](../api/openapi.yaml)
- [Getting Started](getting-started.md)
- [Examples](../examples/README.md)
+
+## OpenFeature and standardization
+
+Flagent is compatible with the OpenFeature model of evaluation: a provider
+interface, evaluation context, and typed flag values. The
+`kotlin-openfeature` KMP module provides an OpenFeature-like client that
+adapts requests to Flagent's `/evaluation` endpoint and maps responses into
+typed results (`boolean`, `string`, `int`, `double`, and JSON object).
+
+This makes it easier to:
+
+- share client code between different feature flag backends,
+- migrate to or from Flagent while keeping application code close to the
+ OpenFeature specification (`https://openfeature.dev/`),
+- keep Kotlin clients vendor-agnostic at the call-site level while
+ delegating evaluation to Flagent.
diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md
index 7bc1cf1a..0c8ad965 100644
--- a/docs/guides/configuration.md
+++ b/docs/guides/configuration.md
@@ -379,6 +379,8 @@ FLAGENT_FIREBASE_ANALYTICS_CLIENT_ID_KEY=client_id
**Required:** Pass `app_instance_id` (Firebase app) or `client_id` (web) in `entityContext` when evaluating so events attach to the correct user in GA4.
+When the admin UI is enabled, you can see a read-only summary of the current Firebase integration status in **Settings → Firebase**.
+
## Analytics Retention
Control retention of analytics events (Firebase-level: first_open, session_start, screen_view, custom).
diff --git a/docs/guides/configuration.ru.md b/docs/guides/configuration.ru.md
index 6dfdf623..392bb316 100644
--- a/docs/guides/configuration.ru.md
+++ b/docs/guides/configuration.ru.md
@@ -355,6 +355,8 @@ FLAGENT_FIREBASE_ANALYTICS_CLIENT_ID_KEY=client_id
**Требуется:** Передавать `app_instance_id` (Firebase app) или `client_id` (web) в `entityContext` при evaluation, чтобы события привязывались к пользователю в GA4.
+При включённом UI админки вы можете посмотреть текущий статус интеграции Firebase (только для чтения) в разделе **Settings → Firebase**.
+
## Примеры файлов конфигурации
### Разработка
diff --git a/docs/guides/faq.md b/docs/guides/faq.md
index f54a728b..c51163cf 100644
--- a/docs/guides/faq.md
+++ b/docs/guides/faq.md
@@ -31,6 +31,18 @@ Yes! Flagent is open-source and licensed under Apache 2.0. You can use it for fr
- **Clean Architecture** – DDD, testable, maintainable
- **Open source** – Apache 2.0, self-hosted, no vendor lock-in
+### How does Flagent differ from LaunchDarkly (and others)?
+
+Flagent is **Kotlin-native**, **self-hosted first**, and **open source** (Apache 2.0). Unlike LaunchDarkly (SaaS, commercial), you run Flagent on your infrastructure and own your data. Feature set: feature flags, A/B experiments, gradual rollouts, kill switches, targeting, client-side evaluation (Kotlin Enhanced, Go Enhanced), optional crash-by-flag analytics. Enterprise adds SSO, RBAC, Smart Rollout, Anomaly Detection, on-premise. See [Pricing and editions](pricing-and-editions.md) for a full comparison.
+
+### Do I need my own server?
+
+**Self-hosted (Open Source):** Yes — you run Flagent yourself (Docker, Kubernetes, or from source). You need a server (or cluster) and a database (PostgreSQL, MySQL, or SQLite). No usage-based billing; full control and data residency. **Flagent Cloud (SaaS)** is planned but not yet available; when it launches, you’ll be able to use Flagent without running your own server. See [Pricing and editions](pricing-and-editions.md).
+
+### What's included in Enterprise?
+
+Enterprise adds: **SSO** (SAML, OAuth/OIDC), **RBAC** (custom roles and permissions), **multi-tenancy** and on-premise deployment, **Smart Rollout** (automated gradual rollout and rollback), **Anomaly Detection** (alerts and optional rollback), **crash-by-flag** analytics and integration with Anomaly, **dedicated support**, SLA, and custom development. Contact: max.developer.luxs@gmail.com. Full comparison: [Pricing and editions](pricing-and-editions.md).
+
## Installation & Deployment
### How do I get started with Flagent?
diff --git a/docs/guides/faq.ru.md b/docs/guides/faq.ru.md
index 02ebac8c..50f0871b 100644
--- a/docs/guides/faq.ru.md
+++ b/docs/guides/faq.ru.md
@@ -22,6 +22,18 @@ Flagent — open-source платформа для feature flags и экспер
- **Production-Ready**: Clean Architecture, лучшие практики
- **Open Source**: активная разработка
+### Чем Flagent отличается от LaunchDarkly (и других)?
+
+Flagent — **Kotlin-native**, в первую очередь **self-hosted** и **open source** (Apache 2.0). В отличие от LaunchDarkly (SaaS, коммерческий), вы запускаете Flagent у себя и владеете данными. Возможности: feature flags, A/B эксперименты, постепенные раскаты, kill switches, таргетинг, client-side evaluation (Kotlin Enhanced, Go Enhanced), опциональная аналитика крашей по флагам. В Enterprise: SSO, RBAC, Smart Rollout, Anomaly Detection, on-premise. Подробнее: [Тарифы и издания](pricing-and-editions.md).
+
+### Нужен ли свой сервер?
+
+**Self-hosted (Open Source):** Да — вы запускаете Flagent сами (Docker, Kubernetes или из исходников). Нужен сервер (или кластер) и БД (PostgreSQL, MySQL или SQLite). Нет поминутной оплаты; полный контроль и хранение данных у себя. **Flagent Cloud (SaaS)** в планах, но пока недоступен; когда запустится, можно будет использовать Flagent без своего сервера. См. [Тарифы и издания](pricing-and-editions.md).
+
+### Что входит в Enterprise?
+
+В Enterprise входят: **SSO** (SAML, OAuth/OIDC), **RBAC** (кастомные роли и права), **мультитенантность** и on-premise, **Smart Rollout** (автоматический постепенный раскат и откат), **Anomaly Detection** (алерты и опциональный откат), аналитика **крашей по флагам** и интеграция с Anomaly, **выделенная поддержка**, SLA и кастомная разработка. Контакт: max.developer.luxs@gmail.com. Полное сравнение: [Тарифы и издания](pricing-and-editions.md).
+
### Как быстро начать?
Самый быстрый способ — Docker:
diff --git a/docs/guides/frontend-ui.md b/docs/guides/frontend-ui.md
index 9353407c..b24f28ad 100644
--- a/docs/guides/frontend-ui.md
+++ b/docs/guides/frontend-ui.md
@@ -43,6 +43,8 @@ Segments are reusable; multiple flags can use the same segment.
Use experiments for A/B tests and gradual rollouts.
+
+
### Evaluation / Debug Console
- **Single evaluation** — enter flag key, entity ID, and optional context; see the evaluated variant and reason.
@@ -50,6 +52,17 @@ Use experiments for A/B tests and gradual rollouts.
Use this to verify that targeting and distributions behave as expected before releasing.
+
+
+#### How to test a flag without deploying
+
+You can check which variant a user would get and why, without running your app in production:
+
+1. **Open Debug Console** — in the sidebar click **Debug** (or go to **UI → Debug Console**). The Single evaluation tab is selected by default.
+2. **Enter flag key and entity** — in **Flag Key** type the key of the flag (e.g. `new_checkout_flow`). In **Entity ID** enter an identifier for the user or session (e.g. `user_123`). Optionally set **Entity type** (e.g. `user`, `report`).
+3. **Optional: set context** — in **Entity Context (JSON)** add attributes used by your segments (e.g. `user_id`, `region`, `tier`). Example: `{"user_id": "user_123", "region": "EU", "tier": "premium"}`. This lets you test segment and constraint rules.
+4. **Evaluate** — click **POST /api/v1/evaluation**. The **Response** area shows the assigned variant, reason, and (if debug is enabled) evaluation details. Use this to confirm targeting and rollout before releasing.
+
### Analytics
- **Metrics** — usage and evaluation metrics over time.
diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md
index 87686a19..6dd7adba 100644
--- a/docs/guides/getting-started.md
+++ b/docs/guides/getting-started.md
@@ -79,8 +79,14 @@ http://localhost:18000
- Email: `admin@local`
- Password: `admin`
+After login you will see the dashboard and the flags list.
+
+
+
### 3. Create Your First Flag
+
+
1. Click **"Create Flag"** button
2. Enter flag details:
- **Key**: `my_first_flag`
@@ -95,70 +101,207 @@ http://localhost:18000
- **Percent**: 100%
6. Click **"Save"**
-### 4. Evaluate from Your App
+### 4. Quick start by platform
+
+Evaluate the flag from your app. Pick your platform (anchors): [Kotlin](#kotlin) · [Ktor](#ktor) · [Spring Boot](#spring-boot) · [JavaScript](#javascript) · [Python](#python) · [Swift](#swift) · [Go](#go) · [Dart / Flutter](#dart--flutter).
+
+---
-Choose your language:
+#### Kotlin
+
+**Install:**
+```kotlin
+dependencies {
+ implementation("com.flagent:kotlin-client:0.1.6") // use version from VERSION or Releases
+}
+```
-**Kotlin:**
+**Minimal code (init + evaluate):**
```kotlin
val client = FlagentClient.create(baseUrl = "http://localhost:18000/api/v1")
+val result = client.evaluate(flagKey = "my_first_flag", entityID = "user123")
+if (result.variantKey == "enabled") { /* feature is on */ }
+```
-val result = client.evaluate(
- flagKey = "my_first_flag",
- entityID = "user123"
+**Optional: OpenFeature-like KMP client:**
+
+If you prefer an OpenFeature-style API, use the multiplatform `kotlin-openfeature`
+module on top of the same backend:
+
+```kotlin
+val provider = FlagentOpenFeatureProvider(
+ FlagentOpenFeatureConfig(baseUrl = "http://localhost:18000/api/v1")
)
+val ofClient = DefaultOpenFeatureClient(provider)
+
+val enabled = ofClient.getBooleanValue(
+ key = "my_first_flag",
+ defaultValue = false,
+ context = EvaluationContext(targetingKey = "user123")
+)
+```
+
+See `sdk/kotlin-openfeature/README.md` and the Android sample (`samples/android`)
+for a full example of this integration.
+
+**Verify in Debug Console:** Open [Debug Console](frontend-ui.md#evaluation--debug-console) in the UI (sidebar → Debug Console), enter flag key `my_first_flag` and entity ID `user123`, then click Evaluate.
-if (result.variantKey == "enabled") {
- // Feature is enabled
+---
+
+#### Ktor
+
+**Install:**
+```kotlin
+implementation("com.flagent:ktor-flagent:0.1.6")
+```
+
+**Minimal code:**
+```kotlin
+// Application.kt
+installFlagent {
+ flagentBaseUrl = "http://localhost:18000"
+ enableEvaluation = true
}
+// In a route:
+val client = call.application.getFlagentClient()
+val result = client?.evaluate(EvaluationRequest(flagKey = "my_first_flag", entityID = "user123"))
```
-**Python:**
-```python
-from flagent import FlagentClient
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): flag key `my_first_flag`, entity ID `user123` → Evaluate.
-client = FlagentClient(base_url="http://localhost:18000/api/v1")
-result = await client.evaluate(flag_key="my_first_flag", entity_id="user123")
+---
+
+#### Spring Boot
-if result.is_enabled():
- # Feature is enabled
+**Install:**
+```kotlin
+implementation("com.flagent:flagent-spring-boot-starter:0.1.6")
+```
+
+**Minimal code (e.g. in a controller):**
+```java
+@Autowired EvaluationApi flagentFacade;
+// ...
+EvalResult r = flagentFacade.evaluate(new EvalContext().flagKey("my_first_flag").entityID("user123"));
+// r.getVariantKey(), r.getEnabled(), etc.
```
-**JavaScript:**
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) — enter `my_first_flag` and `user123`, then Evaluate.
+
+---
+
+#### JavaScript
+
+**Install:**
+```bash
+npm install @flagent/client
+```
+
+**Minimal code:**
```javascript
import { FlagentClient } from '@flagent/client';
+const client = new FlagentClient({ baseUrl: 'http://localhost:18000/api/v1' });
+const result = await client.evaluate({ flagKey: 'my_first_flag', entityID: 'user123' });
+if (result.variantKey === 'enabled') { /* feature is on */ }
+```
-const client = new FlagentClient({
- baseUrl: 'http://localhost:18000/api/v1'
-});
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): flag key `my_first_flag`, entity ID `user123` → Evaluate.
-const result = await client.evaluate({
- flagKey: 'my_first_flag',
- entityID: 'user123'
-});
+---
-if (result.variantKey === 'enabled') {
- // Feature is enabled
-}
+#### Python
+
+**Install:**
+```bash
+pip install flagent-python-client
+```
+
+**Minimal code (async):**
+```python
+import asyncio
+from flagent import create_client
+
+async def main():
+ client = create_client("http://localhost:18000/api/v1")
+ result = await client.evaluate(flag_key="my_first_flag", entity_id="user123")
+ if result.is_enabled(): # or result.variant_key == "enabled"
+ pass # feature is on
+ await client.close()
+asyncio.run(main())
+```
+
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): flag key `my_first_flag`, entity ID `user123` → Evaluate.
+
+---
+
+#### Swift
+
+**Install (Swift Package Manager):**
+```swift
+.package(url: "https://github.com/MaxLuxs/Flagent.git", from: "0.1.6")
```
-**Swift:**
+**Minimal code:**
```swift
let client = FlagentClient(baseURL: "http://localhost:18000/api/v1")
+let result = try await client.evaluate(flagKey: "my_first_flag", entityID: "user123")
+if result.variantKey == "enabled" { /* feature is on */ }
+```
-let result = try await client.evaluate(
- flagKey: "my_first_flag",
- entityID: "user123"
-)
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) — flag key `my_first_flag`, entity ID `user123` → Evaluate.
-if result.variantKey == "enabled" {
- // Feature is enabled
-}
+---
+
+#### Go
+
+**Install:**
+```bash
+go get github.com/MaxLuxs/Flagent/sdk/go
```
+**Minimal code:**
+```go
+client, _ := flagent.NewClient("http://localhost:18000/api/v1")
+result, _ := client.Evaluate(ctx, &flagent.EvaluationContext{
+ FlagKey: flagent.StringPtr("my_first_flag"),
+ EntityID: flagent.StringPtr("user123"),
+})
+if result.IsEnabled() { /* feature is on */ }
+```
+
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): flag key `my_first_flag`, entity ID `user123` → Evaluate.
+
+---
+
+#### Dart / Flutter
+
+**Install (Flutter Enhanced — recommended):**
+```yaml
+# pubspec.yaml
+dependencies:
+ flagent_enhanced:
+ git:
+ url: https://github.com/MaxLuxs/Flagent.git
+ path: sdk/flutter-enhanced
+```
+Or base Dart client from pub.dev: `flagent_client: ^0.1.6`.
+
+**Minimal code (Flutter Enhanced):**
+```dart
+import 'package:flagent_enhanced/flagent_enhanced.dart';
+
+final client = Flagent.create(baseUrl: 'http://localhost:18000/api/v1');
+final result = await client.evaluate(flagKey: 'my_first_flag', entityID: 'user123');
+if (result.variantKey == 'enabled') { /* feature is on */ }
+```
+
+**Verify in Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): flag key `my_first_flag`, entity ID `user123` → Evaluate.
+
+---
+
### 5. Test Your Flag
-Run your app and verify that the flag evaluation works!
+Run your app and confirm the flag evaluates as expected. **Verify the result in the [Debug Console](frontend-ui.md#evaluation--debug-console)** (UI → Debug Console): enter the same flag key and entity ID to see the variant and reason without deploying again.
## Core Concepts
diff --git a/docs/guides/getting-started.ru.md b/docs/guides/getting-started.ru.md
index 6f358f47..6436acc9 100644
--- a/docs/guides/getting-started.ru.md
+++ b/docs/guides/getting-started.ru.md
@@ -77,8 +77,14 @@ http://localhost:18000
- Email: `admin@local`
- Пароль: `admin`
+После входа вы увидите дашборд и список флагов.
+
+
+
### 3. Создать первый флаг
+
+
1. Нажмите кнопку **"Создать флаг"**
2. Введите данные флага:
- **Ключ**: `my_first_flag`
@@ -93,70 +99,185 @@ http://localhost:18000
- **Процент**: 100%
6. Нажать **"Сохранить"**
-### 4. Оценить из вашего приложения
+### 4. Быстрый старт по платформам
+
+Оцените флаг из приложения. Выберите платформу (якоря): [Kotlin](#kotlin) · [Ktor](#ktor) · [Spring Boot](#spring-boot) · [JavaScript](#javascript) · [Python](#python) · [Swift](#swift) · [Go](#go) · [Dart / Flutter](#dart--flutter).
+
+---
-Выберите ваш язык:
+#### Kotlin
+
+**Установка:**
+```kotlin
+dependencies {
+ implementation("com.flagent:kotlin-client:0.1.6") // версия из VERSION или Releases
+}
+```
-**Kotlin:**
+**Минимальный код (инициализация + оценка):**
```kotlin
val client = FlagentClient.create(baseUrl = "http://localhost:18000/api/v1")
+val result = client.evaluate(flagKey = "my_first_flag", entityID = "user123")
+if (result.variantKey == "enabled") { /* функция включена */ }
+```
-val result = client.evaluate(
- flagKey = "my_first_flag",
- entityID = "user123"
-)
+**Проверь в Debug Console:** откройте [Debug Console](frontend-ui.md#evaluation--debug-console) в UI (сайдбар → Debug Console), введите ключ флага `my_first_flag` и entity ID `user123`, нажмите Evaluate.
+
+---
+
+#### Ktor
+
+**Установка:**
+```kotlin
+implementation("com.flagent:ktor-flagent:0.1.6")
+```
-if (result.variantKey == "enabled") {
- // Функция включена
+**Минимальный код:**
+```kotlin
+// Application.kt
+installFlagent {
+ flagentBaseUrl = "http://localhost:18000"
+ enableEvaluation = true
}
+// В роуте:
+val client = call.application.getFlagentClient()
+val result = client?.evaluate(EvaluationRequest(flagKey = "my_first_flag", entityID = "user123"))
```
-**Python:**
-```python
-from flagent import FlagentClient
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): ключ `my_first_flag`, entity ID `user123` → Evaluate.
-client = FlagentClient(base_url="http://localhost:18000/api/v1")
-result = await client.evaluate(flag_key="my_first_flag", entity_id="user123")
+---
+
+#### Spring Boot
-if result.is_enabled():
- # Функция включена
+**Установка:**
+```kotlin
+implementation("com.flagent:flagent-spring-boot-starter:0.1.6")
+```
+
+**Минимальный код (например в контроллере):**
+```java
+@Autowired EvaluationApi flagentFacade;
+// ...
+EvalResult r = flagentFacade.evaluate(new EvalContext().flagKey("my_first_flag").entityID("user123"));
```
-**JavaScript:**
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) — введите `my_first_flag` и `user123`, затем Evaluate.
+
+---
+
+#### JavaScript
+
+**Установка:**
+```bash
+npm install @flagent/client
+```
+
+**Минимальный код:**
```javascript
import { FlagentClient } from '@flagent/client';
+const client = new FlagentClient({ baseUrl: 'http://localhost:18000/api/v1' });
+const result = await client.evaluate({ flagKey: 'my_first_flag', entityID: 'user123' });
+if (result.variantKey === 'enabled') { /* функция включена */ }
+```
-const client = new FlagentClient({
- baseUrl: 'http://localhost:18000/api/v1'
-});
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): ключ `my_first_flag`, entity ID `user123` → Evaluate.
-const result = await client.evaluate({
- flagKey: 'my_first_flag',
- entityID: 'user123'
-});
+---
-if (result.variantKey === 'enabled') {
- // Функция включена
-}
+#### Python
+
+**Установка:**
+```bash
+pip install flagent-python-client
+```
+
+**Минимальный код (async):**
+```python
+import asyncio
+from flagent import create_client
+
+async def main():
+ client = create_client("http://localhost:18000/api/v1")
+ result = await client.evaluate(flag_key="my_first_flag", entity_id="user123")
+ if result.is_enabled(): # или result.variant_key == "enabled"
+ pass # функция включена
+ await client.close()
+asyncio.run(main())
```
-**Swift:**
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): ключ `my_first_flag`, entity ID `user123` → Evaluate.
+
+---
+
+#### Swift
+
+**Установка (Swift Package Manager):**
+```swift
+.package(url: "https://github.com/MaxLuxs/Flagent.git", from: "0.1.6")
+```
+
+**Минимальный код:**
```swift
let client = FlagentClient(baseURL: "http://localhost:18000/api/v1")
+let result = try await client.evaluate(flagKey: "my_first_flag", entityID: "user123")
+if result.variantKey == "enabled" { /* функция включена */ }
+```
-let result = try await client.evaluate(
- flagKey: "my_first_flag",
- entityID: "user123"
-)
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) — ключ `my_first_flag`, entity ID `user123` → Evaluate.
-if result.variantKey == "enabled" {
- // Функция включена
-}
+---
+
+#### Go
+
+**Установка:**
+```bash
+go get github.com/MaxLuxs/Flagent/sdk/go
```
+**Минимальный код:**
+```go
+client, _ := flagent.NewClient("http://localhost:18000/api/v1")
+result, _ := client.Evaluate(ctx, &flagent.EvaluationContext{
+ FlagKey: flagent.StringPtr("my_first_flag"),
+ EntityID: flagent.StringPtr("user123"),
+})
+if result.IsEnabled() { /* функция включена */ }
+```
+
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): ключ `my_first_flag`, entity ID `user123` → Evaluate.
+
+---
+
+#### Dart / Flutter
+
+**Установка (Flutter Enhanced — рекомендуется):**
+```yaml
+# pubspec.yaml
+dependencies:
+ flagent_enhanced:
+ git:
+ url: https://github.com/MaxLuxs/Flagent.git
+ path: sdk/flutter-enhanced
+```
+Либо базовый Dart-клиент с pub.dev: `flagent_client: ^0.1.6`.
+
+**Минимальный код (Flutter Enhanced):**
+```dart
+import 'package:flagent_enhanced/flagent_enhanced.dart';
+
+final client = Flagent.create(baseUrl: 'http://localhost:18000/api/v1');
+final result = await client.evaluate(flagKey: 'my_first_flag', entityID: 'user123');
+if (result.variantKey == 'enabled') { /* функция включена */ }
+```
+
+**Проверь в Debug Console:** [Debug Console](frontend-ui.md#evaluation--debug-console) (UI → Debug Console): ключ `my_first_flag`, entity ID `user123` → Evaluate.
+
+---
+
### 5. Протестировать флаг
-Запустите ваше приложение и убедитесь, что оценка флага работает!
+Запустите приложение и убедитесь, что оценка флага работает. **Проверьте результат в [Debug Console](frontend-ui.md#evaluation--debug-console)** (UI → Debug Console): введите тот же ключ флага и entity ID, чтобы увидеть вариант и причину без повторного деплоя.
## Основные концепции
diff --git a/docs/guides/roadmap.md b/docs/guides/roadmap.md
index 1327469e..1d297dc9 100644
--- a/docs/guides/roadmap.md
+++ b/docs/guides/roadmap.md
@@ -2,7 +2,7 @@
> [English](#english) · [Русский](#русский)
-**This document is the single source of truth for product development.** Use it for planning, prioritisation, and alignment. All “Done” items are verified against the codebase; “Planned” is ordered by priority.
+**This document is the single source of truth for product development.** Use it for planning, prioritisation, and alignment. See also PRD (internal/private docs) for vision, positioning, and monetisation directions. All “Done” items are verified against the codebase; “Planned” is ordered by priority.
---
@@ -24,7 +24,7 @@
| **Data** | Data recorders: Kafka, Kinesis, PubSub. |
| **Backend** | PostgreSQL, MySQL, SQLite; Docker, Docker Compose; CI/CD; [Helm chart](../../helm/flagent/). |
| **Benchmarks** | k6 load tests (evaluation, metrics, anomaly) in [infrastructure/load-tests](../../infrastructure/load-tests/); [load-test workflow](https://github.com/MaxLuxs/Flagent/blob/main/.github/workflows/load-test.yml) in CI (report + PR comment); [benchmarks doc](../performance/benchmarks.md) (targets, run instructions); [tuning guide](../performance/tuning-guide.md). |
-| **SDKs** | Kotlin (KMP), Kotlin Enhanced (client-side eval, SSE), **flagent-koin** (Koin DI), JavaScript/TypeScript, Swift, Swift Enhanced, Python (asyncio), Go, Go Enhanced (client-side eval, SSE), Java, Spring Boot Starter; Dart, Flutter Enhanced; Ktor plugin; Debug UI (Kotlin, Swift, JS). |
+| **SDKs** | Kotlin (KMP), Kotlin Enhanced (client-side eval, SSE), **flagent-koin** (Koin DI), JavaScript/TypeScript, Swift, Swift Enhanced, Python (asyncio), Go, Go Enhanced (client-side eval, SSE), Java, Spring Boot Starter; Dart, Flutter Enhanced; Ktor plugin; Debug UI (Kotlin, Swift, JS). Gradle plugin: verify-flags, optional [strict flag keys](build-time-verification.md#scenario-b-strict-mode-only-flagkeys-or-flagkey) (generateFlagKeys, allowOnlyGeneratedOrAnnotated). |
| **Import/export** | YAML/JSON import (POST /import) and export from Settings (OSS). |
| **Webhooks** | **Outgoing:** configurable URLs for flag events (created/updated/deleted/enabled/disabled); any endpoint (e.g. Slack, Datadog) via Settings → Webhooks. **Incoming:** GitHub webhook — auto-create flag from PR branch name ([GitOps](gitops.md#github-webhook)). |
| **MCP** | Model Context Protocol for AI assistants ([MCP guide](mcp.md)). |
@@ -80,7 +80,7 @@ Contributions and feature requests: [GitHub Issues](https://github.com/MaxLuxs/F
## Русский
-**Этот документ — единый источник правды для разработки продукта.** Используйте его для планирования, приоритизации и согласования. Все пункты «Сделано» проверены по кодовой базе; «В планах» упорядочено по приоритету.
+**Этот документ — единый источник правды для разработки продукта.** Используйте его для планирования, приоритизации и согласования. См. также PRD (внутренняя/приватная документация) — видение, позиционирование и направления монетизации. Все пункты «Сделано» проверены по кодовой базе; «В планах» упорядочено по приоритету.
**Flagent** — первая Kotlin-native платформа для feature flags. Ниже: что **сделано** (Фаза 1, Q1 2026) и что **запланировано** по приоритету.
diff --git a/docs/guides/sdk-selection.md b/docs/guides/sdk-selection.md
new file mode 100644
index 00000000..30fe9f8a
--- /dev/null
+++ b/docs/guides/sdk-selection.md
@@ -0,0 +1,48 @@
+# Какой SDK выбрать
+
+Краткое руководство по выбору клиентского SDK Flagent в зависимости от платформы, сценария (server-side vs client-side evaluation) и способа интеграции.
+
+## Сводная таблица
+
+| SDK | Платформа | Рекомендуемый вход | Server-side eval | Client-side eval (offline) | Когда использовать |
+|-----|-----------|--------------------|------------------|----------------------------|--------------------|
+| **Kotlin Enhanced** | JVM, Android, KMP (iOS) | `Flagent.builder().baseUrl(...).build()` | ✅ | ✅ (mode `.offline`) | Мобильные приложения (Android/iOS), десктоп, общий Kotlin-код. Единый API: `evaluate`, `isEnabled`, `evaluateBatch`. |
+| **Kotlin (base)** | JVM, Android, KMP | `EvaluationApi` + низкоуровневый API | ✅ | ❌ | Когда нужен только вызов API без кэша и офлайн-режима. |
+| **Ktor plugin** | Ktor server | `installFlagent { ... }` | ✅ | ❌ | Сервер на Ktor: один плагин, `getFlagentClient()`, кэш на сервере. |
+| **Spring Boot Starter** | Spring Boot | `application.yml` + `FlagentEvaluationFacade` | ✅ | ❌ | Сервер на Spring: автоконфиг, инъекция фасада. |
+| **JavaScript Enhanced** | Browser, Node, React Native | `Flagent.create({ basePath, ... })` | ✅ | ❌* | Веб и React Native; кэш, один объект с `evaluate`/`isEnabled`/`evaluateBatch`. |
+| **Swift Enhanced** | iOS, macOS | `Flagent.builder()...build()` | ✅ | ✅ (`.mode(.offline)`) | Нативные приложения Apple. |
+| **Go Enhanced** | Go 1.18+ | `enhanced.NewFlagent(ctx, baseURL, opts)` | ✅ | ✅ (`opts.Offline = true`) | Микросервисы, CLI, бэкенды на Go. Интерфейс `Client`: `Evaluate`, `IsEnabled`, `EvaluateBatch`. |
+| **Flutter/Dart Enhanced** | Flutter, Web | `Flagent.create(baseUrl: ..., config: ...)` | ✅ | ✅ (offline snapshot) | Кроссплатформенное мобильное/веб приложение. |
+| **Python** | 3.8+ | `FlagentClient(base_url=...)` (или обёртка) | ✅ | ❌ | Скрипты, ML-пайпы, серверы на Python. |
+| **Java** | JVM | `Flagent.INSTANCE.builder()` (standalone) или Spring Starter | ✅ | ❌ | Серверы на Java без Kotlin. |
+
+\* В JS Enhanced client-side evaluation можно реализовать поверх Export API и локального вычисления при необходимости; основной сценарий — server-side с кэшем.
+
+## Server-side vs client-side evaluation
+
+- **Server-side:** каждый вызов `evaluate`/`isEnabled` при необходимости идёт на сервер (или отдаётся из кэша). Актуально для серверов (Ktor, Spring Boot, Go), когда нужна централизованная логика и минимальная задержка на клиенте не критична.
+- **Client-side (offline):** SDK один раз загружает снапшот флагов (Export API или Flags API), дальше вычисляет вариант локально по правилам (constraints, rollout). Низкая задержка (<1 ms), работа без сети после bootstrap. Доступно в **Kotlin Enhanced** (`.mode(.offline)`), **Swift Enhanced** (`.mode(.offline)`), **Go Enhanced** (`opts.Offline = true`), **Flutter Enhanced**.
+
+## Real-time updates (SSE)
+
+Подписка на изменения флагов без опроса: **Kotlin Enhanced**, **Go Enhanced** поддерживают SSE; после изменения на сервере клиент получает обновления и при необходимости перезагружает снапшот или инвалидирует кэш.
+
+## Рекомендуемый способ создания клиента
+
+Во всех Enhanced SDK рекомендуется один вход:
+
+- **Kotlin:** `Flagent.builder().baseUrl(...).cache(...).mode(...).build()`
+- **JS:** `Flagent.create({ basePath, enableCache, cacheTtlMs, ... })`
+- **Swift:** `Flagent.builder().basePath(...).build()`
+- **Go:** `enhanced.NewFlagent(ctx, baseURL, enhanced.DefaultOptions())`
+- **Dart/Flutter:** `Flagent.create(baseUrl: ..., config: ...)`
+
+Прямое использование `FlagentManager` / `OfflineFlagentManager` / base API остаётся для продвинутых сценариев (кастомный кэш, тонкая настройка).
+
+## Связанные разделы
+
+- [SDKs Overview](../sdks/README.md) — установка и ссылки по каждому SDK.
+- [SDK Integration Examples](../examples/sdk-integration.md) — примеры кода по платформам.
+- [Getting Started](getting-started.md) — быстрый старт и первый флаг.
+- [Offline-First SDK](../features/offline-first-sdk.md) — детали client-side evaluation.
diff --git a/docs/sdks/README.md b/docs/sdks/README.md
index 62fa9d08..f9b6241d 100644
--- a/docs/sdks/README.md
+++ b/docs/sdks/README.md
@@ -6,21 +6,48 @@ Official client SDKs for Flagent. Use them to evaluate feature flags, run A/B te
## Overview
+### Base SDKs (OpenAPI-generated)
+
| SDK | Platforms | Install | Docs |
|-----|-----------|--------|------|
-| **Kotlin** | JVM, Android, KMP | Gradle: `com.flagent:kotlin-client` | [SDKs page](../sdk.html) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/kotlin) |
-| **JavaScript/TS** | Browser, Node.js | npm: `@flagent/sdk-js` | [SDKs page](../sdk.html) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/javascript) |
-| **Swift** | iOS, macOS | SPM / CocoaPods | [SDKs page](../sdk.html) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/swift) |
-| **Python** | 3.8+ | pip: `flagent-sdk` | [SDKs page](../sdk.html) |
-| **Go** | Go 1.18+ | `go get` | [SDKs page](../sdk.html) |
-| **Java** | JVM, Android | Maven/Gradle | [SDKs page](../sdk.html) |
-| **Dart/Flutter** | Flutter | pub.dev | [SDKs page](../sdk.html) |
+| **Kotlin** | JVM, Android, KMP | Gradle: `com.flagent:kotlin-client` | [sdk/kotlin](https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/kotlin) |
+| **JavaScript/TS** | Browser, Node.js | npm: `@flagent/sdk-js` | [sdk/javascript](https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/javascript) |
+| **Swift** | iOS, macOS | SPM / CocoaPods | [sdk/swift](https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/swift) |
+| **Python** | 3.8+ | pip: `flagent-sdk` | [sdk/python](https://github.com/MaxLuxs/Flagent/tree/main/sdk/python) |
+| **Go** | Go 1.18+ | `go get` | [sdk/go](https://github.com/MaxLuxs/Flagent/tree/main/sdk/go) |
+| **Java** | JVM, Android | Maven/Gradle | [sdk/java](https://github.com/MaxLuxs/Flagent/tree/main/sdk/java) |
+| **Dart** | Flutter, Web | pub.dev | [sdk/dart](https://github.com/MaxLuxs/Flagent/tree/main/sdk/dart) |
+
+### Enhanced SDKs (caching, offline, client-side eval where available)
+
+| SDK | Features |
+|-----|----------|
+| **Kotlin Enhanced** [sdk/kotlin-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin-enhanced) | Client-side eval, SSE real-time |
+| **JavaScript Enhanced** [sdk/javascript-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript-enhanced) | Caching, convenient API |
+| **Swift Enhanced** [sdk/swift-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift-enhanced) | Caching |
+| **Go Enhanced** [sdk/go-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/go-enhanced) | Client-side eval, SSE |
+| **Flutter Enhanced** [sdk/flutter-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/flutter-enhanced) | Caching |
+
+### Other server / DI
+
+| SDK | Description |
+|-----|-------------|
+| **flagent-koin** [sdk/flagent-koin](https://github.com/MaxLuxs/Flagent/tree/main/sdk/flagent-koin) | Koin DI module (KMP) |
+| **Spring Boot Starter** [sdk/spring-boot-starter](https://github.com/MaxLuxs/Flagent/tree/main/sdk/spring-boot-starter) | Auto-configuration for Spring Boot |
+
+### Debug UI (optional)
+
+| SDK | Platforms |
+|-----|-----------|
+| **Kotlin Debug UI** [sdk/kotlin-debug-ui](https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin-debug-ui) | Compose Multiplatform (JVM/Android/iOS) |
+| **Swift Debug UI** [sdk/swift-debug-ui](https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift-debug-ui) | SwiftUI (iOS) |
+| **JavaScript Debug UI** [sdk/javascript-debug-ui](https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript-debug-ui) | React (Web) |
Android sample (Kotlin SDK): [samples/android](https://github.com/MaxLuxs/Flagent/tree/main/samples/android).
-- **Base SDKs** — generated from OpenAPI; typed API client.
-- **Enhanced SDKs** — native implementation with caching, offline support, and simpler APIs where available.
-- **Debug UI** — optional Compose/UI libraries for local debugging (e.g. Kotlin, JS).
+## Which SDK to use
+
+See **[Which SDK to choose](../guides/sdk-selection.md)** for a table and short guide: Kotlin vs Kotlin Enhanced vs Ktor vs Spring Boot vs JS vs Swift vs Go, when to use server-side vs client-side evaluation, and recommended entry points (`Flagent.builder()`, `Flagent.create()`, `NewFlagent()`).
## Quick links
diff --git a/docs/sdks/README.ru.md b/docs/sdks/README.ru.md
index 01d7ac5f..d1e780ab 100644
--- a/docs/sdks/README.ru.md
+++ b/docs/sdks/README.ru.md
@@ -6,21 +6,48 @@
## Обзор
+### Базовые SDK (генерация из OpenAPI)
+
| SDK | Платформы | Установка | Документация |
|-----|-----------|----------|--------------|
-| **Kotlin** | JVM, Android, KMP | Gradle: `com.flagent:kotlin-client` | [SDKs](../sdk.html) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/kotlin) |
-| **JavaScript/TS** | Браузер, Node.js | npm: `@flagent/sdk-js` | [SDKs](../sdk.html) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/javascript) |
-| **Swift** | iOS, macOS | SPM / CocoaPods | [SDKs](../sdk.html) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/swift) |
-| **Python** | 3.8+ | pip: `flagent-sdk` | [SDKs](../sdk.html) |
-| **Go** | Go 1.18+ | `go get` | [SDKs](../sdk.html) |
-| **Java** | JVM, Android | Maven/Gradle | [SDKs](../sdk.html) |
-| **Dart/Flutter** | Flutter | pub.dev | [SDKs](../sdk.html) |
+| **Kotlin** | JVM, Android, KMP | Gradle: `com.flagent:kotlin-client` | [sdk/kotlin](https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/kotlin) |
+| **JavaScript/TS** | Браузер, Node.js | npm: `@flagent/sdk-js` | [sdk/javascript](https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/javascript) |
+| **Swift** | iOS, macOS | SPM / CocoaPods | [sdk/swift](https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift) · [Sample](https://github.com/MaxLuxs/Flagent/tree/main/samples/swift) |
+| **Python** | 3.8+ | pip: `flagent-sdk` | [sdk/python](https://github.com/MaxLuxs/Flagent/tree/main/sdk/python) |
+| **Go** | Go 1.18+ | `go get` | [sdk/go](https://github.com/MaxLuxs/Flagent/tree/main/sdk/go) |
+| **Java** | JVM, Android | Maven/Gradle | [sdk/java](https://github.com/MaxLuxs/Flagent/tree/main/sdk/java) |
+| **Dart** | Flutter, Web | pub.dev | [sdk/dart](https://github.com/MaxLuxs/Flagent/tree/main/sdk/dart) |
+
+### Enhanced SDK (кэш, offline, client-side eval где есть)
+
+| SDK | Возможности |
+|-----|-------------|
+| **Kotlin Enhanced** [sdk/kotlin-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin-enhanced) | Client-side eval, SSE real-time |
+| **JavaScript Enhanced** [sdk/javascript-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript-enhanced) | Кэш, удобный API |
+| **Swift Enhanced** [sdk/swift-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift-enhanced) | Кэш |
+| **Go Enhanced** [sdk/go-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/go-enhanced) | Client-side eval, SSE |
+| **Flutter Enhanced** [sdk/flutter-enhanced](https://github.com/MaxLuxs/Flagent/tree/main/sdk/flutter-enhanced) | Кэш |
+
+### Сервер / DI
+
+| SDK | Описание |
+|-----|----------|
+| **flagent-koin** [sdk/flagent-koin](https://github.com/MaxLuxs/Flagent/tree/main/sdk/flagent-koin) | Koin DI модуль (KMP) |
+| **Spring Boot Starter** [sdk/spring-boot-starter](https://github.com/MaxLuxs/Flagent/tree/main/sdk/spring-boot-starter) | Автоконфигурация для Spring Boot |
+
+### Debug UI (опционально)
+
+| SDK | Платформы |
+|-----|-----------|
+| **Kotlin Debug UI** [sdk/kotlin-debug-ui](https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin-debug-ui) | Compose Multiplatform (JVM/Android/iOS) |
+| **Swift Debug UI** [sdk/swift-debug-ui](https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift-debug-ui) | SwiftUI (iOS) |
+| **JavaScript Debug UI** [sdk/javascript-debug-ui](https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript-debug-ui) | React (Web) |
Android-пример (Kotlin): [samples/android](https://github.com/MaxLuxs/Flagent/tree/main/samples/android).
-- **Base SDK** — генерируются из OpenAPI; типизированный API-клиент.
-- **Enhanced SDK** — нативная реализация с кэшем, offline и упрощённым API где доступно.
-- **Debug UI** — опциональные библиотеки для локальной отладки (Kotlin, JS).
+## Какой SDK выбрать
+
+См. **[Какой SDK выбрать](../guides/sdk-selection.md)** — таблица и краткий гайд: Kotlin vs Kotlin Enhanced vs Ktor vs Spring Boot vs JS vs Swift vs Go, когда использовать server-side и client-side evaluation, рекомендуемые точки входа.
## Ссылки
diff --git a/docs/styles.css b/docs/styles.css
index 76198bab..57a53ae1 100644
--- a/docs/styles.css
+++ b/docs/styles.css
@@ -130,6 +130,21 @@ body::before {
align-items: center;
}
+.logo {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-xs);
+}
+
+.logo::before {
+ content: '';
+ width: 32px;
+ height: 32px;
+ border-radius: 9999px;
+ background: url("assets/flagent.png") center/contain no-repeat;
+ box-shadow: var(--shadow-md);
+}
+
.logo-text {
font-size: 1.5rem;
font-weight: 700;
diff --git a/docs/tasks/README.md b/docs/tasks/README.md
deleted file mode 100644
index 780bb703..00000000
--- a/docs/tasks/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# Task plans
-
-- **[Current status and next steps](status.md)** — what’s done, in progress, and planned.
-- **[Testing (samples & SDK)](verification-and-tests.md)** — Kotlin Debug UI, Flutter App test commands.
-- **[Unified SDK entry point](unified-sdk-entry-point.md)** — план единой точки входа (builder/facade) во всех клиентских SDK.
-- **Contribution workflow:** [Roadmap](../guides/roadmap.md), [Contributing](../guides/contributing.md).
diff --git a/docs/tasks/status.md b/docs/tasks/status.md
deleted file mode 100644
index 0c319d86..00000000
--- a/docs/tasks/status.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Current status and next steps
-
-> See [Roadmap](../guides/roadmap.md) for phases and [Contributing](../guides/contributing.md) for how to run tests and contribute.
-
-## Recent (Q1 2026)
-
-- **Experiments UI (OSS):** Variant comparison table, distribution chart, filters (All/Enabled/Disabled) on Experiments page.
-- **Core metrics:** Usage-by-client endpoint; `start`/`end` required for `/flags/{id}/usage`; tests and backend fixes.
-- **Enterprise:** Change requests (create/list/approve/reject/apply), Projects/Applications/Instances (backend + frontend: list, create, breadcrumbs).
-- **Backend tests:** E2E and load tests tagged `e2e` and excluded by default; run with `-PincludeE2E` and no Kafka. UserRepository Exposed fixes; CoreMetricsRoutes tests for missing params.
-
-## In progress
-
-- **Documentation** — roadmap lists “Documentation improvements” as in progress.
-
-## Next steps (by priority)
-
-1. **Documentation** — keep improving guides (configuration, testing, MCP, frontend UI), add or update examples where needed.
-2. **Optional: Projects polish** — filter flags by `projectId` (GET `/flags?projectId=…`), link API key to Instance for Projects (if desired).
-3. **Optional: Newsletter** — connect landing-page “Subscribe” (LandingFooter) to a backend endpoint or external provider (e.g. Mailchimp/SendGrid) when needed.
-4. **Q2+** — YAML/JSON import/export and CLI script are done; released CLI binary and more webhooks (see roadmap).
-
-## Running tests
-
-- Default: `./gradlew :backend:test` (e2e excluded).
-- With E2E: `./gradlew :backend:test -PincludeE2E`.
-- Frontend: `./gradlew :frontend:jsTest`; E2E: see [demo-data](../guides/demo-data.md).
-- Dart SDK: `cd sdk/dart && dart test`.
-- Samples & SDK (Kotlin Debug UI, Flutter App): see [Testing (samples & SDK)](verification-and-tests.md).
diff --git a/docs/tasks/unified-sdk-entry-point.md b/docs/tasks/unified-sdk-entry-point.md
deleted file mode 100644
index 1fcf0227..00000000
--- a/docs/tasks/unified-sdk-entry-point.md
+++ /dev/null
@@ -1,229 +0,0 @@
-# Единая точка входа в клиентских SDK
-
-План введения единой точки входа (builder / фасад) во всех клиентских SDK Flagent, чтобы разработчики настраивали и использовали клиент через один понятный API, без ручной сборки низкоуровневых API.
-
-## Цель
-
-- **Один конфиг** (builder или options) — baseUrl, auth, cache, режим (server-side / client-side evaluation).
-- **Один клиент** — после `build()` / `initialize()` вызывать только `evaluate()`, `isEnabled()`, при необходимости `evaluateBatch()`.
-- **Скрыть внутренние слои** — не требовать от пользователя знать про EvaluationApi, ExportApi, FlagApi, FlagentManager vs OfflineFlagentManager и т.д.
-
-## Общий контракт API (целевой)
-
-Все SDK стремятся к одному стилю:
-
-```
-1. Конфигурация (builder или options):
- - baseUrl (обязательно)
- - auth: bearer token / api key / basic (опционально)
- - cache: enabled, ttlMs (опционально)
- - mode: "server" | "offline" (client-side evaluation), опционально
- - platform: httpClientEngine / context — где нужно для KMP/Android/iOS
-
-2. Создание клиента:
- - client = Flagent.builder().baseUrl(...).auth(...).cache(...).build()
- - client.initialize() // при необходимости (офлайн bootstrap), suspend/async
-
-3. Использование:
- - client.evaluate(flagKey, entityID, entityType?, entityContext?) -> EvalResult
- - client.isEnabled(flagKey, entityID, context?) -> Boolean // удобный обёртка
- - client.evaluateBatch(flagKeys, entities) -> List
// где есть batch
-```
-
-Имена классов и методов могут отличаться по языку (Flagent / FlagentClient, builder / options), но смысл один.
-
----
-
-## Какие SDK затрагиваем
-
-| SDK | Где живёт | Сейчас | Нужна единая точка входа |
-|-----|-----------|--------|---------------------------|
-| **Kotlin (KMP)** | kotlin-client + kotlin-enhanced | EvaluationApi → FlagentManager или ExportApi+FlagApi → OfflineFlagentManager | ✅ Да (приоритет 1) |
-| **JavaScript/TypeScript** | sdk/javascript + sdk/javascript-enhanced | Configuration → FlagentManager | ✅ Да |
-| **Swift** | sdk/swift + sdk/swift-enhanced | FlagentConfig → FlagentManager | ✅ Да |
-| **Go** | sdk/go + sdk/go-enhanced | NewClient + NewOfflineManager / NewManager | ✅ Да |
-| **Dart/Flutter** | sdk/dart + sdk/flutter-enhanced | FlagentManager(baseUrl, config) | ✅ Да (уже близко) |
-| **Java** | sdk/java + spring-boot-starter | ApiClient + EvaluationApi; Spring — FlagentEvaluationFacade | ⚪ Опционально (серверный) |
-| **Python** | sdk/python | Генерация из OpenAPI | ⚪ По желанию (часто серверный) |
-
-Debug UI (kotlin-debug-ui, swift-debug-ui, javascript-debug-ui) и flagent-koin не меняем — они потребляют уже созданный клиент/менеджер.
-
----
-
-## План по этапам
-
-### Этап 1: Kotlin (KMP) — kotlin-enhanced
-
-**Зачем первым:** основной SDK в репозитории, Android/sample-kotlin, есть и server-side, и client-side evaluation.
-
-**Шаги:**
-
-1. **Ввести фасад и билдер в kotlin-enhanced**
- - Добавить объект/класс `Flagent` (или `FlagentClient`) с методом `builder()`.
- - `Flagent.Builder`: цепочка методов `baseUrl()`, `httpClientEngine()`, `auth {}`, `cache(enable, ttlMs)`, `offlineSupport(Boolean)` / `mode(FlagentMode.SERVER | OFFLINE)`, `build()`.
- - Внутри `build()`: при server — создавать EvaluationApi + FlagentManager; при offline — ExportApi + FlagApi + OfflineFlagentManager. Возвращать общий интерфейс (например, `FlagentClient` с методами `evaluate`, `isEnabled`, `evaluateBatch`).
-
-2. **Общий интерфейс клиента**
- - Определить интерфейс (например, `FlagentClient`) с методами: `suspend fun evaluate(...)`, `suspend fun isEnabled(...)`, `suspend fun evaluateBatch(...)`.
- - Реализации: текущий FlagentManager и OfflineFlagentManager обернуть в адаптеры к этому интерфейсу (или привести их к одному интерфейсу, если сигнатуры совпадают).
-
-3. **Расширить FlagentConfig**
- - При необходимости добавить в FlagentConfig (или в builder) поля: offlineSupport, auth (если не через отдельный блок). Не дублировать лишнее — builder может принимать существующий FlagentConfig и дополнять его.
-
-4. **Документация и примеры**
- - Обновить README kotlin-enhanced: "Рекомендуемый способ — Flagent.builder()...".
- - Обновить sample-kotlin и android-sample: перейти на Flagent.builder() вместо ручного EvaluationApi + FlagentManager.
- - В README оставить старый способ как "продвинутый" (прямое использование FlagentManager/OfflineFlagentManager).
-
-5. **Обратная совместимость**
- - FlagentManager и OfflineFlagentManager оставить публичными; фасад только добавляется. Koin-модуль при желании можно доработать под создание через Flagent.builder() позже.
-
-**Результат этапа 1:** приложение может писать только `Flagent.builder().baseUrl(...).cache(true).build()` и вызывать `evaluate` / `isEnabled`, без знания про EvaluationApi и типов менеджеров.
-
----
-
-### Этап 2: JavaScript/TypeScript
-
-**Где:** `sdk/javascript` (base client), `sdk/javascript-enhanced` (FlagentManager, кэш).
-
-**Шаги:**
-
-1. **Единая точка входа в @flagent/enhanced-client**
- - Экспорт: `Flagent.create(options)` или `Flagent.initialize(options)`.
- - Options: `basePath`, `cacheTtlMs`, `enableCache`, опционально `offline` / `clientSideEvaluation`, auth (headers или callback). По возможности один тип `FlagentOptions`.
-
-2. **Один клиентский объект**
- - Возвращать объект с методами: `evaluate(...)`, `isEnabled(...)`, `evaluateBatch(...)`.
- - Внутри при `offline: true` использовать client-side evaluation (если уже есть в JS enhanced); иначе — текущий FlagentManager поверх base client.
-
-3. **Документация**
- - README javascript-enhanced: основной пример через `Flagent.create(...)`; старый способ с `new FlagentManager(config, ...)` оставить как альтернатива.
-
-4. **Семплы**
- - Обновить примеры и React Native snippet в README/REACT_NATIVE.md под новый вход.
-
-**Результат:** веб/React Native инициализируют один раз через `Flagent.create({ basePath, cache: {...} })` и дальше только `evaluate` / `isEnabled`.
-
----
-
-### Этап 3: Swift
-
-**Где:** `sdk/swift`, `sdk/swift-enhanced`.
-
-**Шаги:**
-
-1. **Builder или единый конфиг**
- - В swift-enhanced добавить, например, `FlagentClient.Builder` или статический `FlagentClient.create(config: FlagentConfig)` с расширенным `FlagentConfig`: baseURL, cache, auth, режим offline/client-side.
-
-2. **Единый тип клиента**
- - Один тип (например, `FlagentClient`) с методами `evaluate(...)`, `isEnabled(...)`, `evaluateBatch(...)`.
- - Внутри — обёртка над текущим FlagentManager или offline-менеджером, в зависимости от конфига.
-
-3. **Документация**
- - README swift-enhanced: рекомендуемый путь — создание через builder/create; старый способ оставить.
-
-**Результат:** iOS/macOS приложение настраивает клиент одним вызовом и использует только evaluate/isEnabled.
-
----
-
-### Этап 4: Go
-
-**Где:** `sdk/go`, `sdk/go-enhanced`.
-
-**Шаги:**
-
-1. **Функция-конструктор с опциями**
- - Например, `enhanced.NewFlagent(ctx, baseURL, enhanced.Options{...})` или `flagent.New(ctx, flagent.Config{...})`.
- - Options: BaseURL, Cache TTL, Offline/ClientSideEvaluation, HTTP client, auth.
-
-2. **Единый интерфейс**
- - Интерфейс с методами `Evaluate`, `IsEnabled`, `EvaluateBatch`.
- - Реализации: текущий manager и offline manager приводятся к этому интерфейсу; конструктор возвращает интерфейс.
-
-3. **Документация и примеры**
- - README go-enhanced: основной пример через новый конструктор; старый способ оставить.
-
-**Результат:** сервисы на Go создают клиент одним вызовом и работают через общий интерфейс.
-
----
-
-### Этап 5: Dart/Flutter
-
-**Где:** `sdk/dart`, `sdk/flutter-enhanced`.
-
-**Текущее состояние:** уже есть `FlagentManager(baseUrl, config)` — один конструктор с конфигом.
-
-**Шаги:**
-
-1. **Привести к общему стилю**
- - Добавить именованный конструктор или фасад, например `Flagent.managed(baseUrl, config)` или `Flagent.create({ required baseUrl, cache, ... })`, возвращающий тот же FlagentManager, чтобы документация и примеры во всех SDK говорили одно и то же ("создаёте через Flagent.create / builder").
-
-2. **Опционально: isEnabled**
- - Убедиться, что есть удобный метод вида `isEnabled(flagKey, entityID, context)` поверх evaluate.
-
-3. **Документация**
- - README: "Рекомендуемый способ: Flagent.create(...)" и один блок кода в начале.
-
-**Результат:** Flutter-разработчик видит тот же паттерн, что и в Kotlin/JS/Swift.
-
----
-
-### Этап 6 (опционально): Java
-
-**Где:** `sdk/java`, `sdk/spring-boot-starter`.
-
-**Особенность:** в основном серверный сценарий; Spring уже даёт FlagentEvaluationFacade и конфиг через `application.yml`.
-
-**Шаги (по желанию):**
-
-1. **Фасад для standalone Java**
- - Класс `Flagent` или `FlagentClient` с билдером: baseUrl, auth, cache settings; `build()` возвращает объект с методами `evaluate`, `evaluateBatch` (и при необходимости `isEnabled`).
- - Внутри — существующие ApiClient и EvaluationApi.
-
-2. **Spring**
- - Оставить как есть; при необходимости в доке указать: "Для Spring используйте starter; для standalone — Flagent.builder()".
-
-**Результат:** единообразие с другими SDK при использовании без Spring.
-
----
-
-### Этап 7 (опционально): Python
-
-**Где:** `sdk/python` (генерируется из OpenAPI).
-
-**Шаги (если решим делать единый вход):**
-
-1. Тонкая обёртка в отдельном модуле или в том же пакете: функция `create_client(base_url, ...)` с опциями кэша и auth, возвращающая объект с `evaluate`, `evaluate_batch`.
-2. Внутри — сгенерированный client + простой кэш при необходимости.
-3. README: один рекомендуемый пример через эту обёртку.
-
----
-
-## Порядок выполнения (сводка)
-
-| Приоритет | SDK | Действие |
-|-----------|-----|----------|
-| 1 | Kotlin (kotlin-enhanced) | Фасад Flagent + Builder, интерфейс FlagentClient, обновить samples и README |
-| 2 | JavaScript/TypeScript | Flagent.create() в enhanced-client, один объект с evaluate/isEnabled/evaluateBatch |
-| 3 | Swift | Builder/create в swift-enhanced, единый FlagentClient |
-| 4 | Go | NewFlagent(options), интерфейс Evaluate/IsEnabled/EvaluateBatch |
-| 5 | Dart/Flutter | Flagent.create() / Flagent.managed() в документации и API, проверить isEnabled |
-| 6 | Java | По желанию: Flagent.builder() для standalone |
-| 7 | Python | По желанию: create_client() обёртка |
-
----
-
-## Критерии готовности
-
-- В каждом целевом SDK есть один рекомендуемый способ создать клиент (builder / create / options).
-- Документация и основной пример в README используют этот способ.
-- Методы evaluate и isEnabled (или эквивалент) доступны без знания внутренних API (EvaluationApi, ExportApi и т.д.).
-- Обратная совместимость: старый способ (прямое использование manager/base API) по-прежнему работает и при необходимости описан как "продвинутый".
-
----
-
-## Связанные документы
-
-- [Текущий статус и следующие шаги](status.md)
-- [Тестирование и верификация](verification-and-tests.md)
-- README по каждому SDK в `sdk//README.md`
diff --git a/docs/tasks/verification-and-tests.md b/docs/tasks/verification-and-tests.md
deleted file mode 100644
index a32934de..00000000
--- a/docs/tasks/verification-and-tests.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# Testing (samples & SDK)
-
-See [Current status](status.md) for backend/frontend test commands and [Contributing](../guides/contributing.md) for full workflow.
-
-## Sample and SDK tests
-
-| Component | Test command | Notes |
-|------------------|--------------|--------|
-| **Kotlin client (KMP)** | `./gradlew :kotlin-client:jvmTest` | API client; регенерация: `sdk/kotlin/generate.sh`, см. [CODEGEN](../../sdk/kotlin/CODEGEN.md). Отчёт покрытия: `:kotlin-client:jacocoTestReport` (HTML в `sdk/kotlin/build/reports/jacoco/jacocoTestReport/html/`). Проверка покрытия ≥85%: `./gradlew :kotlin-client:jacocoCoverageVerification`. |
-| **Kotlin Debug UI** | `./gradlew :kotlin-debug-ui:jvmTest` | Compose Multiplatform (JVM/Android/iOS). |
-| **Flutter App** | `cd samples/flutter_app && flutter pub get && flutter test` | Requires Flutter SDK. |
-
-## Quick commands
-
-```bash
-# Kotlin API client (KMP)
-./gradlew :kotlin-client:jvmTest
-
-# Kotlin Debug UI
-./gradlew :kotlin-debug-ui:jvmTest
-
-# Flutter App sample
-cd samples/flutter_app && flutter pub get && flutter test
-```
diff --git a/frontend/e2e/playwright.config.ts b/frontend/e2e/playwright.config.ts
index a8095078..0343340b 100644
--- a/frontend/e2e/playwright.config.ts
+++ b/frontend/e2e/playwright.config.ts
@@ -72,7 +72,7 @@ export default defineConfig({
cwd: '../..',
url: `${BACKEND_URL}/api/v1/health`,
timeout: 180_000,
- reuseExistingServer: false,
+ reuseExistingServer: true,
env: {
...process.env,
FLAGENT_EVALCACHE_REFRESHINTERVAL: '100ms',
diff --git a/frontend/e2e/tests/analytics.spec.ts b/frontend/e2e/tests/analytics.spec.ts
index dda7ad5c..629f56bc 100644
--- a/frontend/e2e/tests/analytics.spec.ts
+++ b/frontend/e2e/tests/analytics.spec.ts
@@ -53,13 +53,31 @@ test.describe('Analytics Page with seeded data @oss', () => {
await page.goto('/analytics');
await page.waitForLoadState('domcontentloaded');
- await expect(
- page.getByText(/Total evaluations|Всего оценок/i)
- ).toBeVisible({ timeout: 10000 });
- await expect(
- page.getByText(/Unique flags|Уникальных флагов/i)
- ).toBeVisible({ timeout: 10000 });
- await expect(page.getByText(/\d+/).first()).toBeVisible({ timeout: 5000 });
+ const overviewTab = page.getByRole('button', {
+ name: /Overview|Обзор/i,
+ });
+ if ((await overviewTab.count()) > 0) {
+ await overviewTab.click();
+ }
+
+ const totalLabel = page.getByText(/Total evaluations|Всего оценок/i);
+ const overviewEmptyHint = page.getByText(
+ /This tab shows evaluation metrics|Здесь — метрики по оценкам флагов|Go to Events|Перейти к событиям/i
+ );
+
+ // Either metrics cards are shown, or the "no evaluations yet" hint is visible.
+ await expect(totalLabel.or(overviewEmptyHint).first()).toBeVisible({
+ timeout: 15000,
+ });
+
+ if ((await totalLabel.count()) > 0) {
+ await expect(
+ page.getByText(/Unique flags|Уникальных флагов/i)
+ ).toBeVisible({ timeout: 10000 });
+ await expect(page.getByText(/\d+/).first()).toBeVisible({
+ timeout: 5000,
+ });
+ }
});
test('Overview tab shows time series chart when data exists', async ({
@@ -74,10 +92,28 @@ test.describe('Analytics Page with seeded data @oss', () => {
await page.goto('/analytics');
await page.waitForLoadState('domcontentloaded');
- await expect(page.getByText(/Total evaluations|Всего оценок/i)).toBeVisible({
+
+ const overviewTab = page.getByRole('button', {
+ name: /Overview|Обзор/i,
+ });
+ if ((await overviewTab.count()) > 0) {
+ await overviewTab.click();
+ }
+
+ const totalLabel = page.getByText(/Total evaluations|Всего оценок/i);
+ const overviewEmptyHint = page.getByText(
+ /This tab shows evaluation metrics|Здесь — метрики по оценкам флагов|Go to Events|Перейти к событиям/i
+ );
+
+ await expect(totalLabel.or(overviewEmptyHint).first()).toBeVisible({
timeout: 15000,
});
+ if ((await totalLabel.count()) === 0) {
+ // Overview has no data; nothing to assert about chart.
+ return;
+ }
+
const chartTitle = page.getByText(
/Evaluations over time|Оценки за период|evaluations/i
);
@@ -93,10 +129,28 @@ test.describe('Analytics Page with seeded data @oss', () => {
await page.goto('/analytics');
await page.waitForLoadState('domcontentloaded');
- await expect(page.getByText(/Total evaluations|Всего оценок/i)).toBeVisible({
+
+ const overviewTab = page.getByRole('button', {
+ name: /Overview|Обзор/i,
+ });
+ if ((await overviewTab.count()) > 0) {
+ await overviewTab.click();
+ }
+
+ const totalLabel = page.getByText(/Total evaluations|Всего оценок/i);
+ const overviewEmptyHint = page.getByText(
+ /This tab shows evaluation metrics|Здесь — метрики по оценкам флагов|Go to Events|Перейти к событиям/i
+ );
+
+ await expect(totalLabel.or(overviewEmptyHint).first()).toBeVisible({
timeout: 15000,
});
+ if ((await totalLabel.count()) === 0) {
+ // No metrics cards, so no "top flags" section either.
+ return;
+ }
+
const topFlagsHeading = page.getByText(
/Top flags by evaluations|Топ флагов по оценкам|evaluations/i
);
diff --git a/frontend/e2e/tests/flag-editor.spec.ts b/frontend/e2e/tests/flag-editor.spec.ts
index e79f6a6f..a4c69aee 100644
--- a/frontend/e2e/tests/flag-editor.spec.ts
+++ b/frontend/e2e/tests/flag-editor.spec.ts
@@ -41,17 +41,15 @@ test.describe('Flag Editor - Full Flow @oss', () => {
await firstRow.click();
await page.waitForLoadState('domcontentloaded');
- // Use checkbox near Enabled/Disabled label (avoids DebugConsole/other checkboxes)
- const enabledSwitch = page
- .locator('label')
- .filter({ hasText: /Enabled|Disabled/ })
- .locator('input[type="checkbox"]')
- .first();
+ // New FlagEditor uses ARIA switch instead of checkbox
+ const enabledSwitch = page.getByRole('switch').first();
await expect(enabledSwitch).toBeVisible({ timeout: 5000 });
- const wasChecked = await enabledSwitch.isChecked();
+ const wasChecked = (await enabledSwitch.getAttribute('aria-checked')) === 'true';
await enabledSwitch.click();
- // Wait for API to complete and UI to update (checkbox is controlled by server state)
- await expect(enabledSwitch).toBeChecked({ checked: !wasChecked, timeout: 10000 });
+ // Wait for API to complete and UI to update (switch is controlled by server state)
+ await expect(enabledSwitch).toHaveAttribute('aria-checked', wasChecked ? 'false' : 'true', {
+ timeout: 10000,
+ });
});
test('can edit description and save', async ({ page }) => {
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/api/ApiClient.kt b/frontend/src/jsMain/kotlin/flagent/frontend/api/ApiClient.kt
index f37c7e51..ddccb7c8 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/api/ApiClient.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/api/ApiClient.kt
@@ -105,6 +105,9 @@ object ApiClient {
val base = AppConfig.apiBaseUrl.trimEnd('/')
return if (base.isEmpty()) path else "$base$path"
}
+
+ /** Public path for newsletter (no API key). */
+ internal fun getNewsletterPath(): String = getAuthPath("/newsletter")
private fun getApiKey(): String? {
(js("window.ENV_API_KEY") as? String)?.takeIf { it.isNotBlank() }?.let { return it }
@@ -690,6 +693,18 @@ object ApiClient {
return client.post(getAdminPath("/users/$id/unblock")).body()
}
+ // ========== Newsletter (public, no API key) ==========
+
+ /**
+ * Subscribe email to newsletter. On success returns; on 4xx/5xx throws (error message in exception).
+ */
+ suspend fun subscribeNewsletter(email: String) {
+ client.post(getNewsletterPath()) {
+ contentType(ContentType.Application.Json)
+ setBody(mapOf("email" to email))
+ }
+ }
+
// ========== Metrics overview (global aggregates) ==========
/**
@@ -789,6 +804,20 @@ object ApiClient {
}
return client.get(url).body()
}
+
+ // ========== Integrations (Firebase) ==========
+
+ /**
+ * Get Firebase integration status (Remote Config sync + Analytics).
+ * Admin-only route protected by JWT or Admin API key.
+ */
+ suspend fun getFirebaseStatus(): FirebaseStatusResponse {
+ return client.get(getAdminPath("/integrations/firebase/status")) {
+ if (getAuthToken() == null) {
+ getAdminApiKey()?.let { header(ADMIN_API_KEY_HEADER, it) }
+ }
+ }.body()
+ }
}
@Serializable
@@ -855,3 +884,25 @@ data class ApplicationCreateRequest(val name: String, val key: String, val platf
@Serializable
data class InstanceCreateRequest(val environmentId: Long, val name: String)
+
+@Serializable
+data class FirebaseRcStatusResponse(
+ val enabled: Boolean,
+ val projectId: String? = null,
+ val syncIntervalSeconds: Long,
+ val parameterPrefix: String,
+ val hasCredentials: Boolean
+)
+
+@Serializable
+data class FirebaseAnalyticsStatusResponse(
+ val enabled: Boolean,
+ val measurementId: String? = null,
+ val hasApiSecret: Boolean
+)
+
+@Serializable
+data class FirebaseStatusResponse(
+ val firebaseRc: FirebaseRcStatusResponse,
+ val firebaseAnalytics: FirebaseAnalyticsStatusResponse
+)
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/App.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/App.kt
index e16377df..58e1096c 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/App.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/App.kt
@@ -4,6 +4,7 @@ import androidx.compose.runtime.*
import flagent.frontend.components.auth.LoginForm
import flagent.frontend.components.common.NotificationToast
import flagent.frontend.components.landing.BlogPage
+import flagent.frontend.components.landing.LandingBackgroundShapes
import flagent.frontend.components.landing.MarketingLanding
import flagent.frontend.components.landing.PricingPage
import flagent.frontend.config.AppConfig
@@ -13,6 +14,7 @@ import flagent.frontend.state.BackendOnboardingState
import flagent.frontend.state.GlobalState
import flagent.frontend.state.LocalGlobalState
import flagent.frontend.state.LocalThemeMode
+import flagent.frontend.state.ThemeMode
import flagent.frontend.state.ThemeState
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.util.AppLogger
@@ -109,8 +111,8 @@ fun App() {
is Route.Settings -> Route.Settings.PATH
is Route.Tenants -> Route.Tenants.PATH
is Route.Projects -> Route.Projects.PATH
- is Route.ProjectDetail -> (route as Route.ProjectDetail).path()
- is Route.ApplicationDetail -> (route as Route.ApplicationDetail).path()
+ is Route.ProjectDetail -> route.path()
+ is Route.ApplicationDetail -> route.path()
is Route.Login -> Route.Home.PATH
}
sessionStorage.setItem(AUTH_RETURN_URL_KEY, returnPath)
@@ -169,9 +171,20 @@ private fun AppShell(
style {
property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif")
minHeight(100.vh)
- backgroundColor(FlagentTheme.contentBg(themeMode))
+ if (AppConfig.showMarketingLanding) {
+ property("background", FlagentTheme.heroGradient(themeMode))
+ if (themeMode == ThemeMode.Dark) {
+ property("background-size", "400% 400%")
+ property("animation", "morphGradient 20s ease infinite")
+ }
+ } else {
+ backgroundColor(FlagentTheme.contentBg(themeMode))
+ }
}
}) {
+ if (AppConfig.showMarketingLanding) {
+ LandingBackgroundShapes(themeMode)
+ }
NotificationToast(
notifications = globalState.notifications,
onDismiss = { id -> globalState.removeNotification(id) }
@@ -185,7 +198,7 @@ private fun AppShell(
when (val r = Router.currentRoute) {
is Route.Home -> LandingPage()
is Route.FlagsList -> FlagsList()
- is Route.Dashboard -> Dashboard()
+ is Route.Dashboard -> Dashboard(tenantViewModel = vm)
is Route.Experiments -> flagent.frontend.components.experiments.ExperimentsPage()
is Route.Segments -> flagent.frontend.components.segments.SegmentsPage()
is Route.Analytics -> flagent.frontend.components.analytics.AnalyticsPage()
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/CommandBar.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/CommandBar.kt
index ee48cb37..756ea3a8 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/CommandBar.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/CommandBar.kt
@@ -94,24 +94,22 @@ fun CommandBar(
val filteredFlags = if (hasQuery) {
val q = query.lowercase().trim()
flagItems.filter {
- it is CommandBarItem.Flag && (
- it.flag.key.lowercase().contains(q) ||
- it.flag.description.lowercase().contains(q)
- )
+ it.flag.key.lowercase().contains(q) ||
+ it.flag.description.lowercase().contains(q)
}
} else emptyList()
val filteredNav = if (hasQuery) {
val q = query.lowercase().trim()
navItems.filter {
- it is CommandBarItem.Nav && it.label.lowercase().contains(q)
+ it.label.lowercase().contains(q)
}
} else navItems
val filteredActions = if (hasQuery) {
val q = query.lowercase().trim()
quickActions.filter {
- it is CommandBarItem.Action && it.label.lowercase().contains(q)
+ it.label.lowercase().contains(q)
}
} else quickActions
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/Dashboard.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/Dashboard.kt
index f2e5207e..e64b1087 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/Dashboard.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/Dashboard.kt
@@ -3,11 +3,15 @@ package flagent.frontend.components
import androidx.compose.runtime.*
import flagent.api.model.FlagResponse
import flagent.frontend.api.ApiClient
+import flagent.frontend.api.AlertSeverity
+import flagent.frontend.api.CrashListResponse
import flagent.frontend.config.AppConfig
import flagent.frontend.api.GlobalMetricsOverviewResponse
import flagent.frontend.components.dashboard.ActivityChart
import flagent.frontend.components.dashboard.StatusDistributionChart
import flagent.frontend.components.dashboard.StatusSlice
+import flagent.frontend.components.dashboard.TopFlagsBarChart
+import flagent.frontend.i18n.LocalizedStrings
import flagent.frontend.navigation.Route
import flagent.frontend.navigation.Router
import flagent.frontend.state.BackendOnboardingState
@@ -16,7 +20,9 @@ import flagent.frontend.state.ThemeMode
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.util.AppLogger
import flagent.frontend.util.ErrorHandler
+import flagent.frontend.util.currentTimeMillis
import flagent.frontend.viewmodel.AnomalyViewModel
+import flagent.frontend.viewmodel.TenantViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import org.jetbrains.compose.web.css.*
@@ -33,21 +39,27 @@ private enum class MetricsPeriod(val rangeMs: Long, val bucketMs: Long) {
* Dashboard - главная страница с общей статистикой
*/
@Composable
-fun Dashboard() {
+fun Dashboard(tenantViewModel: TenantViewModel? = null) {
val themeMode = LocalThemeMode.current
var stats by remember { mutableStateOf(null) }
var flags by remember { mutableStateOf>(emptyList()) }
var metricsOverview by remember { mutableStateOf(null) }
var metricsLoadError by remember { mutableStateOf(null) }
var metricsPeriod by remember { mutableStateOf(MetricsPeriod.P24H) }
+ var metricsRefreshTrigger by remember { mutableStateOf(0) }
+ var isMetricsLoading by remember { mutableStateOf(false) }
+ var lastFlagsRefreshMs by remember { mutableStateOf(null) }
+ var lastMetricsRefreshMs by remember { mutableStateOf(null) }
var isLoading by remember { mutableStateOf(true) }
var error by remember { mutableStateOf(null) }
+ var refreshTrigger by remember { mutableStateOf(0) }
+ var crashOverview by remember { mutableStateOf(null) }
val anomalyViewModel = if (AppConfig.Features.enableAnomalyDetection) {
remember { AnomalyViewModel() }
} else null
- LaunchedEffect(Unit) {
+ LaunchedEffect(Unit, refreshTrigger) {
isLoading = true
error = null
metricsLoadError = null
@@ -55,7 +67,8 @@ fun Dashboard() {
block = {
coroutineScope {
val flagsDeferred = async {
- val (loadedFlags, _) = ApiClient.getFlags()
+ // preload=true нужен для подсчёта flagsWithSegments / flagsWithVariants на дашборде
+ val (loadedFlags, _) = ApiClient.getFlags(preload = true)
loadedFlags
}
val alertsDeferred = anomalyViewModel?.let { vm -> async { vm.loadUnresolvedAlerts() } }
@@ -69,6 +82,7 @@ fun Dashboard() {
flagsWithSegments = loadedFlags.count { it.segments.isNotEmpty() },
flagsWithVariants = loadedFlags.count { it.variants.isNotEmpty() }
)
+ lastFlagsRefreshMs = currentTimeMillis()
alertsDeferred?.await()
}
},
@@ -80,8 +94,9 @@ fun Dashboard() {
isLoading = false
}
- LaunchedEffect(metricsPeriod) {
+ LaunchedEffect(metricsPeriod, metricsRefreshTrigger) {
if (!AppConfig.Features.enableMetrics) return@LaunchedEffect
+ isMetricsLoading = true
metricsLoadError = null
try {
val end = kotlin.js.Date().getTime().toLong()
@@ -92,9 +107,23 @@ fun Dashboard() {
topLimit = 10,
timeBucketMs = metricsPeriod.bucketMs
)
+ lastMetricsRefreshMs = currentTimeMillis()
} catch (e: Throwable) {
metricsLoadError = ErrorHandler.getUserMessage(ErrorHandler.handle(e, null))
metricsOverview = null
+ } finally {
+ isMetricsLoading = false
+ }
+ }
+
+ LaunchedEffect(Unit) {
+ if (!AppConfig.Features.enableCrashAnalytics) return@LaunchedEffect
+ try {
+ val end = kotlin.js.Date().getTime().toLong()
+ val start = end - 86400_000L
+ crashOverview = ApiClient.getCrashes(startTime = start, endTime = end, limit = 5)
+ } catch (_: Throwable) {
+ crashOverview = null
}
}
@@ -103,31 +132,7 @@ fun Dashboard() {
padding(0.px)
}
}) {
- Div({
- style {
- marginBottom(16.px)
- }
- }) {
- H1({
- style {
- fontSize(24.px)
- fontWeight("bold")
- color(FlagentTheme.text(themeMode))
- margin(0.px)
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.dashboardNav)
- }
- P({
- style {
- color(FlagentTheme.textLight(themeMode))
- fontSize(14.px)
- marginTop(4.px)
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.dashboardOverview)
- }
- }
+ DashboardHeader(themeMode, tenantViewModel?.currentTenant?.name, lastFlagsRefreshMs)
if (isLoading) {
Div({
@@ -137,7 +142,7 @@ fun Dashboard() {
color(FlagentTheme.textLight(themeMode))
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.loading)
+ Text(LocalizedStrings.loading)
}
} else if (error != null) {
val isTenantOrApiKeyError = error!!.contains("tenant", ignoreCase = true) ||
@@ -153,16 +158,32 @@ fun Dashboard() {
}
}) {
Text(error!!)
- if (isTenantOrApiKeyError) {
- P({
+ P({
+ style {
+ marginTop(10.px)
+ fontSize(14.px)
+ display(DisplayStyle.Flex)
+ gap(12.px)
+ flexWrap(FlexWrap.Wrap)
+ alignItems(AlignItems.Center)
+ }
+ }) {
+ Button({
style {
- marginTop(10.px)
+ color(FlagentTheme.errorText(themeMode))
+ textDecoration("underline")
+ fontWeight("600")
+ backgroundColor(Color("transparent"))
+ border(0.px)
+ cursor("pointer")
+ padding(0.px)
fontSize(14.px)
- display(DisplayStyle.Flex)
- gap(12.px)
- flexWrap(FlexWrap.Wrap)
}
+ onClick { refreshTrigger++ }
}) {
+ Text(LocalizedStrings.retry)
+ }
+ if (isTenantOrApiKeyError) {
Button({
style {
color(FlagentTheme.errorText(themeMode))
@@ -176,7 +197,7 @@ fun Dashboard() {
}
onClick { Router.navigateToTenantsWithCreate() }
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.createFirstTenant)
+ Text(LocalizedStrings.createFirstTenant)
}
Button({
style {
@@ -191,7 +212,7 @@ fun Dashboard() {
}
onClick { Router.navigateTo(Route.Login) }
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.logInAdmin)
+ Text(LocalizedStrings.logInAdmin)
}
}
}
@@ -214,7 +235,7 @@ fun Dashboard() {
marginBottom(16.px)
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.createFirstFlag)
+ Text(LocalizedStrings.createFirstFlag)
}
Button({
style {
@@ -229,65 +250,29 @@ fun Dashboard() {
}
onClick { Router.navigateTo(Route.CreateFlag) }
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.createFlag)
+ Text(LocalizedStrings.createFlag)
}
}
} else {
- // Stats Cards
- Div({
- style {
- display(DisplayStyle.Grid)
- property("grid-template-columns", "repeat(auto-fit, minmax(160px, 1fr))")
- gap(16.px)
- marginBottom(16.px)
- }
- }) {
- StatCard(themeMode, flagent.frontend.i18n.LocalizedStrings.totalFlagsStat, stats!!.totalFlags.toString(), "flag", FlagentTheme.Primary)
- StatCard(themeMode, flagent.frontend.i18n.LocalizedStrings.enabled, stats!!.enabledFlags.toString(), "check_circle", FlagentTheme.Success)
- StatCard(themeMode, flagent.frontend.i18n.LocalizedStrings.disabled, stats!!.disabledFlags.toString(), "cancel", FlagentTheme.Error)
- StatCard(themeMode, flagent.frontend.i18n.LocalizedStrings.withSegmentsStat, stats!!.flagsWithSegments.toString(), "dashboard", FlagentTheme.Secondary)
- StatCard(themeMode, flagent.frontend.i18n.LocalizedStrings.experimentsTitle, stats!!.flagsWithVariants.toString(), "science", FlagentTheme.Secondary)
- }
-
- // Quick links: Experiments, Analytics
- val experimentsCount = stats!!.flagsWithVariants
- Div({
- style {
- display(DisplayStyle.Grid)
- property("grid-template-columns", "repeat(auto-fit, minmax(160px, 1fr))")
- gap(16.px)
- marginBottom(16.px)
- }
- }) {
- QuickLinkCard(
- themeMode,
- title = flagent.frontend.i18n.LocalizedStrings.experimentsTitle,
- value = experimentsCount.toString(),
- icon = "science",
- color = FlagentTheme.Secondary,
- onClick = { Router.navigateTo(Route.Experiments) }
- )
- QuickLinkCard(
- themeMode,
- title = flagent.frontend.i18n.LocalizedStrings.segments,
- value = (stats?.flagsWithSegments ?: 0).toString(),
- icon = "segment",
- color = FlagentTheme.Primary,
- onClick = { Router.navigateTo(Route.Segments) }
- )
- QuickLinkCard(
- themeMode,
- title = flagent.frontend.i18n.LocalizedStrings.analyticsTitle,
- value = flagent.frontend.i18n.LocalizedStrings.viewMetrics,
- icon = "analytics",
- color = FlagentTheme.Primary,
- onClick = { Router.navigateTo(Route.Analytics) }
- )
- }
+ val s = stats!!
+ StatsRow(themeMode, s)
+ QuickLinksRow(themeMode, s)
// Metrics section: error message or charts
if (AppConfig.Features.enableMetrics) {
- if (metricsLoadError != null && metricsOverview == null) {
+ if (isMetricsLoading && metricsOverview == null && metricsLoadError == null) {
+ Div({
+ style {
+ padding(24.px)
+ textAlign("center")
+ color(FlagentTheme.textLight(themeMode))
+ fontSize(14.px)
+ marginBottom(16.px)
+ }
+ }) {
+ Text(LocalizedStrings.loading)
+ }
+ } else if (metricsLoadError != null && metricsOverview == null) {
Div({
style {
padding(16.px)
@@ -295,79 +280,132 @@ fun Dashboard() {
borderRadius(8.px)
marginBottom(16.px)
property("border", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ display(DisplayStyle.Flex)
+ flexDirection(FlexDirection.Column)
+ gap(8.px)
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.metricsUnavailable + ": " + metricsLoadError)
+ Text(LocalizedStrings.metricsUnavailable + ": " + metricsLoadError!!)
+ Button({
+ style {
+ padding(6.px, 12.px)
+ fontSize(14.px)
+ cursor("pointer")
+ alignSelf(AlignSelf.FlexStart)
+ }
+ onClick { metricsRefreshTrigger++ }
+ }) {
+ Text(LocalizedStrings.retry)
+ }
}
} else if (metricsOverview != null) {
val overview = metricsOverview!!
- if (overview.timeSeries.isNotEmpty()) {
+ // Always show metrics card (header + period selector); charts or empty state inside
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(16.px)
+ property("box-shadow", FlagentTheme.ShadowCard)
+ property("border", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ marginBottom(20.px)
+ }
+ }) {
Div({
style {
- backgroundColor(FlagentTheme.cardBg(themeMode))
- borderRadius(8.px)
- padding(16.px)
- property("box-shadow", FlagentTheme.ShadowCard)
- property("border", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
- marginBottom(20.px)
+ display(DisplayStyle.Flex)
+ justifyContent(JustifyContent.SpaceBetween)
+ alignItems(AlignItems.Center)
+ marginBottom(12.px)
+ flexWrap(org.jetbrains.compose.web.css.FlexWrap.Wrap)
+ gap(8.px)
}
}) {
+ Span({
+ style {
+ fontSize(14.px)
+ color(FlagentTheme.textLight(themeMode))
+ }
+ }) {
+ Text("${LocalizedStrings.totalEvaluationsLabel}: ${overview.totalEvaluations} · ${LocalizedStrings.uniqueFlagsLabel}: ${overview.uniqueFlags}")
+ lastMetricsRefreshMs?.let { ts ->
+ val minAgo = ((currentTimeMillis() - ts) / 60_000).toInt().coerceAtLeast(0)
+ Text(" · ${LocalizedStrings.dataUpdatedMinutesAgo(minAgo)}")
+ }
+ }
+ Div({
+ style { display(DisplayStyle.Flex); gap(8.px) }
+ }) {
+ listOf(
+ MetricsPeriod.P1H to LocalizedStrings.period1h,
+ MetricsPeriod.P24H to LocalizedStrings.period24h,
+ MetricsPeriod.P7D to LocalizedStrings.period7d
+ ).forEach { (period, label) ->
+ Button({
+ style {
+ padding(6.px, 12.px)
+ fontSize(12.px)
+ borderRadius(6.px)
+ border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
+ backgroundColor(if (metricsPeriod == period) FlagentTheme.Primary else FlagentTheme.inputBg(themeMode))
+ color(if (metricsPeriod == period) Color.white else FlagentTheme.text(themeMode))
+ cursor("pointer")
+ }
+ onClick { metricsPeriod = period }
+ }) {
+ Text(label)
+ }
+ }
+ }
+ }
+ if (overview.timeSeries.isNotEmpty() || overview.topFlags.isNotEmpty()) {
Div({
style {
- display(DisplayStyle.Flex)
- justifyContent(JustifyContent.SpaceBetween)
- alignItems(AlignItems.Center)
- marginBottom(12.px)
- flexWrap(org.jetbrains.compose.web.css.FlexWrap.Wrap)
- gap(8.px)
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fit, minmax(320px, 1fr))")
+ gap(20.px)
+ alignItems(AlignItems.Start)
}
}) {
- Span({
- style {
- fontSize(14.px)
- color(FlagentTheme.textLight(themeMode))
+ if (overview.timeSeries.isNotEmpty()) {
+ Div({ style { minHeight(280.px) } }) {
+ ActivityChart(
+ overview.timeSeries,
+ LocalizedStrings.evaluationsOverTime,
+ themeMode
+ )
}
- }) {
- Text("${flagent.frontend.i18n.LocalizedStrings.totalEvaluationsLabel}: ${overview.totalEvaluations} · ${flagent.frontend.i18n.LocalizedStrings.uniqueFlagsLabel}: ${overview.uniqueFlags}")
}
- Div({
- style { display(DisplayStyle.Flex); gap(8.px) }
- }) {
- listOf(
- MetricsPeriod.P1H to flagent.frontend.i18n.LocalizedStrings.period1h,
- MetricsPeriod.P24H to flagent.frontend.i18n.LocalizedStrings.period24h,
- MetricsPeriod.P7D to flagent.frontend.i18n.LocalizedStrings.period7d
- ).forEach { (period, label) ->
- Button({
- style {
- padding(6.px, 12.px)
- fontSize(12.px)
- borderRadius(6.px)
- border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
- backgroundColor(if (metricsPeriod == period) FlagentTheme.Primary else FlagentTheme.inputBg(themeMode))
- color(if (metricsPeriod == period) Color.white else FlagentTheme.text(themeMode))
- cursor("pointer")
- }
- onClick { metricsPeriod = period }
- }) {
- Text(label)
- }
+ if (overview.topFlags.isNotEmpty()) {
+ Div({ style { minHeight(280.px) } }) {
+ TopFlagsBarChart(
+ overview.topFlags,
+ LocalizedStrings.topFlagsByEvaluations,
+ themeMode,
+ maxBars = 8
+ )
}
}
}
- ActivityChart(
- overview.timeSeries,
- flagent.frontend.i18n.LocalizedStrings.evaluationsOverTime,
- themeMode
- )
+ } else {
+ Div({
+ style {
+ padding(32.px)
+ textAlign("center")
+ color(FlagentTheme.textLight(themeMode))
+ fontSize(14.px)
+ }
+ }) {
+ Text(LocalizedStrings.noMetricsData)
+ }
}
}
// Status distribution (from current flags stats)
val statusSlices = listOf(
- StatusSlice(flagent.frontend.i18n.LocalizedStrings.statusEnabledLabel, stats!!.enabledFlags, FlagentTheme.Success.toString()),
- StatusSlice(flagent.frontend.i18n.LocalizedStrings.statusDisabledLabel, stats!!.disabledFlags, FlagentTheme.Error.toString()),
- StatusSlice(flagent.frontend.i18n.LocalizedStrings.statusWithSegments, stats!!.flagsWithSegments, FlagentTheme.Primary.toString()),
- StatusSlice(flagent.frontend.i18n.LocalizedStrings.statusExperiments, stats!!.flagsWithVariants, FlagentTheme.Secondary.toString())
+ StatusSlice(LocalizedStrings.statusEnabledLabel, stats!!.enabledFlags, FlagentTheme.Success.toString()),
+ StatusSlice(LocalizedStrings.statusDisabledLabel, stats!!.disabledFlags, FlagentTheme.Error.toString()),
+ StatusSlice(LocalizedStrings.statusWithSegments, stats!!.flagsWithSegments, FlagentTheme.Primary.toString()),
+ StatusSlice(LocalizedStrings.statusExperiments, stats!!.flagsWithVariants, FlagentTheme.Secondary.toString())
).filter { it.count > 0 }
if (statusSlices.isNotEmpty()) {
Div({
@@ -383,7 +421,7 @@ fun Dashboard() {
}) {
StatusDistributionChart(
statusSlices,
- flagent.frontend.i18n.LocalizedStrings.statusDistribution,
+ LocalizedStrings.statusDistribution,
themeMode
)
}
@@ -411,7 +449,7 @@ fun Dashboard() {
color(FlagentTheme.text(themeMode))
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.topFlags)
+ Text(LocalizedStrings.topFlags)
}
Div({
style {
@@ -433,7 +471,7 @@ fun Dashboard() {
cursor("pointer")
}
onClick { Router.navigateTo(Route.FlagDetail(tf.flagId)) }
- attr("aria-label", "${tf.flagKey.ifBlank { "Flag #${tf.flagId}" }}: ${tf.evaluationCount} evaluations, ${if (flagEnabled == true) "enabled" else "disabled"}")
+ attr("aria-label", "${tf.flagKey.ifBlank { LocalizedStrings.flagNumber(tf.flagId) }}: ${tf.evaluationCount} evaluations, ${if (flagEnabled == true) "enabled" else "disabled"}")
}) {
Span({
style {
@@ -457,7 +495,7 @@ fun Dashboard() {
fontWeight("500")
}
}) {
- Text(tf.flagKey.ifBlank { "Flag #${tf.flagId}" })
+ Text(tf.flagKey.ifBlank { LocalizedStrings.flagNumber(tf.flagId) })
}
}
Span({
@@ -466,7 +504,7 @@ fun Dashboard() {
color(FlagentTheme.textLight(themeMode))
}
}) {
- Text("${tf.evaluationCount} ${flagent.frontend.i18n.LocalizedStrings.evaluations}")
+ Text("${tf.evaluationCount} ${LocalizedStrings.evaluations}")
}
}
}
@@ -474,50 +512,17 @@ fun Dashboard() {
}
}
- // Health Status
- Div({
- style {
- backgroundColor(FlagentTheme.cardBg(themeMode))
- borderRadius(8.px)
- padding(16.px)
- property("border", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
- marginBottom(16.px)
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- gap(12.px)
- }
- }) {
- Span({
- style {
- width(12.px)
- height(12.px)
- borderRadius(50.percent)
- backgroundColor(FlagentTheme.Success)
- property("flex-shrink", "0")
- }
- }) {}
- Div({}) {
- H3({
- style {
- fontSize(14.px)
- fontWeight("600")
- margin(0.px)
- color(FlagentTheme.text(themeMode))
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.healthStatus)
- }
- P({
- style {
- fontSize(13.px)
- color(FlagentTheme.textLight(themeMode))
- margin(0.px)
- marginTop(2.px)
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.healthStatusOk)
- }
- }
+ HealthStatusCard(
+ themeMode = themeMode,
+ stats = s,
+ metricsOverview = metricsOverview,
+ anomalyViewModel = anomalyViewModel,
+ enableMetrics = AppConfig.Features.enableMetrics,
+ enableAnomalyDetection = AppConfig.Features.enableAnomalyDetection
+ )
+
+ if (AppConfig.Features.enableCrashAnalytics) {
+ CrashOverviewSection(themeMode, crashOverview)
}
// Unresolved Alerts
@@ -548,7 +553,7 @@ fun Dashboard() {
color(FlagentTheme.text(themeMode))
}
}) {
- Text("🚨 ${flagent.frontend.i18n.LocalizedStrings.unresolvedAlerts}")
+ Text("🚨 ${LocalizedStrings.unresolvedAlerts}")
}
Button({
style {
@@ -564,7 +569,7 @@ fun Dashboard() {
Router.navigateTo(Route.Alerts)
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.viewAll)
+ Text(LocalizedStrings.viewAll)
}
}
@@ -583,7 +588,7 @@ fun Dashboard() {
marginBottom(5.px)
}
}) {
- Text("Flag #${alert.flagId}: ${alert.severity}")
+ Text("${LocalizedStrings.flagNumber(alert.flagId)}: ${alert.severity}")
}
Div({
style {
@@ -601,7 +606,9 @@ fun Dashboard() {
// Recently updated flags
if (flags.isNotEmpty()) {
- val recentFlags = flags.sortedByDescending { it.updatedAt ?: "" }.take(5)
+ val recentFlags = flags.sortedByDescending { f ->
+ f.updatedAt?.let { kotlin.js.Date(it).getTime().toLong() } ?: 0L
+ }.take(5)
Div({
style {
backgroundColor(FlagentTheme.cardBg(themeMode))
@@ -627,7 +634,7 @@ fun Dashboard() {
color(FlagentTheme.text(themeMode))
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.recentlyUpdatedFlags)
+ Text(LocalizedStrings.recentlyUpdatedFlags)
}
Button({
style {
@@ -641,7 +648,7 @@ fun Dashboard() {
}
onClick { Router.navigateTo(Route.FlagsList) }
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.viewAllFlags)
+ Text(LocalizedStrings.viewAllFlags)
}
}
Table({
@@ -679,7 +686,7 @@ fun Dashboard() {
property("white-space", "nowrap")
}
}) {
- Text(flag.description?.let { d -> d.take(40) + if (d.length > 40) "…" else "" } ?: "—")
+ Text(flag.description.let { d -> if (d.length > 40) d.take(40) + "…" else d })
}
Td({
style {
@@ -697,58 +704,320 @@ fun Dashboard() {
}
}
- // Quick Actions
- Div({
+ QuickActionsSection(themeMode)
+ }
+ }
+ }
+}
+
+@Composable
+private fun DashboardHeader(themeMode: ThemeMode, tenantName: String?, lastFlagsRefreshMs: Long?) {
+ Div({
+ style {
+ marginBottom(16.px)
+ }
+ }) {
+ H1({
+ style {
+ fontSize(24.px)
+ fontWeight("bold")
+ color(FlagentTheme.text(themeMode))
+ margin(0.px)
+ }
+ }) {
+ Text(LocalizedStrings.dashboardNav)
+ }
+ P({
+ style {
+ color(FlagentTheme.textLight(themeMode))
+ fontSize(14.px)
+ marginTop(4.px)
+ }
+ }) {
+ Text(LocalizedStrings.dashboardOverview)
+ }
+ if (tenantName != null) {
+ P({
style {
- backgroundColor(FlagentTheme.cardBg(themeMode))
- borderRadius(8.px)
- padding(16.px)
- property("box-shadow", FlagentTheme.ShadowCard)
+ color(FlagentTheme.textLight(themeMode))
+ fontSize(12.px)
+ marginTop(2.px)
}
}) {
- H2({
- style {
- fontSize(18.px)
- fontWeight("600")
- marginBottom(12.px)
- color(FlagentTheme.text(themeMode))
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.quickAccess)
+ Text(LocalizedStrings.dashboardTenantLabel(tenantName))
+ }
+ }
+ lastFlagsRefreshMs?.let { ts ->
+ val minAgo = ((currentTimeMillis() - ts) / 60_000).toInt().coerceAtLeast(0)
+ P({
+ style {
+ color(FlagentTheme.textLight(themeMode))
+ fontSize(12.px)
+ marginTop(2.px)
}
+ }) {
+ Text(LocalizedStrings.dataUpdatedMinutesAgo(minAgo))
+ }
+ }
+ }
+}
- Div({
- style {
- display(DisplayStyle.Grid)
- property("grid-template-columns", "repeat(auto-fit, minmax(140px, 1fr))")
- gap(12.px)
- }
- }) {
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.createFlag, "add_circle") {
- Router.navigateTo(Route.CreateFlag)
- }
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.viewFlags, "flag") {
- Router.navigateTo(Route.FlagsList)
- }
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.experimentsTitle, "science") {
- Router.navigateTo(Route.Experiments)
- }
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.segmentsTitle, "segment") {
- Router.navigateTo(Route.Segments)
- }
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.analyticsTitle, "analytics") {
- Router.navigateTo(Route.Analytics)
- }
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.debugConsole, "bug_report") {
- Router.navigateTo(Route.DebugConsole())
+@Composable
+private fun StatsRow(themeMode: ThemeMode, stats: DashboardStats) {
+ Div({
+ style {
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fit, minmax(160px, 1fr))")
+ gap(16.px)
+ marginBottom(16.px)
+ }
+ }) {
+ StatCard(themeMode, LocalizedStrings.totalFlagsStat, stats.totalFlags.toString(), "flag", FlagentTheme.Primary)
+ StatCard(themeMode, LocalizedStrings.enabled, stats.enabledFlags.toString(), "check_circle", FlagentTheme.Success)
+ StatCard(themeMode, LocalizedStrings.disabled, stats.disabledFlags.toString(), "cancel", FlagentTheme.Error)
+ StatCard(themeMode, LocalizedStrings.withSegmentsStat, stats.flagsWithSegments.toString(), "dashboard", FlagentTheme.Secondary)
+ }
+}
+
+@Composable
+private fun QuickLinksRow(themeMode: ThemeMode, stats: DashboardStats) {
+ Div({
+ style {
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fit, minmax(160px, 1fr))")
+ gap(16.px)
+ marginBottom(16.px)
+ }
+ }) {
+ QuickLinkCard(
+ themeMode,
+ title = LocalizedStrings.experimentsTitle,
+ value = stats.flagsWithVariants.toString(),
+ subtitle = "${stats.flagsWithVariants} ${LocalizedStrings.experimentsCount}",
+ icon = "science",
+ color = FlagentTheme.Secondary,
+ onClick = { Router.navigateTo(Route.Experiments) }
+ )
+ QuickLinkCard(
+ themeMode,
+ title = LocalizedStrings.segments,
+ value = stats.flagsWithSegments.toString(),
+ icon = "segment",
+ color = FlagentTheme.Primary,
+ onClick = { Router.navigateTo(Route.Segments) }
+ )
+ QuickLinkCard(
+ themeMode,
+ title = LocalizedStrings.analyticsTitle,
+ value = LocalizedStrings.viewMetrics,
+ icon = "analytics",
+ color = FlagentTheme.Primary,
+ onClick = { Router.navigateTo(Route.Analytics) }
+ )
+ }
+}
+
+@Composable
+private fun HealthStatusCard(
+ themeMode: ThemeMode,
+ stats: DashboardStats,
+ metricsOverview: GlobalMetricsOverviewResponse?,
+ anomalyViewModel: AnomalyViewModel?,
+ enableMetrics: Boolean,
+ enableAnomalyDetection: Boolean
+) {
+ val hasHighSeverityAlerts = enableAnomalyDetection && anomalyViewModel?.alerts?.any {
+ it.severity == AlertSeverity.HIGH || it.severity == AlertSeverity.CRITICAL
+ } == true
+ val noEvaluationsInPeriod = enableMetrics && stats.totalFlags > 0 &&
+ (metricsOverview?.totalEvaluations ?: 0L) == 0L
+
+ val (indicatorColor, statusText) = when {
+ hasHighSeverityAlerts -> FlagentTheme.Warning to LocalizedStrings.healthAnomaliesCount(anomalyViewModel!!.alerts.size)
+ noEvaluationsInPeriod -> FlagentTheme.Warning to LocalizedStrings.healthNoEvaluations
+ else -> FlagentTheme.Success to LocalizedStrings.healthStatusOk
+ }
+
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(16.px)
+ property("border", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ marginBottom(16.px)
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(12.px)
+ }
+ }) {
+ Span({
+ style {
+ width(12.px)
+ height(12.px)
+ borderRadius(50.percent)
+ backgroundColor(indicatorColor)
+ property("flex-shrink", "0")
+ }
+ }) {}
+ Div({}) {
+ H3({
+ style {
+ fontSize(14.px)
+ fontWeight("600")
+ margin(0.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) {
+ Text(LocalizedStrings.healthStatus)
+ }
+ P({
+ style {
+ fontSize(13.px)
+ color(FlagentTheme.textLight(themeMode))
+ margin(0.px)
+ marginTop(2.px)
+ }
+ }) {
+ Text(statusText)
+ if (hasHighSeverityAlerts) {
+ Span({
+ style { marginLeft(4.px); textDecoration("underline"); cursor("pointer") }
+ onClick { Router.navigateTo(Route.Alerts) }
+ }) {
+ Text(" · ${LocalizedStrings.viewAll}")
}
- if (AppConfig.Features.enableMultiTenancy) {
- QuickActionButton(themeMode, flagent.frontend.i18n.LocalizedStrings.manageTenantsLink, "business") {
- Router.navigateTo(Route.Tenants)
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun CrashOverviewSection(themeMode: ThemeMode, crashOverview: CrashListResponse?) {
+ val total = crashOverview?.total ?: 0L
+ val items = crashOverview?.items?.take(3) ?: emptyList()
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(16.px)
+ property("border", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ marginBottom(16.px)
+ }
+ }) {
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ justifyContent(JustifyContent.SpaceBetween)
+ alignItems(AlignItems.Center)
+ marginBottom(12.px)
+ }
+ }) {
+ Span({
+ style {
+ fontSize(16.px)
+ fontWeight("600")
+ color(FlagentTheme.text(themeMode))
+ }
+ }) {
+ Text(LocalizedStrings.crashesInPeriod(total.toInt(), LocalizedStrings.period24h))
+ }
+ Button({
+ style {
+ padding(6.px, 12.px)
+ fontSize(14.px)
+ cursor("pointer")
+ backgroundColor(FlagentTheme.Primary)
+ color(Color.white)
+ border(0.px)
+ borderRadius(6.px)
+ }
+ onClick { Router.navigateTo(Route.Crash) }
+ }) {
+ Text(LocalizedStrings.openCrashDashboard)
+ }
+ }
+ if (items.isNotEmpty()) {
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ flexDirection(FlexDirection.Column)
+ gap(8.px)
+ }
+ }) {
+ items.forEach { crash ->
+ Div({
+ style {
+ padding(8.px, 12.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ borderRadius(6.px)
+ fontSize(13.px)
+ color(FlagentTheme.textLight(themeMode))
+ }
+ }) {
+ Text(crash.message.ifBlank { LocalizedStrings.noMessage })
+ val flagKeys = crash.activeFlagKeys?.take(3) ?: emptyList()
+ if (flagKeys.isNotEmpty()) {
+ Span({ style { display(DisplayStyle.Block); marginTop(4.px); fontSize(12.px) } }) {
+ Text("${LocalizedStrings.activeFlags}: ${flagKeys.joinToString(", ")}")
+ }
}
}
}
}
+ }
+ }
+}
+
+@Composable
+private fun QuickActionsSection(themeMode: ThemeMode) {
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(16.px)
+ property("box-shadow", FlagentTheme.ShadowCard)
+ }
+ }) {
+ H2({
+ style {
+ fontSize(18.px)
+ fontWeight("600")
+ marginBottom(12.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) {
+ Text(LocalizedStrings.quickAccess)
+ }
+ Div({
+ style {
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fit, minmax(140px, 1fr))")
+ gap(12.px)
+ }
+ }) {
+ QuickActionButton(themeMode, LocalizedStrings.createFlag, "add_circle") {
+ Router.navigateTo(Route.CreateFlag)
+ }
+ QuickActionButton(themeMode, LocalizedStrings.viewFlags, "flag") {
+ Router.navigateTo(Route.FlagsList)
+ }
+ QuickActionButton(themeMode, LocalizedStrings.experimentsTitle, "science") {
+ Router.navigateTo(Route.Experiments)
+ }
+ QuickActionButton(themeMode, LocalizedStrings.segmentsTitle, "segment") {
+ Router.navigateTo(Route.Segments)
+ }
+ QuickActionButton(themeMode, LocalizedStrings.analyticsTitle, "analytics") {
+ Router.navigateTo(Route.Analytics)
+ }
+ QuickActionButton(themeMode, LocalizedStrings.debugConsole, "bug_report") {
+ Router.navigateTo(Route.DebugConsole())
+ }
+ if (AppConfig.Features.enableMultiTenancy) {
+ QuickActionButton(themeMode, LocalizedStrings.manageTenantsLink, "business") {
+ Router.navigateTo(Route.Tenants)
+ }
}
}
}
@@ -812,6 +1081,7 @@ private fun QuickLinkCard(
themeMode: ThemeMode,
title: String,
value: String,
+ subtitle: String? = null,
icon: String,
color: CSSColorValue,
onClick: () -> Unit
@@ -870,6 +1140,17 @@ private fun QuickLinkCard(
}) {
Text(value)
}
+ subtitle?.let { sub ->
+ Div({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginTop(4.px)
+ }
+ }) {
+ Text(sub)
+ }
+ }
}
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/DebugConsole.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/DebugConsole.kt
index d36df1ba..bbd90ae5 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/DebugConsole.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/DebugConsole.kt
@@ -19,11 +19,17 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.encodeToString
import org.jetbrains.compose.web.attributes.InputType
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
+private val prettyJson = Json { prettyPrint = true }
+private val lenientJson = Json { ignoreUnknownKeys = true }
+
/**
* DebugConsole component - console for testing evaluation
*/
@@ -179,9 +185,13 @@ fun DebugConsole(initialFlagKey: String? = null) {
private fun SingleEvaluationSection(initialFlagKey: String?) {
val themeMode = LocalThemeMode.current
val flagKey = remember { mutableStateOf(initialFlagKey ?: "") }
- val entityID = remember { mutableStateOf("a1234") }
- val entityType = remember { mutableStateOf("report") }
- val entityContextJson = remember { mutableStateOf("{\n \"hello\": \"world\"\n}") }
+ val entityID = remember { mutableStateOf("user_123") }
+ val entityType = remember { mutableStateOf("user") }
+ val entityContextJson = remember { mutableStateOf("""{
+ "user_id": "user_123",
+ "region": "EU",
+ "tier": "premium"
+}""") }
val enableDebug = remember { mutableStateOf(true) }
val result = remember { mutableStateOf(null) }
val loading = remember { mutableStateOf(false) }
@@ -195,8 +205,8 @@ private fun SingleEvaluationSection(initialFlagKey: String?) {
fun formatJson(json: String): String {
return try {
- val jsonObj = Json.parseToJsonElement(json) as? kotlinx.serialization.json.JsonObject
- Json { prettyPrint = true }.encodeToString(jsonObj)
+ val element = Json.parseToJsonElement(json)
+ prettyJson.encodeToString(JsonElement.serializer(), element)
} catch (e: Exception) {
json
}
@@ -236,8 +246,7 @@ private fun SingleEvaluationSection(initialFlagKey: String?) {
try {
val context = try {
if (entityContextJson.value.isNotBlank()) {
- val json = Json { ignoreUnknownKeys = true }
- val jsonObj = json.parseToJsonElement(entityContextJson.value) as? kotlinx.serialization.json.JsonObject
+ val jsonObj = lenientJson.parseToJsonElement(entityContextJson.value) as? JsonObject
jsonObj?.entries?.associate { entry ->
entry.key to entry.value.toString().trim('"')
}
@@ -378,6 +387,7 @@ private fun SingleEvaluationSection(initialFlagKey: String?) {
TextArea {
value(entityContextJson.value)
onInput { event -> entityContextJson.value = event.value }
+ attr("placeholder", "{\"user_id\": \"...\", \"region\": \"EU\", \"tier\": \"premium\"}")
style {
width(100.percent)
padding(10.px)
@@ -394,6 +404,16 @@ private fun SingleEvaluationSection(initialFlagKey: String?) {
borderRadius(3.px)
}
}
+ Span({
+ style {
+ display(DisplayStyle.Block)
+ fontSize(11.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginTop(4.px)
+ }
+ }) {
+ Text(LocalizedStrings.entityContextPlaceholderHint)
+ }
}
Div({
style {
@@ -407,7 +427,7 @@ private fun SingleEvaluationSection(initialFlagKey: String?) {
Input(InputType.Checkbox) {
checked(enableDebug.value)
onChange { event ->
- enableDebug.value = (event.target as org.w3c.dom.HTMLInputElement).checked
+ enableDebug.value = event.target.checked
}
style {
cursor("pointer")
@@ -527,8 +547,8 @@ private fun BatchEvaluationSection(initialFlagKey: String?) {
fun formatJson(json: String): String {
return try {
- val jsonObj = Json.parseToJsonElement(json)
- Json { prettyPrint = true }.encodeToString(jsonObj)
+ val element = Json.parseToJsonElement(json)
+ prettyJson.encodeToString(JsonElement.serializer(), element)
} catch (e: Exception) {
json
}
@@ -568,15 +588,14 @@ private fun BatchEvaluationSection(initialFlagKey: String?) {
try {
// Parse entities
val entities = try {
- val json = Json { ignoreUnknownKeys = true }
- val entitiesList = json.parseToJsonElement(entitiesJson.value) as? kotlinx.serialization.json.JsonArray
+ val entitiesList = lenientJson.parseToJsonElement(entitiesJson.value) as? JsonArray
entitiesList?.mapNotNull { element ->
- val obj = element as? kotlinx.serialization.json.JsonObject
+ val obj = element as? JsonObject
obj?.let {
val entityID = it["entityID"]?.toString()?.trim('"')
val entityType = it["entityType"]?.toString()?.trim('"')
val entityContext = it["entityContext"]?.let { ctx ->
- (ctx as? kotlinx.serialization.json.JsonObject)?.entries?.associate { entry ->
+ (ctx as? JsonObject)?.entries?.associate { entry ->
entry.key to entry.value.toString().trim('"')
}
}
@@ -719,7 +738,7 @@ private fun BatchEvaluationSection(initialFlagKey: String?) {
Input(InputType.Checkbox) {
checked(enableDebug.value)
onChange { event ->
- enableDebug.value = (event.target as org.w3c.dom.HTMLInputElement).checked
+ enableDebug.value = event.target.checked
}
style {
cursor("pointer")
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagEditor.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagEditor.kt
index 94cacef0..507b38d3 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagEditor.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagEditor.kt
@@ -9,6 +9,8 @@ import androidx.compose.runtime.remember
import flagent.frontend.api.ApiClient
import flagent.frontend.components.Icon
import flagent.frontend.components.Slider
+import flagent.frontend.components.common.ToggleSize
+import flagent.frontend.components.common.ToggleSwitch
import flagent.frontend.i18n.LocalizedStrings
import flagent.frontend.state.LocalThemeMode
import flagent.frontend.theme.FlagentTheme
@@ -16,6 +18,9 @@ import flagent.api.constants.ConstraintOperators
import flagent.api.model.FlagResponse
import flagent.api.model.CreateFlagRequest
import flagent.api.model.PutFlagRequest
+import flagent.frontend.components.anomaly.AnomalyAlertsList
+import flagent.frontend.components.metrics.MetricsDashboard
+import flagent.frontend.components.rollout.SmartRolloutConfig
import flagent.frontend.navigation.Route
import flagent.frontend.navigation.Router
import flagent.frontend.navigation.flagTabName
@@ -36,6 +41,7 @@ import org.jetbrains.compose.web.dom.*
import org.jetbrains.compose.web.dom.H2
import org.jetbrains.compose.web.dom.H3
import org.jetbrains.compose.web.dom.H5
+import org.w3c.dom.HTMLElement
/**
* FlagEditor component - create/edit flag with tabs
@@ -103,12 +109,12 @@ fun FlagEditor(flagId: Int?) {
property("box-shadow", "0 2px 4px ${FlagentTheme.Shadow}")
}
onMouseEnter {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.backgroundColor = FlagentTheme.NeutralLight.toString()
element.style.transform = "translateX(-2px)"
}
onMouseLeave {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.backgroundColor = FlagentTheme.Neutral.toString()
element.style.transform = "translateX(0)"
}
@@ -236,37 +242,25 @@ fun FlagEditor(flagId: Int?) {
property("box-shadow", FlagentTheme.ShadowCard)
}
}) {
- Label(attrs = {
- style {
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- gap(10.px)
- cursor("pointer")
- color(Color.white)
- fontWeight("600")
- fontSize(15.px)
- }
- }) {
- Input(InputType.Checkbox) {
- checked(f.enabled)
- onChange { event ->
- val checked = (event.target as org.w3c.dom.HTMLInputElement).checked
- CoroutineScope(Dispatchers.Main).launch {
- try {
- val updated = ApiClient.setFlagEnabled(flagId!!, checked)
- flag.value = updated
- } catch (_: Exception) { }
+ ToggleSwitch(
+ checked = f.enabled,
+ onCheckedChange = { checked ->
+ CoroutineScope(Dispatchers.Main).launch {
+ try {
+ val updated = ApiClient.setFlagEnabled(flagId!!, checked)
+ flag.value = updated
+ } catch (_: Exception) {
}
}
- style { width(20.px); height(20.px); cursor("pointer") }
- }
- Icon(
- name = if (f.enabled) "check_circle" else "cancel",
- size = 22.px,
- color = Color.white
- )
- Text(if (f.enabled) LocalizedStrings.enabled else LocalizedStrings.disabled)
- }
+ },
+ size = ToggleSize.Medium
+ )
+ Icon(
+ name = if (f.enabled) "check_circle" else "cancel",
+ size = 22.px,
+ color = Color.white
+ )
+ Text(if (f.enabled) LocalizedStrings.enabled else LocalizedStrings.disabled)
}
}
}
@@ -282,7 +276,7 @@ fun FlagEditor(flagId: Int?) {
}
}) {
Button({
- onClick { Router.navigateTo(Route.FlagDetail(flagId!!), addToHistory = false) }
+ onClick { Router.navigateTo(Route.FlagDetail(flagId), addToHistory = false) }
style {
padding(12.px, 24.px)
property("background-color", "transparent")
@@ -303,12 +297,12 @@ fun FlagEditor(flagId: Int?) {
}
onMouseEnter {
if (activeTab != "Config") {
- (it.target as org.w3c.dom.HTMLElement).style.color = FlagentTheme.Text.toString()
+ (it.target as HTMLElement).style.color = FlagentTheme.Text.toString()
}
}
onMouseLeave {
if (activeTab != "Config") {
- (it.target as org.w3c.dom.HTMLElement).style.color = FlagentTheme.textLight(themeMode).toString()
+ (it.target as HTMLElement).style.color = FlagentTheme.textLight(themeMode).toString()
}
}
}) {
@@ -341,12 +335,12 @@ fun FlagEditor(flagId: Int?) {
}
onMouseEnter {
if (activeTab != "History") {
- (it.target as org.w3c.dom.HTMLElement).style.color = FlagentTheme.Text.toString()
+ (it.target as HTMLElement).style.color = FlagentTheme.Text.toString()
}
}
onMouseLeave {
if (activeTab != "History") {
- (it.target as org.w3c.dom.HTMLElement).style.color = FlagentTheme.textLight(themeMode).toString()
+ (it.target as HTMLElement).style.color = FlagentTheme.textLight(themeMode).toString()
}
}
}) {
@@ -379,9 +373,9 @@ fun FlagEditor(flagId: Int?) {
when (activeTab) {
"Config" -> FlagConfigTab(flag.value!!, flagId)
"History" -> FlagHistory(flagId)
- "Metrics" -> flagent.frontend.components.metrics.MetricsDashboard(flagId, metricsMetricType)
- "Rollout" -> flagent.frontend.components.rollout.SmartRolloutConfig(flagId)
- "Anomalies" -> flagent.frontend.components.anomaly.AnomalyAlertsList(flagId)
+ "Metrics" -> MetricsDashboard(flagId, metricsMetricType)
+ "Rollout" -> SmartRolloutConfig(flagId)
+ "Anomalies" -> AnomalyAlertsList(flagId)
else -> FlagConfigTab(flag.value!!, flagId)
}
}
@@ -409,13 +403,13 @@ private fun FlagEditorTabButton(themeMode: flagent.frontend.state.ThemeMode, lab
alignItems(AlignItems.Center)
gap(8.px)
property("transition", "all 0.2s")
- marginBottom(-2.px)
+ marginBottom((-2).px)
}
onMouseEnter {
- if (!isActive) (it.target as org.w3c.dom.HTMLElement).style.color = FlagentTheme.Text.toString()
+ if (!isActive) (it.target as HTMLElement).style.color = FlagentTheme.Text.toString()
}
onMouseLeave {
- if (!isActive) (it.target as org.w3c.dom.HTMLElement).style.color = FlagentTheme.textLight(themeMode).toString()
+ if (!isActive) (it.target as HTMLElement).style.color = FlagentTheme.textLight(themeMode).toString()
}
}) {
Icon(name = icon, size = 18.px, color = if (isActive) FlagentTheme.Primary else FlagentTheme.textLight(themeMode))
@@ -549,7 +543,10 @@ private fun CreateFlagForm() {
* Contains: Flag Settings, Variants, Segments, Debug Console, Delete Flag
*/
@Composable
-private fun FlagConfigTab(flag: FlagResponse, flagId: Int) {
+private fun FlagConfigTab(
+ flag: FlagResponse,
+ flagId: Int
+) {
val themeMode = LocalThemeMode.current
val flagState = remember { mutableStateOf(flag) }
val showMdEditor = remember { mutableStateOf(false) }
@@ -797,7 +794,7 @@ private fun FlagSettingsCard(
property("box-shadow", "0 2px 4px ${FlagentTheme.Shadow}")
}
}) {
- Label(attrs = {
+ Div({
style {
display(DisplayStyle.Flex)
alignItems(AlignItems.Center)
@@ -807,18 +804,11 @@ private fun FlagSettingsCard(
fontWeight("600")
}
}) {
- Input(InputType.Checkbox) {
- checked(flag.enabled)
- onChange { event ->
- val checked = (event.target as org.w3c.dom.HTMLInputElement).checked
- setEnabled(checked)
- }
- style {
- width(18.px)
- height(18.px)
- cursor("pointer")
- }
- }
+ ToggleSwitch(
+ checked = flag.enabled,
+ onCheckedChange = { checked -> setEnabled(checked) },
+ size = ToggleSize.Medium
+ )
Span({
style {
fontSize(16.px)
@@ -898,14 +888,14 @@ private fun FlagSettingsCard(
}
onMouseEnter {
if (!saving.value) {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "translateY(-1px)"
element.style.setProperty("box-shadow", "0 4px 6px ${FlagentTheme.ShadowHover}")
}
}
onMouseLeave {
if (!saving.value) {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "translateY(0)"
element.style.setProperty("box-shadow", "0 2px 4px ${FlagentTheme.Shadow}")
}
@@ -968,10 +958,10 @@ private fun FlagSettingsCard(
property("transition", "border-color 0.2s")
}
onFocus {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
}
onBlur {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
}
}
}
@@ -986,7 +976,7 @@ private fun FlagSettingsCard(
paddingTop(28.px)
}
}) {
- Label(attrs = {
+ Div({
style {
display(DisplayStyle.Flex)
alignItems(AlignItems.Center)
@@ -995,16 +985,13 @@ private fun FlagSettingsCard(
whiteSpace("nowrap")
}
}) {
- Input(InputType.Checkbox) {
- checked(dataRecordsEnabled.value)
- onChange { event ->
- dataRecordsEnabled.value = (event.target as org.w3c.dom.HTMLInputElement).checked
- }
- style {
- cursor("pointer")
- flexShrink(0)
- }
- }
+ ToggleSwitch(
+ checked = dataRecordsEnabled.value,
+ onCheckedChange = { checked ->
+ dataRecordsEnabled.value = checked
+ },
+ size = ToggleSize.Small
+ )
Text(LocalizedStrings.dataRecords)
}
}
@@ -1060,10 +1047,10 @@ private fun FlagSettingsCard(
property("transition", "border-color 0.2s")
}
onFocus {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
}
onBlur {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
}
}
}
@@ -1127,10 +1114,10 @@ private fun FlagSettingsCard(
property("transition", "border-color 0.2s")
}
onFocus {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
}
onBlur {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
}
}
// Autocomplete suggestions
@@ -1576,10 +1563,10 @@ private fun VariantsSection(
property("transition", "border-color 0.2s")
}
onFocus {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.Primary.toString()
}
onBlur {
- (it.target as org.w3c.dom.HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
+ (it.target as HTMLElement).style.borderColor = FlagentTheme.inputBorder(themeMode).toString()
}
}
Button({
@@ -1607,14 +1594,14 @@ private fun VariantsSection(
}
onMouseEnter {
if (!creating.value && newVariantKey.value.isNotBlank()) {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "translateY(-1px)"
element.style.setProperty("box-shadow", "0 4px 6px ${FlagentTheme.ShadowHover}")
}
}
onMouseLeave {
if (!creating.value && newVariantKey.value.isNotBlank()) {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "translateY(0)"
element.style.setProperty("box-shadow", "0 2px 4px ${FlagentTheme.Shadow}")
}
@@ -1747,12 +1734,12 @@ private fun VariantCard(
property("transition", "all 0.2s")
}
onMouseEnter {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.setProperty("box-shadow", "0 2px 6px ${FlagentTheme.ShadowHover}")
element.style.transform = "translateY(-2px)"
}
onMouseLeave {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.setProperty("box-shadow", "0 1px 3px ${FlagentTheme.Shadow}")
element.style.transform = "translateY(0)"
}
@@ -2239,7 +2226,7 @@ private fun SegmentsSection(
Input(InputType.Range) {
value(newSegmentRollout.value.toString())
onInput { event ->
- newSegmentRollout.value = (event.target as org.w3c.dom.HTMLInputElement).value.toIntOrNull() ?: 50
+ newSegmentRollout.value = event.target.value.toIntOrNull() ?: 50
}
attr("min", "0")
attr("max", "100")
@@ -2576,7 +2563,7 @@ private fun SegmentCard(
Input(InputType.Number) {
value(rolloutPercent.value.toString())
onInput { event ->
- rolloutPercent.value = (event.target as org.w3c.dom.HTMLInputElement).value.toIntOrNull() ?: 0
+ rolloutPercent.value = event.target.value.toIntOrNull() ?: 0
}
attr("min", "0")
attr("max", "100")
@@ -2753,7 +2740,7 @@ private fun ConstraintsSection(
}
Select(attrs = {
onChange { event ->
- newConstraintOperator.value = (event.target as org.w3c.dom.HTMLSelectElement).value
+ newConstraintOperator.value = event.target.value
}
attr("value", newConstraintOperator.value)
style {
@@ -2945,7 +2932,7 @@ private fun ConstraintRow(
}
Select(attrs = {
onChange { event ->
- operator.value = (event.target as org.w3c.dom.HTMLSelectElement).value
+ operator.value = event.target.value
}
attr("value", operator.value)
style {
@@ -3158,12 +3145,12 @@ private fun DistributionCard(distribution: flagent.api.model.DistributionRespons
property("transition", "transform 0.2s, box-shadow 0.2s")
}
onMouseEnter {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "translateY(-2px)"
element.style.setProperty("box-shadow", "0 4px 8px ${FlagentTheme.ShadowHover}")
}
onMouseLeave {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "translateY(0)"
element.style.setProperty("box-shadow", "0 2px 4px ${FlagentTheme.Shadow}")
}
@@ -3329,7 +3316,7 @@ private fun DistributionEditDialog(
Input(InputType.Checkbox) {
checked(distributions.containsKey(variant.id))
onChange { event ->
- val checked = (event.target as org.w3c.dom.HTMLInputElement).checked
+ val checked = event.target.checked
if (checked) {
distributions[variant.id] = distributions[variant.id] ?: 0
} else {
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagHistory.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagHistory.kt
index 98631b3f..2cb3578c 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagHistory.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagHistory.kt
@@ -368,7 +368,6 @@ private fun formatJsonValue(value: kotlinx.serialization.json.JsonElement): Stri
is kotlinx.serialization.json.JsonArray -> {
"[ ... ]"
}
- else -> value.toString()
}
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagsList.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagsList.kt
index 667ee5f3..c0fed7f4 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagsList.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/FlagsList.kt
@@ -12,9 +12,13 @@ import flagent.api.model.FlagResponse
import flagent.api.model.TagResponse
import flagent.frontend.api.ApiClient
import flagent.frontend.components.common.ConfirmDialog
+import flagent.frontend.components.common.EmptyState
import flagent.frontend.components.common.FilterChip
import flagent.frontend.components.common.PageHeader
import flagent.frontend.components.common.Pagination
+import flagent.frontend.components.common.SkeletonLoader
+import flagent.frontend.components.common.ToggleSize
+import flagent.frontend.components.common.ToggleSwitch
import flagent.frontend.components.flags.CreateFlagModal
import flagent.frontend.config.AppConfig
import flagent.frontend.i18n.LocalizedStrings
@@ -28,6 +32,7 @@ import flagent.frontend.state.Notification
import flagent.frontend.state.NotificationType
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.util.ErrorHandler
+import flagent.frontend.util.triggerDownloadFromString
import kotlinx.browser.localStorage
import kotlinx.browser.window
import kotlinx.serialization.json.buildJsonArray
@@ -78,6 +83,7 @@ import org.jetbrains.compose.web.css.style
import org.jetbrains.compose.web.css.textAlign
import org.jetbrains.compose.web.css.textDecoration
import org.jetbrains.compose.web.css.width
+import org.jetbrains.compose.web.dom.A
import org.jetbrains.compose.web.dom.Button
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.H3
@@ -94,6 +100,7 @@ import org.jetbrains.compose.web.dom.Text
import org.jetbrains.compose.web.dom.Th
import org.jetbrains.compose.web.dom.Thead
import org.jetbrains.compose.web.dom.Tr
+import org.w3c.dom.HTMLInputElement
/**
* FlagsList component - displays list of all flags
@@ -148,24 +155,24 @@ private fun FlagTableRow(
}) {
Td({
style { padding(14.px, 12.px); textAlign("center"); width(40.px) }
- onClick { (it as org.w3c.dom.events.Event).stopPropagation() }
+ onClick { it.stopPropagation() }
}) {
Input(InputType.Checkbox) {
checked(flag.id in selectedIds)
onChange { event ->
- val input = (event.currentTarget as? org.w3c.dom.HTMLInputElement)
- ?: (event.target as? org.w3c.dom.HTMLInputElement)
- if (input != null) {
- if (input.checked) selectedIds.add(flag.id) else selectedIds.remove(flag.id)
- }
+ val input = (event.currentTarget as? HTMLInputElement)
+ ?: event.target
+ if (input.checked) selectedIds.add(flag.id) else selectedIds.remove(flag.id)
}
style { cursor("pointer") }
}
}
- Td({ style { padding(14.px, 12.px); textAlign("left"); maxWidth(320.px) } }) {
- Div({ style { fontWeight("600"); fontSize(15.px); color(FlagentTheme.Primary); marginBottom(2.px); property("overflow", "hidden"); property("text-overflow", "ellipsis") } }) {
+ Td({ style { padding(14.px, 12.px); textAlign("left"); maxWidth(180.px); property("overflow", "hidden"); property("text-overflow", "ellipsis") } }) {
+ Div({ style { fontWeight("600"); fontSize(15.px); color(FlagentTheme.Primary) } }) {
Text(flag.key.ifBlank { "flag_${flag.id}" })
}
+ }
+ Td({ style { padding(14.px, 12.px); textAlign("left"); maxWidth(280.px) } }) {
if (flag.description.isNotBlank()) {
Div({ style { fontSize(13.px); color(FlagentTheme.textLight(themeMode)); marginBottom(6.px); property("display", "-webkit-box"); property("-webkit-line-clamp", "2"); property("-webkit-box-orient", "vertical"); overflow("hidden") } }) {
Text(flag.description)
@@ -222,9 +229,9 @@ private fun FlagTableRow(
}
Td({
style { padding(14.px, 12.px); textAlign("center"); width(100.px) }
- onClick { (it as org.w3c.dom.events.Event).stopPropagation() }
+ onClick { it.stopPropagation() }
}) {
- Label(attrs = {
+ Div({
style {
display(DisplayStyle.Flex)
alignItems(AlignItems.Center)
@@ -240,16 +247,13 @@ private fun FlagTableRow(
property("box-shadow", "0 1px 3px ${FlagentTheme.Shadow}")
}
}) {
- Input(InputType.Checkbox) {
- checked(flag.enabled)
- onChange { event ->
- // currentTarget = input (listener target); event.target can be Label when clicking "ON"/"OFF" text
- val input = (event.currentTarget as? org.w3c.dom.HTMLInputElement)
- ?: (event.target as? org.w3c.dom.HTMLInputElement)
- if (input != null) onToggleEnabled(flag.id, input.checked)
- }
- style { cursor("pointer"); width(14.px); margin(0.px) }
- }
+ ToggleSwitch(
+ checked = flag.enabled,
+ onCheckedChange = { checked ->
+ onToggleEnabled(flag.id, checked)
+ },
+ size = ToggleSize.Small
+ )
Text(if (flag.enabled) "ON" else "OFF")
}
}
@@ -275,7 +279,7 @@ private fun GroupedFlagsTableBody(
}
}) {
Td({
- attr("colspan", "7")
+ attr("colspan", "8")
style {
padding(12.px, 16.px)
fontWeight("600")
@@ -650,6 +654,25 @@ fun FlagsList() {
}
}
+ val pendingToggle = remember { mutableStateOf?>(null) }
+ ConfirmDialog(
+ isOpen = pendingToggle.value != null,
+ title = LocalizedStrings.confirmToggleFlagTitle,
+ message = LocalizedStrings.confirmToggleFlagMessage,
+ confirmLabel = LocalizedStrings.confirmToggleFlagYes,
+ cancelLabel = LocalizedStrings.confirmToggleFlagNo,
+ onConfirm = {
+ pendingToggle.value?.let { (flagId, enabled) ->
+ onToggleEnabled(flagId, enabled)
+ }
+ pendingToggle.value = null
+ },
+ onCancel = { pendingToggle.value = null }
+ )
+ val onToggleWithConfirm: (Int, Boolean) -> Unit = { flagId, enabled ->
+ pendingToggle.value = Pair(flagId, enabled)
+ }
+
val realtimeRefreshTrigger = remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
@@ -724,7 +747,9 @@ fun FlagsList() {
subtitle = LocalizedStrings.featureFlagsSubtitle
)
- if (!loading.value && error.value == null && totalCount.value > 0) {
+ val effectiveTotalCount = if (totalCount.value > 0L) totalCount.value else flags.size.toLong()
+
+ if (!loading.value && error.value == null && effectiveTotalCount > 0L) {
Div({
style {
fontSize(13.px)
@@ -736,7 +761,7 @@ fun FlagsList() {
}
}) {
Icon("insights", size = 18.px, color = FlagentTheme.textLight(themeMode))
- Text("${totalCount.value} ${LocalizedStrings.featureFlags.lowercase()}")
+ Text("$effectiveTotalCount ${LocalizedStrings.featureFlags.lowercase()}")
}
}
@@ -918,7 +943,10 @@ fun FlagsList() {
CreateFlagModal(
onClose = { showCreateFlagModal.value = false },
onSelectTemplate = { template ->
- if (newFlagDescription.value.isNotBlank()) createFlag(template)
+ if (newFlagDescription.value.isBlank()) {
+ newFlagDescription.value = LocalizedStrings.createFlagTypeBooleanTitle
+ }
+ createFlag(template)
},
onSelectFullForm = { Router.navigateTo(Route.CreateFlag) }
)
@@ -1350,6 +1378,44 @@ fun FlagsList() {
}) {
Text(LocalizedStrings.copyShareLink)
}
+ Button({
+ onClick {
+ val list = flags
+ val header = "id,key,description,tags,enabled,updatedBy,updatedAt"
+ fun csvEscape(s: String): String {
+ val escaped = s.replace("\"", "\"\"")
+ return if (escaped.contains(',') || escaped.contains('"') || escaped.contains('\n')) "\"$escaped\"" else escaped
+ }
+ val rows = list.joinToString("\n") { f ->
+ listOf(
+ f.id.toString(),
+ csvEscape(f.key),
+ csvEscape(f.description),
+ csvEscape(f.tags.joinToString(";") { it.value }),
+ f.enabled.toString(),
+ csvEscape(f.updatedBy ?: ""),
+ csvEscape(f.updatedAt ?: "")
+ ).joinToString(",")
+ }
+ triggerDownloadFromString(
+ listOf(header, rows).joinToString("\n"),
+ "flags-export.csv",
+ "text/csv;charset=utf-8"
+ )
+ globalState.addNotification(Notification(message = LocalizedStrings.exportCsv + " (" + list.size + ")", type = NotificationType.SUCCESS))
+ }
+ style {
+ padding(8.px, 14.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border { width(1.px); style(LineStyle.Solid); color(FlagentTheme.cardBorder(themeMode)) }
+ borderRadius(6.px)
+ cursor("pointer")
+ fontSize(13.px)
+ }
+ }) {
+ Text(LocalizedStrings.exportCsv)
+ }
}
}
}
@@ -1366,7 +1432,7 @@ fun FlagsList() {
)
if (loading.value) {
- Spinner()
+ SkeletonLoader(height = 320.px)
} else if (error.value != null) {
val err = error.value!!
val isTenantOrApiKeyError = err.contains("tenant", ignoreCase = true) ||
@@ -1426,7 +1492,39 @@ fun FlagsList() {
}
}
} else {
- val sortedFlags = remember(flags, sortColumn.value, sortAscending.value) {
+ val hasActiveFiltersForEmpty = searchQuery.value.isNotBlank() || keyFilter.value.isNotBlank() ||
+ statusFilter.value != null || selectedTags.isNotEmpty() ||
+ quickFilterExperiments.value || quickFilterWithSegments.value
+ if (totalCount.value == 0L && flags.isEmpty() && !hasActiveFiltersForEmpty) {
+ EmptyState(
+ icon = "flag",
+ title = LocalizedStrings.createFirstFlag,
+ description = LocalizedStrings.emptyFlagsDescription,
+ actionLabel = LocalizedStrings.createFlag,
+ onAction = { showCreateFlagModal.value = true }
+ )
+ Div({
+ style {
+ marginTop(16.px)
+ textAlign("center")
+ }
+ }) {
+ A(href = "${AppConfig.docsUrl}#/guides/getting-started.md", attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style {
+ color(FlagentTheme.Primary)
+ textDecoration("underline")
+ fontSize(14.px)
+ }
+ }) {
+ Text(LocalizedStrings.gettingStartedGuideLink)
+ }
+ }
+ } else {
+ // Compute sorted flags on every recomposition so that UI reacts
+ // when individual elements in the state list `flags` are updated.
+ val sortedFlags = run {
var result = flags.toList()
sortColumn.value?.let { column ->
result = when (column) {
@@ -1442,16 +1540,15 @@ fun FlagsList() {
result
}
- val groupedByTag = remember(sortedFlags, groupByTag.value) {
- if (!groupByTag.value) null
- else {
- val noTagsKey = "\u0000"
- sortedFlags
- .groupBy { f -> f.tags.firstOrNull()?.value ?: noTagsKey }
- .toList()
- .sortedBy { (k, _) -> if (k == noTagsKey) "zzz" else k }
- .associate { it.first to it.second }
- }
+ val groupedByTag = if (!groupByTag.value) {
+ null
+ } else {
+ val noTagsKey = "\u0000"
+ sortedFlags
+ .groupBy { f -> f.tags.firstOrNull()?.value ?: noTagsKey }
+ .toList()
+ .sortedBy { (k, _) -> if (k == noTagsKey) "zzz" else k }
+ .associate { it.first to it.second }
}
if (sortedFlags.isEmpty()) {
@@ -1493,7 +1590,8 @@ fun FlagsList() {
}
}
} else {
- val totalPages = maxOf(1, ((totalCount.value + PAGE_SIZE - 1) / PAGE_SIZE).toInt())
+ val totalItemsForPagination = if (totalCount.value > 0L) totalCount.value else sortedFlags.size.toLong()
+ val totalPages = maxOf(1, ((totalItemsForPagination + PAGE_SIZE - 1) / PAGE_SIZE).toInt())
Div({
style {
backgroundColor(FlagentTheme.cardBg(themeMode))
@@ -1536,16 +1634,57 @@ fun FlagsList() {
Input(InputType.Checkbox) {
checked(sortedFlags.isNotEmpty() && sortedFlags.all { it.id in selectedIds })
onChange { event ->
- if ((event.target as org.w3c.dom.HTMLInputElement).checked) {
+ if ((event.target as HTMLInputElement).checked) {
sortedFlags.forEach { selectedIds.add(it.id) }
} else {
sortedFlags.forEach { selectedIds.remove(it.id) }
}
}
- onClick { (it as org.w3c.dom.events.Event).stopPropagation() }
+ onClick { it.stopPropagation() }
style { cursor("pointer") }
}
}
+ Th({
+ onClick { sortFlags("key") }
+ style {
+ padding(10.px, 12.px)
+ cursor("pointer")
+ property("user-select", "none")
+ fontWeight("600")
+ fontSize(13.px)
+ color(FlagentTheme.text(themeMode))
+ textAlign("left")
+ property("transition", "background-color 0.2s")
+ }
+ onMouseEnter {
+ (it.target as org.w3c.dom.HTMLElement).style.backgroundColor =
+ FlagentTheme.inputBg(themeMode).toString()
+ }
+ onMouseLeave {
+ (it.target as org.w3c.dom.HTMLElement).style.backgroundColor =
+ FlagentTheme.inputBg(themeMode).toString()
+ }
+ }) {
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ }
+ }) {
+ Icon(
+ name = "key",
+ size = 16.px,
+ color = FlagentTheme.text(themeMode)
+ )
+ Text(LocalizedStrings.flagKey)
+ if (sortColumn.value == "key") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending.value) "↑" else "↓")
+ }
+ }
+ }
+ }
Th({
onClick { sortFlags("description") }
style {
@@ -1737,7 +1876,7 @@ fun FlagsList() {
themeMode = themeMode,
selectedIds = selectedIds,
selectedTags = selectedTags,
- onToggleEnabled = onToggleEnabled
+ onToggleEnabled = onToggleWithConfirm
)
} else {
sortedFlags.forEachIndexed { index, flag ->
@@ -1747,7 +1886,7 @@ fun FlagsList() {
themeMode = themeMode,
selectedIds = selectedIds,
selectedTags = selectedTags,
- onToggleEnabled = onToggleEnabled
+ onToggleEnabled = onToggleWithConfirm
)
}
}
@@ -1775,7 +1914,7 @@ fun FlagsList() {
color(FlagentTheme.textLight(themeMode))
}
}) {
- Text("${totalCount.value} ${LocalizedStrings.featureFlags.lowercase()}")
+ Text("$totalItemsForPagination ${LocalizedStrings.featureFlags.lowercase()}")
}
Pagination(
currentPage = currentPage.value,
@@ -2154,5 +2293,6 @@ fun FlagsList() {
}
}
}
+ }
}
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/Icon.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/Icon.kt
index ad173b85..708a80fe 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/Icon.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/Icon.kt
@@ -2,9 +2,11 @@ package flagent.frontend.components
import androidx.compose.runtime.Composable
import flagent.frontend.theme.FlagentTheme
+import org.jetbrains.compose.web.attributes.AttrsScopeBuilder
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.Span
import org.jetbrains.compose.web.dom.Text
+import org.w3c.dom.HTMLElement
/**
* Material Icon component with smooth animations
@@ -19,7 +21,7 @@ fun Icon(
size: CSSSizeValue = 24.px,
color: CSSColorValue? = null,
animated: Boolean = false,
- attrs: (org.jetbrains.compose.web.attributes.AttrsBuilder) -> Unit = {}
+ attrs: (AttrsScopeBuilder) -> Unit = {}
) {
Span({
classes("material-icons")
@@ -33,15 +35,15 @@ fun Icon(
}
if (animated) {
onMouseEnter {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "scale(1.15) rotate(5deg)"
}
onMouseLeave {
- val element = it.target as org.w3c.dom.HTMLElement
+ val element = it.target as HTMLElement
element.style.transform = "scale(1) rotate(0deg)"
}
}
- attrs.invoke(this.unsafeCast>())
+ attrs.invoke(this.unsafeCast>())
}) {
Text(name)
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/InfoTooltip.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/InfoTooltip.kt
index 069b34fe..d088f45d 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/InfoTooltip.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/InfoTooltip.kt
@@ -29,9 +29,9 @@ enum class TooltipPosition {
}
/**
- * InfoTooltip component - shows information icon with tooltip on hover/click.
- * Uses z-index 10000 so it appears above Navbar (z-index 100) and modals.
- * Uses fixed positioning with viewport margin so it never goes under navigation.
+ * InfoTooltip component - shows information icon with tooltip on click.
+ * By default opens below the "!" button so it is not covered by other elements.
+ * Uses fixed positioning and high z-index so it appears above navbar and modals.
*/
private const val TOOLTIP_WIDTH_PX = 320
private const val TOOLTIP_OFFSET_PX = 8
@@ -41,7 +41,7 @@ fun InfoTooltip(
title: String,
description: String,
details: String? = null,
- preferredPosition: TooltipPosition = TooltipPosition.Top
+ preferredPosition: TooltipPosition = TooltipPosition.Bottom
) {
val themeMode = LocalThemeMode.current
val showTooltip = remember { mutableStateOf(false) }
@@ -141,18 +141,11 @@ fun InfoTooltip(
if (showTooltip.value) {
val pos = tooltipPosition.value
- Div({
+ if (pos != null) Div({
style {
position(Position.Fixed)
- if (pos != null) {
- left(pos.first.px)
- top(pos.second.px)
- } else {
- left(50.percent)
- top(50.percent)
- property("transform", "translate(-50%, -50%)")
- }
- property("margin", "min(20px, 5vh) auto")
+ left(pos.first.px)
+ top(pos.second.px)
width(320.px)
maxWidth(90.vw)
maxHeight(80.vh)
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/LandingPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/LandingPage.kt
index 07d74a40..e961d0c0 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/LandingPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/LandingPage.kt
@@ -20,109 +20,120 @@ fun LandingPage() {
position(Position.Relative)
minHeight(100.vh)
overflow("hidden")
- property(
- "background",
- FlagentTheme.GradientHero
- )
- property("background-size", "400% 400%")
- property("animation", "morphGradient 20s ease infinite")
property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif")
}
}) {
- // Dot grid pattern
+ // Fixed background layer — no repaint on scroll
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("inset", "0")
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property(
+ "background",
+ FlagentTheme.GradientHero
+ )
+ property("background-size", "400% 400%")
+ property("animation", "morphGradient 20s ease infinite")
+ }
+ }) {}
+ Div({
+ style {
+ position(Position.Fixed)
+ property("inset", "0")
+ property("z-index", "0")
+ property("pointer-events", "none")
property(
"background-image",
"radial-gradient(rgba(14, 165, 233, 0.12) 1px, transparent 1px)"
)
property("background-size", "28px 28px")
- property("pointer-events", "none")
}
}) {}
-
- // Floating blobs
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("top", "-8%")
property("right", "-3%")
width(450.px)
height(450.px)
borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
property("background", "radial-gradient(circle, rgba(14, 165, 233, 0.2) 0%, transparent 65%)")
property("animation", "float 14s ease-in-out infinite")
- property("pointer-events", "none")
}
}) {}
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("bottom", "-12%")
property("left", "-6%")
width(500.px)
height(500.px)
borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
property("background", "radial-gradient(circle, rgba(20, 184, 166, 0.18) 0%, transparent 65%)")
property("animation", "floatSlow 20s ease-in-out infinite")
- property("pointer-events", "none")
}
}) {}
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("top", "35%")
property("right", "12%")
width(140.px)
height(140.px)
borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
property("background", "radial-gradient(circle, rgba(56, 189, 248, 0.15) 0%, transparent 70%)")
property("animation", "floatReverse 11s ease-in-out infinite")
- property("pointer-events", "none")
}
}) {}
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("top", "15%")
property("left", "8%")
width(100.px)
height(100.px)
borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
property("background", "radial-gradient(circle, rgba(20, 184, 166, 0.12) 0%, transparent 70%)")
property("animation", "float 9s ease-in-out infinite reverse")
- property("pointer-events", "none")
}
}) {}
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("bottom", "25%")
property("right", "5%")
width(200.px)
height(200.px)
borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
property("background", "radial-gradient(circle, rgba(14, 165, 233, 0.1) 0%, transparent 70%)")
property("animation", "floatSlow 16s ease-in-out infinite")
- property("pointer-events", "none")
}
}) {}
-
- // Glow orb
Div({
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("top", "-15%")
property("left", "50%")
property("transform", "translateX(-50%)")
width(600.px)
height(400.px)
borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
property("background", "radial-gradient(ellipse, rgba(14, 165, 233, 0.15) 0%, transparent 70%)")
property("animation", "glowPulse 10s ease-in-out infinite")
- property("pointer-events", "none")
}
}) {}
@@ -184,7 +195,7 @@ fun LandingPage() {
property("margin", "0 auto 40px")
}
}) {
- Text("Feature flags, A/B testing, and dynamic configuration. Manage flags, run experiments, and roll out changes safely.")
+ Text("Feature flags, A/B testing, and dynamic configuration. Roll back in one click — without redeploying.")
}
// CTA buttons - Sign in is primary when auth required
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/Modal.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/Modal.kt
index c4ca8849..028b2a87 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/Modal.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/Modal.kt
@@ -1,7 +1,11 @@
package flagent.frontend.components
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import flagent.frontend.i18n.LocalizedStrings
+import kotlinx.browser.document
+import org.w3c.dom.events.Event
+import org.w3c.dom.events.KeyboardEvent
import flagent.frontend.state.LocalThemeMode
import flagent.frontend.theme.FlagentTheme
import org.jetbrains.compose.web.css.*
@@ -46,6 +50,17 @@ fun Modal(
content: @Composable () -> Unit
) {
val themeMode = LocalThemeMode.current
+ DisposableEffect(Unit) {
+ val handler: (KeyboardEvent) -> Unit = { e ->
+ if (e.key == "Escape") {
+ e.preventDefault()
+ onClose()
+ }
+ }
+ val wrapped: (Event) -> Unit = { handler(it.unsafeCast()) }
+ document.addEventListener("keydown", wrapped)
+ onDispose { document.removeEventListener("keydown", wrapped) }
+ }
Div({
style {
position(Position.Fixed)
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/SegmentEditor.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/SegmentEditor.kt
index a0c9ae81..d1b099e2 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/SegmentEditor.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/SegmentEditor.kt
@@ -130,7 +130,7 @@ fun SegmentEditor(flagId: Int, segmentId: Int? = null) {
Input(InputType.Range) {
value(rolloutPercent.value.toString())
onInput { event ->
- val inputValue = (event.target as org.w3c.dom.HTMLInputElement).value
+ val inputValue = event.target.value
rolloutPercent.value = inputValue.toIntOrNull() ?: 0
}
attr("min", "0")
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/ShellLayout.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/ShellLayout.kt
index 690f37d4..54abb905 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/ShellLayout.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/ShellLayout.kt
@@ -72,6 +72,8 @@ fun ShellLayout(
CommandBar(isOpen = commandBarOpen.value, onClose = { commandBarOpen.value = false })
+ val useHeroBackground = AppConfig.showMarketingLanding
+
Div(attrs = {
style {
display(DisplayStyle.Flex)
@@ -79,7 +81,9 @@ fun ShellLayout(
height(100.vh)
property("max-height", "100vh")
overflow("hidden")
- backgroundColor(FlagentTheme.contentBg(themeMode))
+ if (!useHeroBackground) {
+ backgroundColor(FlagentTheme.contentBg(themeMode))
+ }
}
}) {
Div(attrs = {
@@ -116,7 +120,9 @@ fun ShellLayout(
overflow("auto")
padding(20.px)
property("box-sizing", "border-box")
- backgroundColor(FlagentTheme.contentBg(themeMode))
+ if (!useHeroBackground) {
+ backgroundColor(FlagentTheme.contentBg(themeMode))
+ }
}
}) {
Div({
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/Slider.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/Slider.kt
index 9b3f88e1..39861ec3 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/Slider.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/Slider.kt
@@ -91,7 +91,7 @@ fun Slider(
id(sliderId)
value(value.toString())
onInput { event ->
- val inputValue = (event.target as org.w3c.dom.HTMLInputElement).value.toIntOrNull() ?: min
+ val inputValue = event.target.value.toIntOrNull() ?: min
onValueChange(inputValue.coerceIn(min, max))
}
attr("min", min.toString())
@@ -173,7 +173,7 @@ fun Slider(
justifyContent(JustifyContent.SpaceBetween)
fontSize(11.px)
color(FlagentTheme.textLight(themeMode))
- marginTop(-4.px)
+ marginTop((-4).px)
}
}) {
Span { Text("$min%") }
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/analytics/AnalyticsPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/analytics/AnalyticsPage.kt
index 477592a4..6b98717d 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/analytics/AnalyticsPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/analytics/AnalyticsPage.kt
@@ -2,6 +2,7 @@ package flagent.frontend.components.analytics
import androidx.compose.runtime.*
import flagent.api.model.FlagResponse
+import flagent.api.model.TagResponse
import flagent.frontend.api.AnalyticsOverviewResponse
import flagent.frontend.api.ApiClient
import flagent.frontend.api.GlobalMetricsOverviewResponse
@@ -44,9 +45,15 @@ fun AnalyticsPage() {
var analyticsOverviewPrevious by remember { mutableStateOf(null) }
var isLoading by remember { mutableStateOf(true) }
var error by remember { mutableStateOf(null) }
- var activeTab by remember { mutableStateOf("overview") }
+ var activeTab by remember { mutableStateOf("events") }
var timeRange by remember { mutableStateOf("24h") }
var compareWithPrevious by remember { mutableStateOf(false) }
+ var flagsSearchQuery by remember { mutableStateOf("") }
+ var flagsStatusFilter by remember { mutableStateOf(null) }
+ val flagsSelectedTags = remember { mutableStateListOf() }
+ val flagsAvailableTagsState = remember { mutableStateOf>(emptyList()) }
+ var flagsSortColumn by remember { mutableStateOf(null) }
+ var flagsSortAscending by remember { mutableStateOf(true) }
var isLoadingEvents by remember { mutableStateOf(false) }
@@ -61,7 +68,12 @@ fun AnalyticsPage() {
LaunchedEffect(Unit) {
ErrorHandler.withErrorHandling(
- block = { flags = ApiClient.getFlags().first },
+ block = {
+ flags = ApiClient.getFlags().first
+ try {
+ flagsAvailableTagsState.value = ApiClient.getTags()
+ } catch (_: Throwable) { /* ignore */ }
+ },
onError = { err -> error = ErrorHandler.getUserMessage(err) }
)
}
@@ -204,7 +216,7 @@ fun AnalyticsPage() {
Input(InputType.Checkbox) {
id("analytics-compare")
checked(compareWithPrevious)
- onInput { compareWithPrevious = (it.target as? org.w3c.dom.HTMLInputElement)?.checked ?: false }
+ onInput { compareWithPrevious = it.target.checked }
}
Label(attrs = {
attr("for", "analytics-compare")
@@ -247,6 +259,43 @@ fun AnalyticsPage() {
Text(error!!)
}
} else if (hasOverview && activeTab == "overview") {
+ val ov = overview!!
+ val overviewEmpty = ov.totalEvaluations == 0L && ov.timeSeries.isEmpty()
+ if (overviewEmpty) {
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(24.px)
+ property("box-shadow", FlagentTheme.ShadowCard)
+ }
+ }) {
+ P({
+ style {
+ color(FlagentTheme.text(themeMode))
+ fontSize(14.px)
+ margin(0.px)
+ marginBottom(12.px)
+ }
+ }) {
+ Text(LocalizedStrings.analyticsOverviewEmptyHint)
+ }
+ Button({
+ style {
+ padding(8.px, 16.px)
+ backgroundColor(FlagentTheme.Primary)
+ color(Color.white)
+ border(0.px)
+ borderRadius(6.px)
+ cursor("pointer")
+ fontSize(14.px)
+ }
+ onClick { activeTab = "events" }
+ }) {
+ Text(LocalizedStrings.switchToEventsTab)
+ }
+ }
+ } else {
Div({
style {
display(DisplayStyle.Flex)
@@ -380,6 +429,7 @@ fun AnalyticsPage() {
}
}
}
+ }
} else if (activeTab == "events") {
if (isLoadingEvents) {
Div({
@@ -571,6 +621,183 @@ fun AnalyticsPage() {
overview?.topFlags?.associate { it.flagId to it.evaluationCount } ?: emptyMap()
}
val showEvaluations = AppConfig.Features.enableMetrics && overview != null
+ val filteredFlags = remember(flags, flagsSearchQuery, flagsStatusFilter, flagsSelectedTags) {
+ var list = flags
+ flagsStatusFilter?.let { status -> list = list.filter { it.enabled == status } }
+ val q = flagsSearchQuery.trim().lowercase()
+ if (q.isNotEmpty()) {
+ list = list.filter { f ->
+ f.key.lowercase().contains(q) || f.description.lowercase().contains(q)
+ }
+ }
+ if (flagsSelectedTags.isNotEmpty()) {
+ list = list.filter { f -> f.tags.any { it.value in flagsSelectedTags } }
+ }
+ list
+ }
+ val sortedFlags = remember(filteredFlags, flagsSortColumn, flagsSortAscending) {
+ var result = filteredFlags
+ flagsSortColumn?.let { col ->
+ result = when (col) {
+ "key" -> result.sortedBy { it.key }
+ "description" -> result.sortedBy { it.description }
+ "status" -> result.sortedBy { it.enabled }
+ "segments" -> result.sortedBy { it.segments.size }
+ "variants" -> result.sortedBy { it.variants.size }
+ "evaluations" -> result.sortedBy { evalCountByFlagId[it.id] ?: 0L }
+ "updatedAt" -> result.sortedBy { it.updatedAt ?: "" }
+ else -> result
+ }
+ if (!flagsSortAscending) result = result.reversed()
+ }
+ result
+ }
+ fun sortByFlags(column: String) {
+ if (flagsSortColumn == column) flagsSortAscending = !flagsSortAscending
+ else { flagsSortColumn = column; flagsSortAscending = true }
+ }
+ val hasFlagsFilters = flagsSearchQuery.isNotBlank() || flagsStatusFilter != null || flagsSelectedTags.isNotEmpty()
+
+ if (sortedFlags.isEmpty() && hasFlagsFilters) {
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(40.px)
+ property("box-shadow", FlagentTheme.ShadowCard)
+ textAlign("center")
+ }
+ }) {
+ Icon("search_off", size = 48.px, color = FlagentTheme.textLight(themeMode))
+ P({
+ style {
+ marginTop(16.px)
+ color(FlagentTheme.text(themeMode))
+ fontSize(16.px)
+ }
+ }) {
+ Text(LocalizedStrings.noFlags)
+ }
+ Button({
+ style {
+ marginTop(12.px)
+ padding(8.px, 16.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border(0.px)
+ borderRadius(6.px)
+ cursor("pointer")
+ fontSize(14.px)
+ }
+ onClick {
+ flagsSearchQuery = ""
+ flagsStatusFilter = null
+ flagsSelectedTags.clear()
+ }
+ }) {
+ Text(LocalizedStrings.clearFilters)
+ }
+ }
+ } else {
+ Div({
+ style {
+ marginBottom(16.px)
+ display(DisplayStyle.Flex)
+ flexWrap(FlexWrap.Wrap)
+ alignItems(AlignItems.Center)
+ gap(12.px)
+ }
+ }) {
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ flex(1)
+ property("min-width", "200px")
+ }
+ }) {
+ Span({
+ classes("material-icons")
+ style { fontSize(20.px); color(FlagentTheme.textLight(themeMode)) }
+ }) { Text("search") }
+ Input(InputType.Text) {
+ value(flagsSearchQuery)
+ onInput { event -> flagsSearchQuery = event.value }
+ attr("placeholder", LocalizedStrings.searchExperimentsPlaceholder)
+ style {
+ flex(1)
+ padding(8.px, 12.px)
+ borderRadius(6.px)
+ border(1.px, LineStyle.Solid, FlagentTheme.inputBorder(themeMode))
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ fontSize(14.px)
+ }
+ }
+ }
+ listOf(
+ null to LocalizedStrings.filterAll,
+ true to LocalizedStrings.enabled,
+ false to LocalizedStrings.disabled
+ ).forEach { (status, label) ->
+ Button({
+ style {
+ padding(6.px, 12.px)
+ fontSize(13.px)
+ borderRadius(6.px)
+ border(1.px, LineStyle.Solid, if (flagsStatusFilter == status) FlagentTheme.Primary else FlagentTheme.cardBorder(themeMode))
+ backgroundColor(if (flagsStatusFilter == status) FlagentTheme.Primary else FlagentTheme.inputBg(themeMode))
+ color(if (flagsStatusFilter == status) Color.white else FlagentTheme.text(themeMode))
+ cursor("pointer")
+ }
+ onClick { flagsStatusFilter = status }
+ }) {
+ Text(label)
+ }
+ }
+ flagsSelectedTags.forEach { tagValue: String ->
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(4.px)
+ padding(6.px, 10.px)
+ backgroundColor(FlagentTheme.PrimaryLight)
+ color(FlagentTheme.PrimaryDark)
+ borderRadius(16.px)
+ fontSize(12.px)
+ cursor("pointer")
+ }
+ onClick { flagsSelectedTags.remove(tagValue) }
+ }) {
+ Text(tagValue)
+ Icon("close", size = 14.px, color = FlagentTheme.PrimaryDark)
+ }
+ }
+ flagsAvailableTagsState.value.filter { it.value !in flagsSelectedTags }.take(8).forEach { tag ->
+ Span({
+ style {
+ display(DisplayStyle.InlineBlock)
+ padding(6.px, 10.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
+ borderRadius(16.px)
+ fontSize(12.px)
+ cursor("pointer")
+ }
+ onClick { flagsSelectedTags.add(tag.value) }
+ }) {
+ Text("+ ${tag.value}")
+ }
+ }
+ Span({
+ style { color(FlagentTheme.textLight(themeMode)); fontSize(14.px); marginLeft(8.px) }
+ }) {
+ Text("${sortedFlags.size} ${LocalizedStrings.featureFlags.lowercase()}")
+ }
+ }
Div({
style {
backgroundColor(FlagentTheme.cardBg(themeMode))
@@ -594,16 +821,112 @@ fun AnalyticsPage() {
property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
}
}) {
- listOf(
- "Key",
- LocalizedStrings.description,
- LocalizedStrings.status,
- LocalizedStrings.segments,
- LocalizedStrings.variants,
- if (showEvaluations) "Evaluations" else null,
- LocalizedStrings.updatedAtUtc,
- if (AppConfig.Features.enableMetrics) LocalizedStrings.action else null
- ).filterNotNull().forEach { h ->
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("key") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.flagKey)
+ if (flagsSortColumn == "key") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("description") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.description)
+ if (flagsSortColumn == "description") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("status") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.status)
+ if (flagsSortColumn == "status") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("segments") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.segments)
+ if (flagsSortColumn == "segments") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("variants") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.variants)
+ if (flagsSortColumn == "variants") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ if (showEvaluations) {
Th({
style {
padding(10.px, 12.px)
@@ -612,13 +935,57 @@ fun AnalyticsPage() {
fontWeight(600)
color(FlagentTheme.textLight(themeMode))
property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("evaluations") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text("Evaluations")
+ if (flagsSortColumn == "evaluations") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
}
- }) { Text(h) }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortByFlags("updatedAt") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.updatedAtUtc)
+ if (flagsSortColumn == "updatedAt") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (flagsSortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ if (AppConfig.Features.enableMetrics) {
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ }
+ }) { Text(LocalizedStrings.action) }
}
}
}
Tbody {
- flags.forEach { flag ->
+ sortedFlags.forEach { flag ->
val evalCount = evalCountByFlagId[flag.id]
val onRowClick: () -> Unit = {
if (AppConfig.Features.enableMetrics) {
@@ -736,6 +1103,7 @@ fun AnalyticsPage() {
}
}
}
+ }
}
@Composable
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/auth/LoginForm.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/auth/LoginForm.kt
index fc75b9be..10afe575 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/auth/LoginForm.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/auth/LoginForm.kt
@@ -1,15 +1,68 @@
package flagent.frontend.components.auth
-import androidx.compose.runtime.*
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
import flagent.frontend.components.Icon
import flagent.frontend.config.AppConfig
+import flagent.frontend.i18n.LocalizedStrings
+import flagent.frontend.navigation.Route
+import flagent.frontend.navigation.Router
import flagent.frontend.state.LocalThemeMode
+import flagent.frontend.theme.AppGradientBackground
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.viewmodel.AuthViewModel
import kotlinx.browser.window
import org.jetbrains.compose.web.attributes.InputType
-import org.jetbrains.compose.web.css.*
-import org.jetbrains.compose.web.dom.*
+import org.jetbrains.compose.web.css.AlignItems
+import org.jetbrains.compose.web.css.Color
+import org.jetbrains.compose.web.css.DisplayStyle
+import org.jetbrains.compose.web.css.FlexDirection
+import org.jetbrains.compose.web.css.FlexWrap
+import org.jetbrains.compose.web.css.JustifyContent
+import org.jetbrains.compose.web.css.LineStyle
+import org.jetbrains.compose.web.css.Position
+import org.jetbrains.compose.web.css.alignItems
+import org.jetbrains.compose.web.css.backgroundColor
+import org.jetbrains.compose.web.css.border
+import org.jetbrains.compose.web.css.borderRadius
+import org.jetbrains.compose.web.css.color
+import org.jetbrains.compose.web.css.cursor
+import org.jetbrains.compose.web.css.display
+import org.jetbrains.compose.web.css.flex
+import org.jetbrains.compose.web.css.flexDirection
+import org.jetbrains.compose.web.css.flexShrink
+import org.jetbrains.compose.web.css.flexWrap
+import org.jetbrains.compose.web.css.fontSize
+import org.jetbrains.compose.web.css.fontWeight
+import org.jetbrains.compose.web.css.gap
+import org.jetbrains.compose.web.css.height
+import org.jetbrains.compose.web.css.justifyContent
+import org.jetbrains.compose.web.css.margin
+import org.jetbrains.compose.web.css.marginBottom
+import org.jetbrains.compose.web.css.marginTop
+import org.jetbrains.compose.web.css.maxWidth
+import org.jetbrains.compose.web.css.minHeight
+import org.jetbrains.compose.web.css.overflow
+import org.jetbrains.compose.web.css.padding
+import org.jetbrains.compose.web.css.paddingLeft
+import org.jetbrains.compose.web.css.paddingTop
+import org.jetbrains.compose.web.css.percent
+import org.jetbrains.compose.web.css.position
+import org.jetbrains.compose.web.css.px
+import org.jetbrains.compose.web.css.textAlign
+import org.jetbrains.compose.web.css.textDecoration
+import org.jetbrains.compose.web.css.vh
+import org.jetbrains.compose.web.css.width
+import org.jetbrains.compose.web.dom.A
+import org.jetbrains.compose.web.dom.Button
+import org.jetbrains.compose.web.dom.Div
+import org.jetbrains.compose.web.dom.H1
+import org.jetbrains.compose.web.dom.Input
+import org.jetbrains.compose.web.dom.Label
+import org.jetbrains.compose.web.dom.P
+import org.jetbrains.compose.web.dom.Text
+import org.w3c.dom.HTMLElement
/**
* Login Form with animated background, decorative shapes, and glass-morphism card.
@@ -25,534 +78,611 @@ fun LoginForm(
val passwordVisible = remember { mutableStateOf(false) }
val rememberMe = remember { mutableStateOf(false) }
- Div({
- classes("login-page")
- style {
- position(Position.Relative)
- display(DisplayStyle.Flex)
- justifyContent(JustifyContent.Center)
- alignItems(AlignItems.Center)
- minHeight(100.vh)
- overflow("hidden")
- property(
- "background",
- FlagentTheme.GradientHero
- )
- property("background-size", "400% 400%")
- property("animation", "morphGradient 15s ease infinite")
- }
- }) {
- // Dot grid pattern overlay
- Div({
- style {
- position(Position.Absolute)
- property("inset", "0")
- property(
- "background-image",
- "radial-gradient(rgba(14, 165, 233, 0.15) 1px, transparent 1px)"
- )
- property("background-size", "32px 32px")
- property("pointer-events", "none")
- }
- }) {}
-
- // Floating decorative blobs
- Div({
- style {
- position(Position.Absolute)
- property("top", "10%")
- property("right", "15%")
- width(320.px)
- height(320.px)
- borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(14, 165, 233, 0.25) 0%, transparent 70%)")
- property("animation", "float 12s ease-in-out infinite")
- property("pointer-events", "none")
- }
- }) {}
- Div({
- style {
- position(Position.Absolute)
- property("bottom", "20%")
- property("left", "10%")
- width(280.px)
- height(280.px)
- borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(20, 184, 166, 0.2) 0%, transparent 70%)")
- property("animation", "floatSlow 18s ease-in-out infinite")
- property("pointer-events", "none")
- }
- }) {}
- Div({
- style {
- position(Position.Absolute)
- property("top", "50%")
- property("left", "5%")
- width(120.px)
- height(120.px)
- borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 70%)")
- property("animation", "floatReverse 10s ease-in-out infinite")
- property("pointer-events", "none")
- }
- }) {}
- Div({
- style {
- position(Position.Absolute)
- property("bottom", "10%")
- property("right", "20%")
- width(180.px)
- height(180.px)
- borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(14, 165, 233, 0.15) 0%, transparent 70%)")
- property("animation", "float 14s ease-in-out infinite reverse")
- property("pointer-events", "none")
- }
- }) {}
-
- // Glow orbs
- Div({
- style {
- position(Position.Absolute)
- property("top", "-10%")
- property("right", "-5%")
- width(400.px)
- height(400.px)
- borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(14, 165, 233, 0.2) 0%, transparent 60%)")
- property("animation", "glowPulse 8s ease-in-out infinite")
- property("pointer-events", "none")
- }
- }) {}
-
- // Login card — two-column layout so content fits without scrolling
+ AppGradientBackground {
Div({
+ classes("login-page")
style {
position(Position.Relative)
- width(100.percent)
- maxWidth(680.px)
- margin(24.px)
- padding(28.px)
display(DisplayStyle.Flex)
- flexDirection(FlexDirection.Row)
- flexWrap(FlexWrap.Wrap)
- gap(32.px)
- property("background", "rgba(255, 255, 255, 0.03)")
- property("backdrop-filter", "blur(20px)")
- property("-webkit-backdrop-filter", "blur(20px)")
- property("border", "1px solid rgba(255, 255, 255, 0.08)")
- borderRadius(16.px)
- property("box-shadow", "0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255,255,255,0.05)")
- property("animation", "loginCardIn 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards")
- property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif")
+ justifyContent(JustifyContent.Center)
+ alignItems(AlignItems.Center)
+ minHeight(100.vh)
+ overflow("hidden")
}
}) {
- // Left column: form
+ // Background circles (fixed, behind the card)
+ Div({
+ style {
+ position(Position.Fixed)
+ property("top", "10%")
+ property("right", "15%")
+ width(320.px)
+ height(320.px)
+ borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property(
+ "background",
+ "radial-gradient(circle, rgba(14, 165, 233, 0.25) 0%, transparent 70%)"
+ )
+ property("animation", "float 12s ease-in-out infinite")
+ }
+ }) {}
Div({
style {
- flex(1)
- property("min-width", "260px")
+ position(Position.Fixed)
+ property("bottom", "20%")
+ property("left", "10%")
+ width(280.px)
+ height(280.px)
+ borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property(
+ "background",
+ "radial-gradient(circle, rgba(20, 184, 166, 0.2) 0%, transparent 70%)"
+ )
+ property("animation", "floatSlow 18s ease-in-out infinite")
+ }
+ }) {}
+ Div({
+ style {
+ position(Position.Fixed)
+ property("top", "50%")
+ property("left", "5%")
+ width(120.px)
+ height(120.px)
+ borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property(
+ "background",
+ "radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 70%)"
+ )
+ property("animation", "floatReverse 10s ease-in-out infinite")
+ }
+ }) {}
+ Div({
+ style {
+ position(Position.Fixed)
+ property("bottom", "10%")
+ property("right", "20%")
+ width(180.px)
+ height(180.px)
+ borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property(
+ "background",
+ "radial-gradient(circle, rgba(14, 165, 233, 0.15) 0%, transparent 70%)"
+ )
+ property("animation", "float 14s ease-in-out infinite reverse")
+ }
+ }) {}
+ Div({
+ style {
+ position(Position.Fixed)
+ property("top", "-10%")
+ property("right", "-5%")
+ width(400.px)
+ height(400.px)
+ borderRadius(50.percent)
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property(
+ "background",
+ "radial-gradient(circle, rgba(14, 165, 233, 0.2) 0%, transparent 60%)"
+ )
+ property("animation", "glowPulse 8s ease-in-out infinite")
+ }
+ }) {}
+
+ // Login card — two-column layout so content fits without scrolling
+ Div({
+ style {
+ position(Position.Relative)
+ property("z-index", "1")
+ width(100.percent)
+ maxWidth(680.px)
+ margin(24.px)
+ padding(28.px)
+ display(DisplayStyle.Flex)
+ flexDirection(FlexDirection.Row)
+ flexWrap(FlexWrap.Wrap)
+ gap(32.px)
+ property("background", "rgba(255, 255, 255, 0.03)")
+ property("backdrop-filter", "blur(20px)")
+ property("-webkit-backdrop-filter", "blur(20px)")
+ property("border", "1px solid rgba(255, 255, 255, 0.08)")
+ borderRadius(16.px)
+ property(
+ "box-shadow",
+ "0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255,255,255,0.05)"
+ )
+ property("animation", "loginCardIn 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards")
+ property(
+ "font-family",
+ "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif"
+ )
}
}) {
- // Logo / title area (compact)
+ // Left column: form
Div({
style {
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- gap(12.px)
- marginBottom(20.px)
+ flex(1)
+ property("min-width", "260px")
}
}) {
- Div({
+ // Top: Back to site (first element in card)
+ Button({
+ onClick {
+ if (AppConfig.showMarketingLanding) {
+ Router.navigateTo(Route.Home)
+ } else {
+ Router.navigateTo(Route.Dashboard)
+ }
+ }
style {
- width(44.px)
- height(44.px)
- flexShrink(0)
- borderRadius(12.px)
- property(
- "background",
- "linear-gradient(135deg, ${FlagentTheme.Primary} 0%, ${FlagentTheme.Secondary} 100%)"
- )
+ padding(8.px, 14.px)
+ backgroundColor(Color.transparent)
+ color(Color("rgba(255,255,255,0.8)"))
+ border(1.px, LineStyle.Solid, Color("rgba(255,255,255,0.3)"))
+ borderRadius(8.px)
+ cursor("pointer")
+ fontSize(13.px)
+ fontWeight(500)
display(DisplayStyle.Flex)
alignItems(AlignItems.Center)
- justifyContent(JustifyContent.Center)
- property("box-shadow", "0 6px 16px rgba(14, 165, 233, 0.35)")
+ gap(6.px)
+ marginBottom(20.px)
+ property("transition", "all 0.2s ease")
+ }
+ onMouseEnter {
+ (it.target as HTMLElement).style.backgroundColor =
+ "rgba(255,255,255,0.1)"
+ (it.target as HTMLElement).style.color = "white"
+ }
+ onMouseLeave {
+ (it.target as HTMLElement).style.backgroundColor = "transparent"
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.8)"
}
}) {
- Icon("flag", size = 22.px, color = Color.white)
+ Icon("arrow_back", size = 18.px, color = Color("rgba(255,255,255,0.8)"))
+ Text(LocalizedStrings.backToSite)
}
+
+ // Header: logo + title
Div({
style {
- flex(1)
- property("min-width", "0")
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(12.px)
+ marginBottom(20.px)
}
}) {
- H1({
+ Div({
style {
- fontSize(20.px)
- fontWeight(600)
- color(Color.white)
- margin(0.px)
- property("letter-spacing", "-0.02em")
+ width(44.px)
+ height(44.px)
+ flexShrink(0)
+ borderRadius(12.px)
+ property(
+ "background",
+ "linear-gradient(135deg, ${FlagentTheme.Primary} 0%, ${FlagentTheme.Secondary} 100%)"
+ )
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ property("box-shadow", "0 6px 16px rgba(14, 165, 233, 0.35)")
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.welcomeToFlagent)
+ Icon("flag", size = 22.px, color = Color.white)
}
- P({
+ Div({
style {
- fontSize(13.px)
- color(Color("rgba(255,255,255,0.6)"))
- margin(4.px, 0.px, 0.px, 0.px)
+ flex(1)
+ property("min-width", "0")
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.signInToManage)
+ H1({
+ style {
+ fontSize(20.px)
+ fontWeight(600)
+ color(Color.white)
+ margin(0.px)
+ property("letter-spacing", "-0.02em")
+ }
+ }) {
+ Text(LocalizedStrings.welcomeToFlagent)
+ }
+ P({
+ style {
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ margin(4.px, 0.px, 0.px, 0.px)
+ }
+ }) {
+ Text(LocalizedStrings.signInToManage)
+ }
}
}
- }
- // Email input
- Div(attrs = { style { marginBottom(14.px) } }) {
- Label(attrs = {
- style {
- display(DisplayStyle.Block)
- fontSize(13.px)
- fontWeight(500)
- color(Color("rgba(255,255,255,0.8)"))
- marginBottom(8.px)
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.emailLabel)
- }
- Input(InputType.Email) {
- value(email.value)
- onInput { e -> email.value = (e.target as? org.w3c.dom.HTMLInputElement)?.value ?: "" }
- attr("placeholder", "you@example.com")
- style {
- width(100.percent)
- padding(14.px, 16.px)
- property("background", "rgba(255,255,255,0.06)")
- property("border", "1px solid rgba(255,255,255,0.12)")
- borderRadius(10.px)
- fontSize(15.px)
- color(Color.white)
- property("box-sizing", "border-box")
- property("transition", "all 0.2s ease")
- }
- onFocus {
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("border-color", "rgba(14, 165, 233, 0.6)")
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("box-shadow", "0 0 0 3px rgba(14, 165, 233, 0.2)")
- }
- onBlur {
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("border-color", "rgba(255,255,255,0.12)")
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("box-shadow", "none")
+ // Email input
+ Div(attrs = { style { marginBottom(14.px) } }) {
+ Label(attrs = {
+ style {
+ display(DisplayStyle.Block)
+ fontSize(13.px)
+ fontWeight(500)
+ color(Color("rgba(255,255,255,0.8)"))
+ marginBottom(8.px)
+ }
+ }) {
+ Text(LocalizedStrings.emailLabel)
+ }
+ Input(InputType.Email) {
+ value(email.value)
+ onInput { e -> email.value = e.target.value }
+ attr("placeholder", "you@example.com")
+ style {
+ width(100.percent)
+ padding(14.px, 16.px)
+ property("background", "rgba(255,255,255,0.06)")
+ property("border", "1px solid rgba(255,255,255,0.12)")
+ borderRadius(10.px)
+ fontSize(15.px)
+ color(Color.white)
+ property("box-sizing", "border-box")
+ property("transition", "all 0.2s ease")
+ }
+ onFocus {
+ (it.target as HTMLElement).style.setProperty(
+ "border-color",
+ "rgba(14, 165, 233, 0.6)"
+ )
+ (it.target as HTMLElement).style.setProperty(
+ "box-shadow",
+ "0 0 0 3px rgba(14, 165, 233, 0.2)"
+ )
+ }
+ onBlur {
+ (it.target as HTMLElement).style.setProperty(
+ "border-color",
+ "rgba(255,255,255,0.12)"
+ )
+ (it.target as HTMLElement).style.setProperty("box-shadow", "none")
+ }
+ }
}
- }
- }
- // Password input with visibility toggle
- Div(attrs = { style { marginBottom(14.px) } }) {
- Label(attrs = {
- style {
- display(DisplayStyle.Block)
- fontSize(13.px)
- fontWeight(500)
- color(Color("rgba(255,255,255,0.8)"))
- marginBottom(8.px)
- }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.passwordLabel)
- }
- Div(attrs = {
- style {
- position(Position.Relative)
- }
- }) {
- Input(if (passwordVisible.value) InputType.Text else InputType.Password) {
- value(password.value)
- onInput { e -> password.value = (e.target as? org.w3c.dom.HTMLInputElement)?.value ?: "" }
- attr("placeholder", "••••••••")
- style {
- width(100.percent)
- padding(14.px, 44.px, 14.px, 16.px)
- property("background", "rgba(255,255,255,0.06)")
- property("border", "1px solid rgba(255,255,255,0.12)")
- borderRadius(10.px)
- fontSize(15.px)
- color(Color.white)
- property("box-sizing", "border-box")
- property("transition", "all 0.2s ease")
- }
- onFocus {
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("border-color", "rgba(14, 165, 233, 0.6)")
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("box-shadow", "0 0 0 3px rgba(14, 165, 233, 0.2)")
+ // Password input with visibility toggle
+ Div(attrs = { style { marginBottom(14.px) } }) {
+ Label(attrs = {
+ style {
+ display(DisplayStyle.Block)
+ fontSize(13.px)
+ fontWeight(500)
+ color(Color("rgba(255,255,255,0.8)"))
+ marginBottom(8.px)
+ }
+ }) {
+ Text(LocalizedStrings.passwordLabel)
}
- onBlur {
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("border-color", "rgba(255,255,255,0.12)")
- (it.target as org.w3c.dom.HTMLElement).style.setProperty("box-shadow", "none")
+ Div(attrs = {
+ style {
+ position(Position.Relative)
+ }
+ }) {
+ Input(if (passwordVisible.value) InputType.Text else InputType.Password) {
+ value(password.value)
+ onInput { e -> password.value = e.target.value }
+ attr("placeholder", "••••••••")
+ style {
+ width(100.percent)
+ padding(14.px, 44.px, 14.px, 16.px)
+ property("background", "rgba(255,255,255,0.06)")
+ property("border", "1px solid rgba(255,255,255,0.12)")
+ borderRadius(10.px)
+ fontSize(15.px)
+ color(Color.white)
+ property("box-sizing", "border-box")
+ property("transition", "all 0.2s ease")
+ }
+ onFocus {
+ (it.target as HTMLElement).style.setProperty(
+ "border-color",
+ "rgba(14, 165, 233, 0.6)"
+ )
+ (it.target as HTMLElement).style.setProperty(
+ "box-shadow",
+ "0 0 0 3px rgba(14, 165, 233, 0.2)"
+ )
+ }
+ onBlur {
+ (it.target as HTMLElement).style.setProperty(
+ "border-color",
+ "rgba(255,255,255,0.12)"
+ )
+ (it.target as HTMLElement).style.setProperty(
+ "box-shadow",
+ "none"
+ )
+ }
+ }
+ Button(attrs = {
+ style {
+ position(Position.Absolute)
+ property("top", "50%")
+ property("right", "12px")
+ property("transform", "translateY(-50%)")
+ padding(4.px)
+ backgroundColor(Color.transparent)
+ color(Color("rgba(255,255,255,0.6)"))
+ border(0.px)
+ cursor("pointer")
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ }
+ onClick { passwordVisible.value = !passwordVisible.value }
+ onMouseEnter {
+ (it.target as HTMLElement).style.color = "white"
+ }
+ onMouseLeave {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.6)"
+ }
+ }) {
+ Icon(
+ if (passwordVisible.value) "visibility_off" else "visibility",
+ size = 20.px,
+ color = Color("rgba(255,255,255,0.6)")
+ )
+ }
}
}
- Button(attrs = {
+
+ // Remember me
+ Div(attrs = {
style {
- position(Position.Absolute)
- property("top", "50%")
- property("right", "12px")
- property("transform", "translateY(-50%)")
- padding(4.px)
- backgroundColor(Color.transparent)
- color(Color("rgba(255,255,255,0.6)"))
- border(0.px)
- cursor("pointer")
display(DisplayStyle.Flex)
alignItems(AlignItems.Center)
- justifyContent(JustifyContent.Center)
+ marginBottom(16.px)
+ gap(8.px)
}
- onClick { passwordVisible.value = !passwordVisible.value }
- onMouseEnter {
- (it.target as org.w3c.dom.HTMLElement).style.color = "white"
+ }) {
+ Input(InputType.Checkbox) {
+ checked(rememberMe.value)
+ onInput { rememberMe.value = it.target.checked }
+ style {
+ width(18.px)
+ height(18.px)
+ cursor("pointer")
+ }
}
- onMouseLeave {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.6)"
+ Label(attrs = {
+ style {
+ fontSize(14.px)
+ color(Color("rgba(255,255,255,0.7)"))
+ cursor("pointer")
+ }
+ onClick { rememberMe.value = !rememberMe.value }
+ }) {
+ Text(LocalizedStrings.rememberMeLabel)
}
- }) {
- Icon(if (passwordVisible.value) "visibility_off" else "visibility", size = 20.px, color = Color("rgba(255,255,255,0.6)"))
}
- }
- }
- // Remember me
- Div(attrs = {
- style {
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- marginBottom(16.px)
- gap(8.px)
- }
- }) {
- Input(InputType.Checkbox) {
- checked(rememberMe.value)
- onInput { rememberMe.value = (it.target as? org.w3c.dom.HTMLInputElement)?.checked ?: false }
- style {
- width(18.px)
- height(18.px)
- cursor("pointer")
- }
- }
- Label(attrs = {
- style {
- fontSize(14.px)
- color(Color("rgba(255,255,255,0.7)"))
- cursor("pointer")
+ Button({
+ onClick {
+ viewModel.login(email.value, password.value) {
+ onSuccess()
+ }
+ }
+ if (viewModel.isLoading) {
+ attr("disabled", "")
+ }
+ style {
+ width(100.percent)
+ padding(14.px)
+ property(
+ "background",
+ "linear-gradient(135deg, ${FlagentTheme.Primary} 0%, ${FlagentTheme.PrimaryDark} 100%)"
+ )
+ color(Color.white)
+ border(0.px)
+ borderRadius(10.px)
+ cursor(if (viewModel.isLoading) "not-allowed" else "pointer")
+ fontSize(15.px)
+ fontWeight(600)
+ property("box-shadow", "0 4px 14px rgba(14, 165, 233, 0.4)")
+ property("transition", "all 0.2s ease")
+ }
+ if (!viewModel.isLoading) {
+ onMouseEnter {
+ val el = it.target as HTMLElement
+ el.style.transform = "translateY(-1px)"
+ el.style.setProperty(
+ "box-shadow",
+ "0 6px 20px rgba(14, 165, 233, 0.5)"
+ )
+ }
+ onMouseLeave {
+ val el = it.target as HTMLElement
+ el.style.transform = "translateY(0)"
+ el.style.setProperty(
+ "box-shadow",
+ "0 4px 14px rgba(14, 165, 233, 0.4)"
+ )
+ }
+ }
+ }) {
+ Text(if (viewModel.isLoading) LocalizedStrings.signingIn else LocalizedStrings.signIn)
}
- onClick { rememberMe.value = !rememberMe.value }
- }) {
- Text(flagent.frontend.i18n.LocalizedStrings.rememberMeLabel)
- }
- }
- Button({
- onClick {
- viewModel.login(email.value, password.value) {
- onSuccess()
- }
- }
- if (viewModel.isLoading) {
- attr("disabled", "")
- }
- style {
- width(100.percent)
- padding(14.px)
- property(
- "background",
- "linear-gradient(135deg, ${FlagentTheme.Primary} 0%, ${FlagentTheme.PrimaryDark} 100%)"
- )
- color(Color.white)
- border(0.px)
- borderRadius(10.px)
- cursor(if (viewModel.isLoading) "not-allowed" else "pointer")
- fontSize(15.px)
- fontWeight(600)
- property("box-shadow", "0 4px 14px rgba(14, 165, 233, 0.4)")
- property("transition", "all 0.2s ease")
- }
- if (!viewModel.isLoading) {
- onMouseEnter {
- val el = it.target as org.w3c.dom.HTMLElement
- el.style.transform = "translateY(-1px)"
- el.style.setProperty("box-shadow", "0 6px 20px rgba(14, 165, 233, 0.5)")
- }
- onMouseLeave {
- val el = it.target as org.w3c.dom.HTMLElement
- el.style.transform = "translateY(0)"
- el.style.setProperty("box-shadow", "0 4px 14px rgba(14, 165, 233, 0.4)")
+ viewModel.error?.let { error ->
+ Div({
+ style {
+ marginTop(12.px)
+ padding(12.px)
+ backgroundColor(FlagentTheme.errorBg(themeMode))
+ property("border", "1px solid var(--flagent-color-error)")
+ borderRadius(8.px)
+ color(FlagentTheme.errorText(themeMode))
+ fontSize(13.px)
+ }
+ }) {
+ Text(error)
+ }
}
}
- }) {
- Text(if (viewModel.isLoading) flagent.frontend.i18n.LocalizedStrings.signingIn else flagent.frontend.i18n.LocalizedStrings.signIn)
- }
- viewModel.error?.let { error ->
+ // Right column: links and SSO (horizontal grouping)
Div({
- style {
- marginTop(12.px)
- padding(12.px)
- backgroundColor(FlagentTheme.errorBg(themeMode))
- property("border", "1px solid var(--flagent-color-error)")
- borderRadius(8.px)
- color(FlagentTheme.errorText(themeMode))
- fontSize(13.px)
- }
- }) {
- Text(error)
- }
- }
- }
-
- // Right column: links and SSO (horizontal grouping)
- Div({
- style {
- display(DisplayStyle.Flex)
- flexDirection(FlexDirection.Column)
- gap(16.px)
- property("min-width", "180px")
- }
- }) {
- // Links section: support, GitHub, documentation (compact)
- Div({
- style {
- paddingTop(4.px)
- property("border-left", "1px solid rgba(255,255,255,0.08)")
- paddingLeft(20.px)
- display(DisplayStyle.Flex)
- flexDirection(FlexDirection.Column)
- gap(10.px)
- }
- }) {
- A(href = "mailto:${AppConfig.supportEmail}", attrs = {
- attr("target", "_blank")
- attr("rel", "noopener noreferrer")
style {
display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- gap(8.px)
- color(Color("rgba(255,255,255,0.6)"))
- textDecoration("none")
- fontSize(13.px)
- property("transition", "color 0.2s ease")
- }
- onMouseEnter {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.9)"
- }
- onMouseLeave {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.6)"
- }
- }) {
- Icon("mail", size = 18.px, color = Color("rgba(255,255,255,0.6)"))
- Text(flagent.frontend.i18n.LocalizedStrings.supportLink)
- }
- A(href = AppConfig.githubUrl, attrs = {
- attr("target", "_blank")
- attr("rel", "noopener noreferrer")
- style {
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- gap(8.px)
- color(Color("rgba(255,255,255,0.6)"))
- textDecoration("none")
- fontSize(13.px)
- property("transition", "color 0.2s ease")
- }
- onMouseEnter {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.9)"
- }
- onMouseLeave {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.6)"
- }
- }) {
- Icon("code", size = 18.px, color = Color("rgba(255,255,255,0.6)"))
- Text(flagent.frontend.i18n.LocalizedStrings.questionsAndGuides)
- }
- A(href = AppConfig.docsUrl, attrs = {
- attr("target", "_blank")
- attr("rel", "noopener noreferrer")
- style {
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- gap(8.px)
- color(Color("rgba(255,255,255,0.6)"))
- textDecoration("none")
- fontSize(13.px)
- property("transition", "color 0.2s ease")
- }
- onMouseEnter {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.9)"
- }
- onMouseLeave {
- (it.target as org.w3c.dom.HTMLElement).style.color = "rgba(255,255,255,0.6)"
+ flexDirection(FlexDirection.Column)
+ gap(16.px)
+ property("min-width", "180px")
}
}) {
- Icon("menu_book", size = 18.px, color = Color("rgba(255,255,255,0.6)"))
- Text(flagent.frontend.i18n.LocalizedStrings.documentation)
- }
- }
-
- if (AppConfig.Features.enableSso) {
- Div({
- style {
- paddingTop(12.px)
- property("border-top", "1px solid rgba(255,255,255,0.08)")
- }
- }) {
- Div(attrs = {
+ // Links section: support, GitHub, documentation (compact)
+ Div({
style {
- display(DisplayStyle.Block)
- fontSize(12.px)
- color(Color("rgba(255,255,255,0.5)"))
- marginBottom(12.px)
- textAlign("center")
+ paddingTop(4.px)
+ property("border-left", "1px solid rgba(255,255,255,0.08)")
+ paddingLeft(20.px)
+ display(DisplayStyle.Flex)
+ flexDirection(FlexDirection.Column)
+ gap(10.px)
}
}) {
- Text(flagent.frontend.i18n.LocalizedStrings.orSignInWithSso)
- }
- Button({
- onClick {
- val base = AppConfig.apiBaseUrl
- val url = if (base.isEmpty() || base == "http://localhost" || base == "https://localhost") {
- "${window.location.origin}/sso/login/1"
- } else {
- "$base/sso/login/1"
+ A(href = "mailto:${AppConfig.supportEmail}", attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textDecoration("none")
+ fontSize(13.px)
+ property("transition", "color 0.2s ease")
+ }
+ onMouseEnter {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.9)"
}
- window.location.href = url
+ onMouseLeave {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.6)"
+ }
+ }) {
+ Icon("mail", size = 18.px, color = Color("rgba(255,255,255,0.6)"))
+ Text(LocalizedStrings.supportLink)
}
- style {
- width(100.percent)
- padding(12.px, 16.px)
- backgroundColor(Color.transparent)
- color(FlagentTheme.PrimaryLight)
- border(1.px, LineStyle.Solid, Color("rgba(14, 165, 233, 0.5)"))
- borderRadius(10.px)
- cursor("pointer")
- fontSize(14.px)
- fontWeight(500)
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- justifyContent(JustifyContent.Center)
- gap(8.px)
- property("transition", "all 0.2s ease")
+ A(href = AppConfig.githubUrl, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textDecoration("none")
+ fontSize(13.px)
+ property("transition", "color 0.2s ease")
+ }
+ onMouseEnter {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.9)"
+ }
+ onMouseLeave {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.6)"
+ }
+ }) {
+ Icon("code", size = 18.px, color = Color("rgba(255,255,255,0.6)"))
+ Text(LocalizedStrings.questionsAndGuides)
}
- onMouseEnter {
- val el = it.target as org.w3c.dom.HTMLElement
- el.style.backgroundColor = "rgba(14, 165, 233, 0.15)"
+ A(href = AppConfig.docsUrl, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textDecoration("none")
+ fontSize(13.px)
+ property("transition", "color 0.2s ease")
+ }
+ onMouseEnter {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.9)"
+ }
+ onMouseLeave {
+ (it.target as HTMLElement).style.color = "rgba(255,255,255,0.6)"
+ }
+ }) {
+ Icon("menu_book", size = 18.px, color = Color("rgba(255,255,255,0.6)"))
+ Text(LocalizedStrings.documentation)
}
- onMouseLeave {
- (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = "transparent"
+ }
+
+ if (AppConfig.Features.enableSso) {
+ Div({
+ style {
+ paddingTop(12.px)
+ property("border-top", "1px solid rgba(255,255,255,0.08)")
+ }
+ }) {
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Block)
+ fontSize(12.px)
+ color(Color("rgba(255,255,255,0.5)"))
+ marginBottom(12.px)
+ textAlign("center")
+ }
+ }) {
+ Text(LocalizedStrings.orSignInWithSso)
+ }
+ Button({
+ onClick {
+ val base = AppConfig.apiBaseUrl
+ val url =
+ if (base.isEmpty() || base == "http://localhost" || base == "https://localhost") {
+ "${window.location.origin}/sso/login/1"
+ } else {
+ "$base/sso/login/1"
+ }
+ window.location.href = url
+ }
+ style {
+ width(100.percent)
+ padding(12.px, 16.px)
+ backgroundColor(Color.transparent)
+ color(FlagentTheme.PrimaryLight)
+ border(1.px, LineStyle.Solid, Color("rgba(14, 165, 233, 0.5)"))
+ borderRadius(10.px)
+ cursor("pointer")
+ fontSize(14.px)
+ fontWeight(500)
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ gap(8.px)
+ property("transition", "all 0.2s ease")
+ }
+ onMouseEnter {
+ val el = it.target as HTMLElement
+ el.style.backgroundColor = "rgba(14, 165, 233, 0.15)"
+ }
+ onMouseLeave {
+ (it.target as HTMLElement).style.backgroundColor = "transparent"
+ }
+ }) {
+ Icon("login", size = 18.px, color = FlagentTheme.PrimaryLight)
+ Text(LocalizedStrings.loginWithSso)
+ }
}
- }) {
- Icon("login", size = 18.px, color = FlagentTheme.PrimaryLight)
- Text(flagent.frontend.i18n.LocalizedStrings.loginWithSso)
}
}
}
- }
}
}
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ConfirmDialog.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ConfirmDialog.kt
index 899bc9e0..1a6acd50 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ConfirmDialog.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ConfirmDialog.kt
@@ -30,19 +30,6 @@ fun ConfirmDialog(
width(100.percent)
}
}) {
- // Title
- H3({
- style {
- fontSize(18.px)
- fontWeight(600)
- color(FlagentTheme.text(themeMode))
- margin(0.px)
- marginBottom(16.px)
- }
- }) {
- Text(title)
- }
-
// Optional error (e.g. delete failed)
errorMessage?.let { err ->
Div({
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ToggleSwitch.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ToggleSwitch.kt
new file mode 100644
index 00000000..636341df
--- /dev/null
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/common/ToggleSwitch.kt
@@ -0,0 +1,92 @@
+package flagent.frontend.components.common
+
+import androidx.compose.runtime.Composable
+import flagent.frontend.state.LocalThemeMode
+import flagent.frontend.theme.FlagentTheme
+import org.jetbrains.compose.web.css.*
+import org.jetbrains.compose.web.dom.Div
+
+enum class ToggleSize {
+ Small,
+ Medium
+}
+
+/**
+ * iOS/Android-style toggle: pill track (gray when off, green when on) + sliding white knob with animation.
+ */
+@Composable
+fun ToggleSwitch(
+ checked: Boolean,
+ onCheckedChange: (Boolean) -> Unit,
+ enabled: Boolean = true,
+ size: ToggleSize = ToggleSize.Medium,
+) {
+ val themeMode = LocalThemeMode.current
+
+ val trackWidth = when (size) {
+ ToggleSize.Small -> 40.px
+ ToggleSize.Medium -> 48.px
+ }
+ val trackHeight = when (size) {
+ ToggleSize.Small -> 24.px
+ ToggleSize.Medium -> 28.px
+ }
+ val knobSize = when (size) {
+ ToggleSize.Small -> 18.px
+ ToggleSize.Medium -> 22.px
+ }
+ val paddingPx = 3
+ val translateX = when (size) {
+ ToggleSize.Small -> 40 - 18 - paddingPx * 2 // trackWidth - knobSize - padding*2
+ ToggleSize.Medium -> 48 - 22 - paddingPx * 2
+ }
+
+ Div({
+ attr("role", "switch")
+ attr("aria-checked", checked.toString())
+ if (!enabled) {
+ attr("aria-disabled", "true")
+ }
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ width(trackWidth)
+ height(trackHeight)
+ padding(paddingPx.px)
+ borderRadius(999.px)
+ backgroundColor(
+ if (checked) FlagentTheme.Success
+ else FlagentTheme.NeutralLighter
+ )
+ border(
+ 1.px,
+ LineStyle.Solid,
+ if (checked) FlagentTheme.Success else FlagentTheme.inputBorder(themeMode)
+ )
+ cursor(if (enabled) "pointer" else "not-allowed")
+ property("transition", "background-color 0.22s ease, border-color 0.22s ease")
+ property("overflow", "hidden")
+ }
+ if (enabled) {
+ onClick {
+ onCheckedChange(!checked)
+ }
+ }
+ }) {
+ Div({
+ style {
+ width(knobSize)
+ height(knobSize)
+ borderRadius(999.px)
+ backgroundColor(Color.white)
+ property(
+ "transform",
+ if (checked) "translateX(${translateX}px)" else "translateX(0px)"
+ )
+ property("transition", "transform 0.22s cubic-bezier(0.4, 0, 0.2, 1)")
+ property("box-shadow", FlagentTheme.ShadowCard)
+ property("flex-shrink", "0")
+ }
+ })
+ }
+}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/dashboard/TopFlagsBarChart.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/dashboard/TopFlagsBarChart.kt
new file mode 100644
index 00000000..440d557d
--- /dev/null
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/dashboard/TopFlagsBarChart.kt
@@ -0,0 +1,111 @@
+package flagent.frontend.components.dashboard
+
+import androidx.compose.runtime.*
+import flagent.frontend.api.TopFlagEntryResponse
+import flagent.frontend.i18n.LocalizedStrings
+import flagent.frontend.state.ThemeMode
+import flagent.frontend.theme.FlagentTheme
+import flagent.frontend.util.currentTimeMillis
+import kotlinx.browser.document
+import org.jetbrains.compose.web.css.*
+import org.jetbrains.compose.web.dom.*
+import org.w3c.dom.HTMLCanvasElement
+
+/**
+ * Horizontal bar chart for top flags by evaluation count.
+ * Uses Chart.js; theme-aware. Limits labels for readability.
+ */
+@Composable
+fun TopFlagsBarChart(
+ topFlags: List,
+ title: String,
+ themeMode: ThemeMode,
+ maxBars: Int = 8
+) {
+ val canvasId = remember { "top-flags-bar-${currentTimeMillis()}" }
+ var chartInstance by remember { mutableStateOf(null) }
+ val limited = topFlags.take(maxBars)
+
+ LaunchedEffect(limited, themeMode) {
+ val canvas = document.getElementById(canvasId) as? HTMLCanvasElement
+ if (canvas != null) destroyChartOnCanvas(canvas)
+ chartInstance = null
+ if (canvas != null && limited.isNotEmpty()) {
+ chartInstance = createBarChart(canvas, limited, title, themeMode)
+ }
+ }
+
+ DisposableEffect(canvasId) {
+ onDispose {
+ val canvas = document.getElementById(canvasId) as? HTMLCanvasElement
+ if (canvas != null) destroyChartOnCanvas(canvas)
+ chartInstance = null
+ }
+ }
+
+ Div({
+ style {
+ width(100.percent)
+ height(280.px)
+ position(Position.Relative)
+ }
+ }) {
+ Canvas({
+ id(canvasId)
+ style { width(100.percent); height(100.percent) }
+ })
+ }
+}
+
+private fun destroyChartOnCanvas(canvas: HTMLCanvasElement) {
+ val Chart = js("window.Chart")
+ val existing = Chart.getChart(canvas)
+ if (existing != null) existing.destroy()
+}
+
+private fun createBarChart(
+ canvas: HTMLCanvasElement,
+ topFlags: List,
+ title: String,
+ themeMode: ThemeMode
+): dynamic {
+ val labels = topFlags.map { entry ->
+ val key = entry.flagKey.ifBlank { LocalizedStrings.flagNumber(entry.flagId) }
+ if (key.length > 20) key.take(17) + "…" else key
+ }.toTypedArray()
+ val data = topFlags.map { it.evaluationCount.toInt() }.toTypedArray()
+ val Chart = js("window.Chart")
+ val gridColor = FlagentTheme.cardBorder(themeMode).toString()
+ val tickColor = FlagentTheme.text(themeMode).toString()
+ val titleColor = FlagentTheme.text(themeMode).toString()
+ val barColor = FlagentTheme.Primary.toString()
+
+ val config = js("""({
+ type: 'bar',
+ data: { labels: [], datasets: [{ label: 'Evaluations', data: [], backgroundColor: '', borderColor: '', borderWidth: 1 }] },
+ options: {
+ indexAxis: 'y',
+ responsive: true,
+ maintainAspectRatio: false,
+ plugins: {
+ title: { display: true, text: '', font: { size: 16, weight: 'bold' }, color: '' },
+ legend: { display: false }
+ },
+ scales: {
+ x: { beginAtZero: true, grid: { color: '' }, ticks: { color: '' } },
+ y: { grid: { color: '' }, ticks: { color: '', maxTicksLimit: 12 } }
+ }
+ }
+ })""")
+ config.data.labels = labels
+ config.data.datasets[0].data = data
+ config.data.datasets[0].backgroundColor = barColor
+ config.data.datasets[0].borderColor = barColor
+ config.options.plugins.title.text = title
+ config.options.plugins.title.color = titleColor
+ config.options.scales.x.grid.color = gridColor
+ config.options.scales.x.ticks.color = tickColor
+ config.options.scales.y.grid.color = gridColor
+ config.options.scales.y.ticks.color = tickColor
+ return js("new Chart(canvas, config)")
+}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/experiments/ExperimentsPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/experiments/ExperimentsPage.kt
index e0c31af6..0e0e2a1b 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/experiments/ExperimentsPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/experiments/ExperimentsPage.kt
@@ -2,8 +2,10 @@ package flagent.frontend.components.experiments
import androidx.compose.runtime.*
import flagent.api.model.FlagResponse
+import flagent.api.model.TagResponse
import flagent.frontend.api.ApiClient
import flagent.frontend.components.Icon
+import flagent.frontend.components.common.FilterChip
import flagent.frontend.components.common.PageHeader
import flagent.frontend.config.AppConfig
import flagent.frontend.i18n.LocalizedStrings
@@ -12,14 +14,18 @@ import flagent.frontend.navigation.Router
import flagent.frontend.state.LocalThemeMode
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.util.ErrorHandler
+import org.jetbrains.compose.web.attributes.InputType
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
/** Status filter for experiments list */
private enum class ExperimentStatusFilter { All, Enabled, Disabled }
+private const val NO_TAGS_GROUP_KEY = "\u0000"
+
/**
- * Experiments (A/B) page: flags with 2+ variants. Card grid or table layout with status filter.
+ * Experiments (A/B) page: flags with 2+ variants. Card grid or table layout with status filter,
+ * search, tags filter, group by tags, and sortable table.
*/
@Composable
fun ExperimentsPage() {
@@ -29,6 +35,12 @@ fun ExperimentsPage() {
var error by remember { mutableStateOf(null) }
var statusFilter by remember { mutableStateOf(ExperimentStatusFilter.All) }
var viewCards by remember { mutableStateOf(true) }
+ var searchQuery by remember { mutableStateOf("") }
+ val selectedTags = remember { mutableStateListOf() }
+ val availableTagsState = remember { mutableStateOf>(emptyList()) }
+ var groupByTag by remember { mutableStateOf(false) }
+ var sortColumn by remember { mutableStateOf(null) }
+ var sortAscending by remember { mutableStateOf(true) }
LaunchedEffect(Unit) {
isLoading = true
@@ -37,6 +49,9 @@ fun ExperimentsPage() {
block = {
val (all, _) = ApiClient.getFlags(preload = true)
flags = all.filter { it.variants.size >= 2 }
+ try {
+ availableTagsState.value = ApiClient.getTags()
+ } catch (_: Throwable) { /* ignore */ }
},
onError = { err ->
error = ErrorHandler.getUserMessage(err)
@@ -45,14 +60,55 @@ fun ExperimentsPage() {
isLoading = false
}
- val filteredFlags = remember(flags, statusFilter) {
- when (statusFilter) {
+ val filteredFlags = remember(flags, statusFilter, searchQuery, selectedTags) {
+ var list = when (statusFilter) {
ExperimentStatusFilter.All -> flags
ExperimentStatusFilter.Enabled -> flags.filter { it.enabled }
ExperimentStatusFilter.Disabled -> flags.filter { !it.enabled }
}
+ val q = searchQuery.trim().lowercase()
+ if (q.isNotEmpty()) {
+ list = list.filter { f ->
+ f.key.lowercase().contains(q) || f.description.lowercase().contains(q)
+ }
+ }
+ if (selectedTags.isNotEmpty()) {
+ list = list.filter { f -> f.tags.any { it.value in selectedTags } }
+ }
+ list
}
+ val sortedFlags = remember(filteredFlags, sortColumn, sortAscending) {
+ var result = filteredFlags
+ sortColumn?.let { col ->
+ result = when (col) {
+ "key" -> result.sortedBy { it.key }
+ "description" -> result.sortedBy { it.description }
+ "updatedAt" -> result.sortedBy { it.updatedAt ?: "" }
+ "status" -> result.sortedBy { it.enabled }
+ else -> result
+ }
+ if (!sortAscending) result = result.reversed()
+ }
+ result
+ }
+
+ val groupedByTag = remember(sortedFlags, groupByTag) {
+ if (!groupByTag) null
+ else sortedFlags
+ .groupBy { f -> f.tags.firstOrNull()?.value ?: NO_TAGS_GROUP_KEY }
+ .toList()
+ .sortedBy { (k, _) -> if (k == NO_TAGS_GROUP_KEY) "zzz" else k }
+ .associate { it.first to it.second }
+ }
+
+ fun sortBy(column: String) {
+ if (sortColumn == column) sortAscending = !sortAscending
+ else { sortColumn = column; sortAscending = true }
+ }
+
+ val hasActiveFilters = searchQuery.isNotBlank() || selectedTags.isNotEmpty()
+
Div({
style {
padding(0.px)
@@ -127,16 +183,43 @@ fun ExperimentsPage() {
}
}
} else {
- // Always show filter bar when not loading/error so user can change filter when result is empty
Div({
style {
+ marginBottom(16.px)
display(DisplayStyle.Flex)
flexWrap(FlexWrap.Wrap)
alignItems(AlignItems.Center)
gap(12.px)
- marginBottom(16.px)
}
}) {
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ flex(1)
+ property("min-width", "200px")
+ }
+ }) {
+ Span({
+ classes("material-icons")
+ style { fontSize(20.px); color(FlagentTheme.textLight(themeMode)) }
+ }) { Text("search") }
+ Input(InputType.Text) {
+ value(searchQuery)
+ onInput { event -> searchQuery = event.value }
+ attr("placeholder", LocalizedStrings.searchExperimentsPlaceholder)
+ style {
+ flex(1)
+ padding(8.px, 12.px)
+ borderRadius(6.px)
+ border(1.px, LineStyle.Solid, FlagentTheme.inputBorder(themeMode))
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ fontSize(14.px)
+ }
+ }
+ }
listOf(
ExperimentStatusFilter.All to LocalizedStrings.filterAll,
ExperimentStatusFilter.Enabled to LocalizedStrings.enabled,
@@ -157,6 +240,26 @@ fun ExperimentsPage() {
Text(label)
}
}
+ FilterChip(themeMode, LocalizedStrings.groupByTags, groupByTag, onClick = { groupByTag = !groupByTag })
+ if (hasActiveFilters) {
+ Button({
+ style {
+ padding(6.px, 12.px)
+ fontSize(12.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
+ borderRadius(16.px)
+ cursor("pointer")
+ }
+ onClick {
+ searchQuery = ""
+ selectedTags.clear()
+ }
+ }) {
+ Text(LocalizedStrings.clearFilters)
+ }
+ }
Span({ style { marginLeft(8.px); color(FlagentTheme.textLight(themeMode)); fontSize(13.px) } }) { Text("•") }
Button({
style {
@@ -195,10 +298,58 @@ fun ExperimentsPage() {
fontSize(14.px)
}
}) {
- Text("${filteredFlags.size} ${LocalizedStrings.experimentsCount}")
+ Text("${sortedFlags.size} ${LocalizedStrings.experimentsCount}")
+ }
+ }
+ if (availableTagsState.value.isNotEmpty() && selectedTags.size < 12) {
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ flexWrap(FlexWrap.Wrap)
+ gap(6.px)
+ alignItems(AlignItems.Center)
+ marginBottom(12.px)
+ }
+ }) {
+ selectedTags.forEach { tagValue: String ->
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(4.px)
+ padding(6.px, 10.px)
+ backgroundColor(FlagentTheme.PrimaryLight)
+ color(FlagentTheme.PrimaryDark)
+ borderRadius(16.px)
+ fontSize(12.px)
+ cursor("pointer")
+ }
+ onClick { selectedTags.remove(tagValue) }
+ }) {
+ Text(tagValue)
+ Icon("close", size = 14.px, color = FlagentTheme.PrimaryDark)
+ }
+ }
+ availableTagsState.value.filter { it.value !in selectedTags }.take(8).forEach { tag ->
+ Span({
+ style {
+ display(DisplayStyle.InlineBlock)
+ padding(6.px, 10.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
+ borderRadius(16.px)
+ fontSize(12.px)
+ cursor("pointer")
+ }
+ onClick { selectedTags.add(tag.value) }
+ }) {
+ Text("+ ${tag.value}")
+ }
+ }
}
}
- if (filteredFlags.isEmpty()) {
+ if (sortedFlags.isEmpty()) {
Div({
style {
backgroundColor(FlagentTheme.cardBg(themeMode))
@@ -230,9 +381,28 @@ fun ExperimentsPage() {
}) {
Text(
if (flags.isEmpty()) LocalizedStrings.noExperimentsHint
+ else if (hasActiveFilters) LocalizedStrings.noExperimentsChangeFilterHint
else LocalizedStrings.noExperimentsChangeFilterHint
)
}
+ if (hasActiveFilters) {
+ Button({
+ style {
+ marginTop(12.px)
+ marginRight(8.px)
+ padding(8.px, 16.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border(0.px)
+ borderRadius(6.px)
+ cursor("pointer")
+ fontSize(14.px)
+ }
+ onClick { searchQuery = ""; selectedTags.clear() }
+ }) {
+ Text(LocalizedStrings.clearSearch)
+ }
+ }
Button({
style {
marginTop(20.px)
@@ -249,6 +419,132 @@ fun ExperimentsPage() {
Text(LocalizedStrings.viewFlags)
}
}
+ } else if (groupedByTag != null) {
+ groupedByTag.entries.forEach { (tagKey, list) ->
+ Div({
+ style {
+ marginBottom(24.px)
+ }
+ }) {
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ marginBottom(12.px)
+ padding(12.px, 16.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ borderRadius(8.px)
+ property("border-left", "4px solid ${FlagentTheme.Primary}")
+ }
+ }) {
+ Icon("local_offer", size = 18.px, color = FlagentTheme.Primary)
+ Text(if (tagKey == NO_TAGS_GROUP_KEY) LocalizedStrings.noTagsGroup else tagKey)
+ Span({ style { color(FlagentTheme.textLight(themeMode)); fontSize(13.px) } }) {
+ Text(" (${list.size})")
+ }
+ }
+ if (viewCards) {
+ Div({
+ style {
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fill, minmax(280px, 1fr))")
+ gap(16.px)
+ }
+ }) {
+ list.forEach { flag -> ExperimentCard(flag = flag) }
+ }
+ } else {
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ overflow("hidden")
+ property("box-shadow", "0 1px 3px ${FlagentTheme.Shadow}")
+ }
+ }) {
+ Table({
+ style { width(100.percent); property("border-collapse", "collapse") }
+ }) {
+ Thead {
+ Tr({
+ style {
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ }
+ }) {
+ listOf(LocalizedStrings.flagKey, LocalizedStrings.description, LocalizedStrings.variants, LocalizedStrings.status, LocalizedStrings.action).forEach { h ->
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ }
+ }) { Text(h) }
+ }
+ }
+ }
+ Tbody {
+ list.forEach { flag ->
+ Tr({
+ style {
+ property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ property("transition", "background-color 0.15s")
+ }
+ onMouseEnter { (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = FlagentTheme.inputBg(themeMode).toString() }
+ onMouseLeave { (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = "transparent" }
+ }) {
+ Td({
+ style { padding(10.px, 12.px); fontSize(14.px); color(FlagentTheme.Primary); cursor("pointer") }
+ onClick { Router.navigateTo(Route.FlagDetail(flag.id)) }
+ }) { Text(flag.key.ifBlank { "Flag #${flag.id}" }) }
+ Td({ style { padding(10.px, 12.px); fontSize(14.px); property("max-width", "200px"); property("overflow", "hidden"); property("text-overflow", "ellipsis"); property("white-space", "nowrap") } }) {
+ Text(flag.description.ifBlank { "—" })
+ }
+ Td({ style { padding(10.px, 12.px); fontSize(14.px) } }) {
+ Text(flag.variants.joinToString(", ") { it.key })
+ }
+ Td({ style { padding(10.px, 12.px); fontSize(12.px) } }) {
+ Span({
+ style {
+ padding(4.px, 8.px)
+ borderRadius(6.px)
+ backgroundColor(if (flag.enabled) FlagentTheme.successBg(themeMode) else FlagentTheme.inputBg(themeMode))
+ color(if (flag.enabled) FlagentTheme.Success else FlagentTheme.textLight(themeMode))
+ }
+ }) { Text(if (flag.enabled) LocalizedStrings.enabled else LocalizedStrings.disabled) }
+ }
+ Td({ style { padding(10.px, 12.px) } }) {
+ Div({ style { display(DisplayStyle.Flex); gap(8.px); flexWrap(FlexWrap.Wrap) } }) {
+ if (AppConfig.Features.enableMetrics) {
+ Button({
+ style { padding(6.px, 10.px); backgroundColor(FlagentTheme.Primary); color(Color.white); border(0.px); borderRadius(6.px); cursor("pointer"); fontSize(12.px) }
+ onClick { Router.navigateTo(Route.FlagMetrics(flag.id)) }
+ }) {
+ Icon("bar_chart", size = 14.px, color = FlagentTheme.Background)
+ Text(LocalizedStrings.viewMetrics)
+ }
+ }
+ Button({
+ style { padding(6.px, 10.px); backgroundColor(FlagentTheme.inputBg(themeMode)); color(FlagentTheme.text(themeMode)); border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode)); borderRadius(6.px); cursor("pointer"); fontSize(12.px) }
+ onClick { Router.navigateTo(Route.FlagDetail(flag.id)) }
+ }) {
+ Icon("settings", size = 14.px)
+ Text(LocalizedStrings.edit)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
} else if (viewCards) {
Div({
style {
@@ -257,7 +553,7 @@ fun ExperimentsPage() {
gap(16.px)
}
}) {
- filteredFlags.forEach { flag ->
+ sortedFlags.forEach { flag ->
ExperimentCard(flag = flag)
}
}
@@ -283,22 +579,93 @@ fun ExperimentsPage() {
property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
}
}) {
- listOf(LocalizedStrings.flagKey, LocalizedStrings.description, LocalizedStrings.variants, LocalizedStrings.status, LocalizedStrings.action).forEach { h ->
- Th({
- style {
- padding(10.px, 12.px)
- textAlign("left")
- fontSize(12.px)
- fontWeight(600)
- color(FlagentTheme.textLight(themeMode))
- property("text-transform", "uppercase")
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("key") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.flagKey)
+ if (sortColumn == "key") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("description") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.description)
+ if (sortColumn == "description") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ }
+ }) { Text(LocalizedStrings.variants) }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("status") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.status)
+ if (sortColumn == "status") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
}
- }) { Text(h) }
+ }
}
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ }
+ }) { Text(LocalizedStrings.action) }
}
}
Tbody {
- filteredFlags.forEach { flag ->
+ sortedFlags.forEach { flag ->
Tr({
style {
property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/flags/CreateFlagModal.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/flags/CreateFlagModal.kt
index e17d8d22..139c1cb2 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/flags/CreateFlagModal.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/flags/CreateFlagModal.kt
@@ -1,7 +1,11 @@
package flagent.frontend.components.flags
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import flagent.frontend.components.Icon
+import kotlinx.browser.document
+import org.w3c.dom.events.Event
+import org.w3c.dom.events.KeyboardEvent
import flagent.frontend.i18n.LocalizedStrings
import flagent.frontend.state.LocalThemeMode
import flagent.frontend.state.ThemeMode
@@ -22,6 +26,17 @@ fun CreateFlagModal(
onSelectFullForm: () -> Unit
) {
val themeMode = LocalThemeMode.current
+ DisposableEffect(Unit) {
+ val handler: (KeyboardEvent) -> Unit = { e ->
+ if (e.key == "Escape") {
+ e.preventDefault()
+ onClose()
+ }
+ }
+ val wrapped: (Event) -> Unit = { handler(it.unsafeCast()) }
+ document.addEventListener("keydown", wrapped)
+ onDispose { document.removeEventListener("keydown", wrapped) }
+ }
Div({
style {
position(Position.Fixed)
@@ -50,6 +65,7 @@ fun CreateFlagModal(
borderRadius(12.px)
width(100.percent)
property("max-width", "520px")
+ margin(24.px)
border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
property("box-shadow", FlagentTheme.ShadowModal)
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/BlogPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/BlogPage.kt
index 92b3b9c6..8626c36b 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/BlogPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/BlogPage.kt
@@ -25,15 +25,20 @@ fun BlogPage() {
minHeight(100.vh)
overflow("hidden")
paddingTop(80.px)
- property(
- "background",
- FlagentTheme.GradientHero
- )
- property("background-size", "400% 400%")
- property("animation", "morphGradient 20s ease infinite")
property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif")
}
}) {
+ Div(attrs = {
+ style {
+ position(Position.Fixed)
+ property("inset", "0")
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property("background", FlagentTheme.GradientHero)
+ property("background-size", "400% 400%")
+ property("animation", "morphGradient 20s ease infinite")
+ }
+ }) {}
LandingBackgroundShapes()
Div(attrs = {
style {
@@ -91,7 +96,7 @@ fun BlogPage() {
}) {
Input(InputType.Email, attrs = {
value(email.value)
- onInput { email.value = (it.target as org.w3c.dom.HTMLInputElement).value }
+ onInput { email.value = it.target.value }
style {
padding(14.px, 20.px)
width(280.px)
@@ -117,7 +122,7 @@ fun BlogPage() {
fontSize(15.px)
fontWeight(600)
}
- // Newsletter: Coming soon — see internal/docs/tasks/TODO-plan.md
+ // Newsletter: Coming soon — see internal/private docs
onClick { /* Coming soon — no backend yet */ }
}) {
Text("Subscribe")
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingFooter.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingFooter.kt
index 549aa170..1550f156 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingFooter.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingFooter.kt
@@ -1,11 +1,16 @@
package flagent.frontend.components.landing
import androidx.compose.runtime.*
+import flagent.frontend.api.ApiClient
import flagent.frontend.components.Icon
import flagent.frontend.config.AppConfig
import flagent.frontend.navigation.Route
import flagent.frontend.navigation.Router
+import flagent.frontend.state.LocalGlobalState
+import flagent.frontend.state.Notification
+import flagent.frontend.state.NotificationType
import flagent.frontend.theme.FlagentTheme
+import kotlinx.coroutines.launch
import org.jetbrains.compose.web.attributes.InputType
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
@@ -16,6 +21,9 @@ import org.jetbrains.compose.web.dom.*
@Composable
fun LandingFooter() {
val email = remember { mutableStateOf("") }
+ val globalState = LocalGlobalState.current
+ val scope = rememberCoroutineScope()
+ val subscribing = remember { mutableStateOf(false) }
Div(attrs = {
style {
@@ -49,7 +57,10 @@ fun LandingFooter() {
margin(0.px)
}
}) {
- Text("Flagent reduces the risk of releasing new features, drives innovation by streamlining software releases, and increases revenue by optimizing end-user experience.")
+ Text(
+ "Flagent reduces release risk and drives innovation: ship behind flags, roll back in one click without redeploying, and run A/B tests with type-safe SDKs. " +
+ "Open source, self-host free, with an OpenFeature-style Kotlin Multiplatform client when you want vendor-agnostic integration."
+ )
}
Div(attrs = {
style {
@@ -117,7 +128,7 @@ fun LandingFooter() {
"Documentation" to AppConfig.docsUrl,
"API Reference" to "${AppConfig.docsUrl}api-docs.html",
"GitHub" to AppConfig.githubUrl,
- "Roadmap" to "${AppConfig.docsUrl}guides/roadmap.md"
+ "Roadmap" to "${AppConfig.docsUrl}#/guides/roadmap"
))
FooterColumn("Product", listOf(
"Feature Flags" to Route.FlagsList.PATH,
@@ -152,7 +163,7 @@ fun LandingFooter() {
}) {
Input(InputType.Email, attrs = {
value(email.value)
- onInput { email.value = (it.target as org.w3c.dom.HTMLInputElement).value }
+ onInput { email.value = it.target.value }
style {
padding(10.px, 14.px)
width(180.px)
@@ -174,23 +185,32 @@ fun LandingFooter() {
color(Color.white)
border(0.px)
borderRadius(8.px)
- cursor("pointer")
+ cursor(if (subscribing.value) "wait" else "pointer")
fontSize(14.px)
fontWeight(500)
}
- // Newsletter: Coming soon — wire to backend or Mailchimp/SendGrid when ready; see internal/docs/tasks/TODO-plan.md
- onClick { /* Coming soon — no backend yet */ }
- }) {
- Text("Subscribe")
- }
- Span(attrs = {
- style {
- marginLeft(8.px)
- fontSize(12.px)
- color(Color("rgba(255,255,255,0.6)"))
+ onClick {
+ val addr = email.value.trim()
+ if (addr.isBlank()) {
+ globalState.addNotification(Notification(message = "Enter your email", type = NotificationType.WARNING))
+ return@onClick
+ }
+ subscribing.value = true
+ scope.launch {
+ try {
+ ApiClient.subscribeNewsletter(addr)
+ globalState.addNotification(Notification(message = "Subscribed successfully", type = NotificationType.SUCCESS))
+ email.value = ""
+ } catch (e: Throwable) {
+ val msg = e.message?.takeIf { it.isNotBlank() } ?: "Subscription failed"
+ globalState.addNotification(Notification(message = msg, type = NotificationType.ERROR))
+ } finally {
+ subscribing.value = false
+ }
+ }
}
}) {
- Text("(Coming soon)")
+ Text(if (subscribing.value) "…" else "Subscribe")
}
}
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingNavbar.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingNavbar.kt
index ef2bfddf..350d3f7e 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingNavbar.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/LandingNavbar.kt
@@ -5,6 +5,9 @@ import flagent.frontend.components.Icon
import flagent.frontend.config.AppConfig
import flagent.frontend.navigation.Route
import flagent.frontend.navigation.Router
+import flagent.frontend.state.LocalThemeMode
+import flagent.frontend.state.ThemeMode
+import flagent.frontend.state.ThemeState
import flagent.frontend.theme.FlagentTheme
import kotlinx.browser.document
import kotlinx.browser.window
@@ -22,6 +25,7 @@ fun LandingNavbar() {
val isMobile = remember { mutableStateOf(false) }
val activeLink = remember { mutableStateOf(null) }
val route = Router.currentRoute
+ val themeMode = LocalThemeMode.current
DisposableEffect(route) {
val listener: (dynamic) -> Unit = {
@@ -223,6 +227,42 @@ fun LandingNavbar() {
Icon("code", size = 18.px, color = Color.white)
Text("GitHub")
}
+ Button(attrs = {
+ style {
+ padding(8.px, 10.px)
+ backgroundColor(Color.transparent)
+ color(Color("rgba(255,255,255,0.9)"))
+ border(0.px)
+ borderRadius(999.px)
+ cursor("pointer")
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ fontSize(13.px)
+ property("transition", "all 0.2s ease")
+ }
+ onClick { ThemeState.toggle() }
+ onMouseEnter {
+ (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = "rgba(15,23,42,0.4)"
+ }
+ onMouseLeave {
+ (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = "transparent"
+ }
+ }) {
+ Icon(
+ if (themeMode == ThemeMode.Dark) "light_mode" else "dark_mode",
+ size = 18.px,
+ color = FlagentTheme.Background
+ )
+ Span(attrs = {
+ style {
+ fontSize(12.px)
+ color(Color("rgba(255,255,255,0.85)"))
+ }
+ }) {
+ Text(if (themeMode == ThemeMode.Dark) "Light" else "Dark")
+ }
+ }
}
}
}
@@ -257,6 +297,7 @@ fun LandingNavbar() {
fontSize(14.px)
padding(12.px, 0.px)
}
+ onClick { menuOpen.value = false }
}) { Text("Blog") }
A(href = AppConfig.docsUrl, attrs = {
attr("target", "_blank")
@@ -267,6 +308,7 @@ fun LandingNavbar() {
fontSize(14.px)
padding(12.px, 0.px)
}
+ onClick { menuOpen.value = false }
}) { Text("Docs") }
if (AppConfig.requiresAuth) {
Button(attrs = {
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/MarketingLanding.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/MarketingLanding.kt
index 3228485d..94e103eb 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/MarketingLanding.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/MarketingLanding.kt
@@ -1,10 +1,17 @@
package flagent.frontend.components.landing
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import flagent.frontend.components.Icon
import flagent.frontend.config.AppConfig
import flagent.frontend.navigation.Route
import flagent.frontend.navigation.Router
+import flagent.frontend.state.LocalThemeMode
+import flagent.frontend.state.ThemeMode
+import flagent.frontend.theme.AppGradientBackground
import flagent.frontend.theme.FlagentTheme
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
@@ -15,33 +22,29 @@ import org.jetbrains.compose.web.dom.*
*/
@Composable
fun MarketingLanding() {
+ val themeMode = LocalThemeMode.current
LandingNavbar()
- Div(attrs = {
- classes("landing-page")
- style {
- position(Position.Relative)
- minHeight(100.vh)
- overflow("hidden")
- paddingTop(80.px)
- property(
- "background",
- FlagentTheme.GradientHero
- )
- property("background-size", "400% 400%")
- property("animation", "morphGradient 20s ease infinite")
- property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif")
- }
- }) {
- LandingBackgroundShapes()
+ AppGradientBackground(mode = themeMode) {
Div(attrs = {
+ classes("landing-page")
style {
position(Position.Relative)
- padding(48.px, 24.px)
- maxWidth(1100.px)
- property("margin", "0 auto")
- property("z-index", "1")
+ minHeight(100.vh)
+ overflow("hidden")
+ paddingTop(80.px)
+ property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif")
}
}) {
+ LandingBackgroundShapes(themeMode)
+ Div(attrs = {
+ style {
+ position(Position.Relative)
+ padding(48.px, 24.px)
+ maxWidth(1100.px)
+ property("margin", "0 auto")
+ property("z-index", "1")
+ }
+ }) {
Div(attrs = {
id("hero-section")
classes("reveal-on-scroll")
@@ -49,80 +52,125 @@ fun MarketingLanding() {
}) {
HeroSection()
}
+ Div(attrs = {
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ }) {
+ CodeSnippetSection()
+ }
Div(attrs = {
classes("reveal-on-scroll")
attr("data-reveal", "true")
}) {
FeaturesSection()
}
+ Div(attrs = {
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ }) {
+ RoadmapSection()
+ }
+ Div(attrs = {
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ }) {
+ TrustSection()
+ }
+ Div(attrs = {
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ }) {
+ SdksSection()
+ }
Div(attrs = {
classes("reveal-on-scroll")
attr("data-reveal", "true")
}) {
UseCasesSection()
}
- }
- Div(attrs = {
- classes("reveal-on-scroll")
- attr("data-reveal", "true")
- }) {
- LandingFooter()
+ Div(attrs = {
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ }) {
+ QuickFactsSection()
+ }
+ Div(attrs = {
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ style { marginTop(64.px) }
+ }) {
+ EnterpriseSection()
+ }
+ }
+ Div(attrs = {
+ style { position(Position.Relative); property("z-index", "1") }
+ classes("reveal-on-scroll")
+ attr("data-reveal", "true")
+ }) {
+ LandingFooter()
+ }
}
}
}
@Composable
-fun LandingBackgroundShapes() {
+fun LandingBackgroundShapes(themeMode: ThemeMode = ThemeMode.Dark) {
+ val isLight = themeMode == ThemeMode.Light
+ val dotOpacity = if (isLight) 0.06 else 0.12
+ val blob1 = if (isLight) "rgba(14, 165, 233, 0.09)" else "rgba(14, 165, 233, 0.2)"
+ val blob2 = if (isLight) "rgba(20, 184, 166, 0.08)" else "rgba(20, 184, 166, 0.18)"
+ val blob3 = if (isLight) "rgba(14, 165, 233, 0.07)" else "rgba(14, 165, 233, 0.15)"
Div(attrs = {
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("inset", "0")
- property(
- "background-image",
- "radial-gradient(rgba(14, 165, 233, 0.12) 1px, transparent 1px)"
- )
- property("background-size", "28px 28px")
+ property("z-index", "0")
property("pointer-events", "none")
+ property("background-image", "radial-gradient(rgba(14, 165, 233, $dotOpacity) 1px, transparent 1px)")
+ property("background-size", "28px 28px")
}
}) {}
Div(attrs = {
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("top", "-8%")
property("right", "-3%")
width(450.px)
height(450.px)
borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(14, 165, 233, 0.2) 0%, transparent 65%)")
- property("animation", "float 14s ease-in-out infinite")
+ property("z-index", "0")
property("pointer-events", "none")
+ property("background", "radial-gradient(circle, $blob1 0%, transparent 65%)")
+ property("animation", "float 14s ease-in-out infinite")
}
}) {}
Div(attrs = {
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("bottom", "-12%")
property("left", "-6%")
width(500.px)
height(500.px)
borderRadius(50.percent)
- property("background", "radial-gradient(circle, rgba(20, 184, 166, 0.18) 0%, transparent 65%)")
- property("animation", "floatSlow 20s ease-in-out infinite")
+ property("z-index", "0")
property("pointer-events", "none")
+ property("background", "radial-gradient(circle, $blob2 0%, transparent 65%)")
+ property("animation", "floatSlow 20s ease-in-out infinite")
}
}) {}
Div(attrs = {
style {
- position(Position.Absolute)
+ position(Position.Fixed)
property("top", "-15%")
property("left", "50%")
property("transform", "translateX(-50%)")
width(600.px)
height(400.px)
borderRadius(50.percent)
- property("background", "radial-gradient(ellipse, rgba(14, 165, 233, 0.15) 0%, transparent 70%)")
- property("animation", "glowPulse 10s ease-in-out infinite")
+ property("z-index", "0")
property("pointer-events", "none")
+ property("background", "radial-gradient(ellipse, $blob3 0%, transparent 70%)")
+ property("animation", "glowPulse 10s ease-in-out infinite")
}
}) {}
}
@@ -162,11 +210,20 @@ private fun HeroSection() {
fontSize(52.px)
fontWeight(700)
color(Color.white)
- marginBottom(20.px)
+ marginBottom(12.px)
property("letter-spacing", "-0.03em")
property("line-height", "1.15")
}
- }) { Text("Ship Features Safely. Experiment Confidently.") }
+ }) { Text("Flagent — feature flags & A/B tests in one place") }
+ P(attrs = {
+ style {
+ fontSize(16.px)
+ color(FlagentTheme.PrimaryLight)
+ fontWeight(600)
+ marginBottom(16.px)
+ property("letter-spacing", "0.02em")
+ }
+ }) { Text("The only feature-flag platform built on Kotlin Multiplatform. Self-host free, upgrade when you need it.") }
P(attrs = {
classes("hero-subtitle")
style {
@@ -177,7 +234,7 @@ private fun HeroSection() {
property("margin", "0 auto 40px")
}
}) {
- Text("Feature flags, A/B testing, and gradual rollouts. Reduce release risk, run experiments, and roll back instantly — without redeploying.")
+ Text("Toggle features, run experiments, and roll back in one click — without redeploying. Type-safe SDKs for Kotlin, JS, Swift, Python, Go.")
}
Div(attrs = {
style {
@@ -225,19 +282,58 @@ private fun HeroSection() {
Text("Sign in")
}
}
- Button(attrs = {
+ A(href = AppConfig.gettingStartedUrl, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ gap(8.px)
+ padding(18.px, 36.px)
+ property(
+ "background",
+ "linear-gradient(135deg, ${FlagentTheme.Primary} 0%, ${FlagentTheme.PrimaryDark} 100%)"
+ )
+ color(Color.white)
+ textDecoration("none")
+ border(0.px)
+ borderRadius(12.px)
+ fontSize(16.px)
+ fontWeight(600)
+ property("box-shadow", "0 8px 24px rgba(14, 165, 233, 0.45)")
+ property("transition", "all 0.25s cubic-bezier(0.4, 0, 0.2, 1)")
+ }
+ onMouseEnter {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.transform = "translateY(-3px) scale(1.02)"
+ el.style.setProperty("box-shadow", "0 12px 32px rgba(14, 165, 233, 0.55)")
+ }
+ onMouseLeave {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.transform = "translateY(0) scale(1)"
+ el.style.setProperty("box-shadow", "0 8px 24px rgba(14, 165, 233, 0.45)")
+ }
+ }) {
+ Icon("rocket_launch", size = 20.px, color = Color.white)
+ Text("Start free (self-host)")
+ }
+ A(href = "mailto:${AppConfig.enterpriseContactEmail}?subject=Flagent%20Enterprise%20%2F%20Request%20demo", attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ gap(8.px)
padding(18.px, 36.px)
backgroundColor(Color.transparent)
color(FlagentTheme.PrimaryLight)
border(2.px, LineStyle.Solid, Color("rgba(14, 165, 233, 0.6)"))
borderRadius(12.px)
- cursor("pointer")
+ textDecoration("none")
fontSize(16.px)
fontWeight(600)
property("transition", "all 0.25s ease")
}
- onClick { Router.navigateTo(Route.Dashboard) }
onMouseEnter {
val el = it.target as org.w3c.dom.HTMLElement
el.style.backgroundColor = "rgba(14, 165, 233, 0.15)"
@@ -251,7 +347,38 @@ private fun HeroSection() {
el.style.transform = "translateY(0) scale(1)"
}
}) {
- Text("Get Started")
+ Icon("business_center", size = 20.px, color = FlagentTheme.PrimaryLight)
+ Text("Request demo")
+ }
+ if (!AppConfig.requiresAuth) {
+ Button(attrs = {
+ style {
+ padding(18.px, 36.px)
+ backgroundColor(Color.transparent)
+ color(FlagentTheme.PrimaryLight)
+ border(2.px, LineStyle.Solid, Color("rgba(14, 165, 233, 0.6)"))
+ borderRadius(12.px)
+ cursor("pointer")
+ fontSize(16.px)
+ fontWeight(600)
+ property("transition", "all 0.25s ease")
+ }
+ onClick { Router.navigateTo(Route.Dashboard) }
+ onMouseEnter {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.backgroundColor = "rgba(14, 165, 233, 0.15)"
+ el.style.borderColor = FlagentTheme.PrimaryLight.toString()
+ el.style.transform = "translateY(-2px) scale(1.02)"
+ }
+ onMouseLeave {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.backgroundColor = "transparent"
+ el.style.borderColor = "rgba(14, 165, 233, 0.6)"
+ el.style.transform = "translateY(0) scale(1)"
+ }
+ }) {
+ Text("Get Started")
+ }
}
A(href = AppConfig.githubUrl, attrs = {
attr("target", "_blank")
@@ -283,11 +410,12 @@ private fun HeroSection() {
}
P(attrs = {
style {
- marginTop(32.px)
+ marginTop(28.px)
fontSize(14.px)
color(Color("rgba(255,255,255,0.55)"))
}
}) {
+ Text("Built for Kotlin and multiplatform teams. ")
A(href = AppConfig.docsUrl, attrs = {
attr("target", "_blank")
attr("rel", "noopener noreferrer")
@@ -296,7 +424,7 @@ private fun HeroSection() {
textDecoration("none")
}
}) {
- Text("Powered by open source Flagent")
+ Text("Open source · Docs")
}
}
Div(attrs = {
@@ -330,24 +458,384 @@ private fun HeroSection() {
}
Div(attrs = {
style {
- padding(80.px)
+ padding(0.px)
property("background", "linear-gradient(180deg, rgba(15,23,42,0.95) 0%, rgba(30,41,59,0.9) 100%)")
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Column)
alignItems(AlignItems.Center)
justifyContent(JustifyContent.Center)
- gap(16.px)
+ overflow("hidden")
+ }
+ }) {
+ Img(
+ src = "/screenshot-dashboard.png",
+ attrs = {
+ style {
+ width(100.percent)
+ property("max-width", "900px")
+ property("object-fit", "contain")
+ property("display", "block")
+ }
+ attr("alt", "Flagent Dashboard")
+ }
+ )
+ }
+ }
+ }
+}
+
+private data class CodeExample(val lang: String, val code: String)
+
+@Composable
+private fun CodeSnippetSection() {
+ val examples = listOf(
+ CodeExample("Kotlin", """val client = FlagentClient.create(baseUrl = "http://localhost:18000/api/v1")
+val result = client.evaluate(flagKey = "new_checkout", entityID = "user123")
+if (result.variantKey == "enabled") {
+ NewCheckoutScreen()
+} else {
+ LegacyCheckout()
+}"""),
+ CodeExample("JavaScript", """import { FlagentClient } from '@flagent/client';
+const client = new FlagentClient({ baseUrl: 'http://localhost:18000/api/v1' });
+const result = await client.evaluate({ flagKey: 'new_checkout', entityID: 'user123' });
+if (result.variantKey === 'enabled') NewCheckoutScreen();
+else LegacyCheckout();"""),
+ CodeExample("Swift", """let client = FlagentClient(baseURL: "http://localhost:18000/api/v1")
+let result = try await client.evaluate(flagKey: "new_checkout", entityID: "user123")
+if result.variantKey == "enabled" { NewCheckoutScreen() }
+else { LegacyCheckout() }"""),
+ CodeExample("Python", """from flagent import create_client
+client = create_client("http://localhost:18000/api/v1")
+result = await client.evaluate(flag_key="new_checkout", entity_id="user123")
+if result.is_enabled(): NewCheckoutScreen()
+else: LegacyCheckout()"""),
+ CodeExample("Go", """result, _ := client.Evaluate(ctx, &flagent.EvaluationContext{
+ FlagKey: flagent.StringPtr("new_checkout"), EntityID: flagent.StringPtr("user123"),
+})
+if result.IsEnabled() { NewCheckoutScreen() } else { LegacyCheckout() }"""),
+ CodeExample("Flutter", """final client = Flagent.create(baseUrl: 'http://localhost:18000/api/v1');
+final result = await client.evaluate(flagKey: 'new_checkout', entityID: 'user123');
+if (result.variantKey == 'enabled') NewCheckoutScreen();
+else LegacyCheckout();"""),
+ )
+ var selectedIndex by remember { mutableStateOf(0) }
+ val selected = examples[selectedIndex]
+ Div(attrs = {
+ style { marginBottom(64.px) }
+ }) {
+ H2(attrs = {
+ style {
+ fontSize(22.px)
+ fontWeight(600)
+ color(Color.white)
+ textAlign("center")
+ marginBottom(12.px)
+ }
+ }) { Text("Integrate in minutes") }
+ P(attrs = {
+ style {
+ fontSize(15.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textAlign("center")
+ marginBottom(28.px)
+ }
+ }) { Text("Same API across Kotlin, JavaScript, Swift, Python, Go, Java, Flutter. Type-safe, offline-first.") }
+ Div(attrs = {
+ style {
+ maxWidth(640.px)
+ property("margin", "0 auto")
+ borderRadius(14.px)
+ property("border", "1px solid rgba(255,255,255,0.12)")
+ property("box-shadow", "0 20px 50px rgba(0,0,0,0.35)")
+ overflow("hidden")
+ }
+ }) {
+ Div(attrs = {
+ style {
+ padding(12.px, 16.px)
+ property("background", "rgba(0,0,0,0.35)")
+ property("border-bottom", "1px solid rgba(255,255,255,0.08)")
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(4.px)
+ flexWrap(FlexWrap.Wrap)
}
}) {
- Icon("dashboard", size = 64.px, color = FlagentTheme.PrimaryLight)
- Span(attrs = { style { fontSize(14.px); color(Color("rgba(255,255,255,0.5)")) } }) { Text("Dashboard preview") }
+ Div(attrs = { style { width(10.px); height(10.px); borderRadius(50.percent); backgroundColor(FlagentTheme.Error) } }) {}
+ Div(attrs = { style { width(10.px); height(10.px); borderRadius(50.percent); backgroundColor(FlagentTheme.Warning) } }) {}
+ Div(attrs = { style { width(10.px); height(10.px); borderRadius(50.percent); backgroundColor(FlagentTheme.Success) } }) {}
+ Span(attrs = { style { marginLeft(12.px); fontSize(12.px); color(Color("rgba(255,255,255,0.5)")) } }) { Text("Flagent · ${selected.lang}") }
+ Span(attrs = { style { flexGrow(1) } }) {}
+ examples.forEachIndexed { i, ex ->
+ Button(attrs = {
+ style {
+ padding(6.px, 12.px)
+ fontSize(12.px)
+ fontWeight(500)
+ borderRadius(6.px)
+ border(0.px)
+ cursor("pointer")
+ if (i == selectedIndex) {
+ property("background", "rgba(14, 165, 233, 0.35)")
+ color(Color.white)
+ } else {
+ backgroundColor(Color.transparent)
+ color(Color("rgba(255,255,255,0.7)"))
+ }
+ }
+ onClick { selectedIndex = i }
+ }) { Text(ex.lang) }
+ }
+ }
+ Div(attrs = {
+ style {
+ padding(20.px, 24.px)
+ property("background", "rgba(15, 23, 42, 0.95)")
+ property("font-family", "'JetBrains Mono', 'Fira Code', monospace")
+ fontSize(13.px)
+ lineHeight("1.6")
+ color(Color("rgba(255,255,255,0.92)"))
+ }
+ }) {
+ Pre(attrs = {
+ style {
+ margin(0.px)
+ whiteSpace("pre-wrap")
+ property("word-break", "break-word")
+ }
+ }) { Text(selected.code) }
+ }
+ }
+ Div(attrs = { style { textAlign("center"); marginTop(20.px) } }) {
+ A(href = AppConfig.gettingStartedUrl, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style {
+ color(FlagentTheme.PrimaryLight)
+ textDecoration("none")
+ fontSize(14.px)
+ fontWeight(600)
+ }
+ }) { Text("View full Quick Start →") }
+ }
+ }
+}
+
+private val SDK_LINKS = listOf(
+ "Kotlin" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/kotlin",
+ "Ktor" to "https://github.com/MaxLuxs/Flagent/tree/main/ktor-flagent",
+ "JavaScript" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/javascript",
+ "Swift" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/swift",
+ "Python" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/python",
+ "Go" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/go",
+ "Java" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/java",
+ "Flutter" to "https://github.com/MaxLuxs/Flagent/tree/main/sdk/flutter-enhanced",
+)
+
+@Composable
+private fun SdksSection() {
+ Div(attrs = {
+ style {
+ marginBottom(64.px)
+ padding(32.px, 24.px)
+ property("background", "rgba(255,255,255,0.03)")
+ property("border", "1px solid rgba(255,255,255,0.06)")
+ borderRadius(16.px)
+ }
+ }) {
+ P(attrs = {
+ style {
+ fontSize(14.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textAlign("center")
+ marginBottom(20.px)
+ }
+ }) { Text("One API. Every platform.") }
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ flexWrap(FlexWrap.Wrap)
+ gap(12.px)
+ justifyContent(JustifyContent.Center)
+ }
+ }) {
+ SDK_LINKS.forEach { (label, url) ->
+ A(href = url, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style {
+ padding(8.px, 16.px)
+ property("background", "rgba(255,255,255,0.06)")
+ borderRadius(8.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.85)"))
+ fontWeight(500)
+ textDecoration("none")
+ property("transition", "all 0.2s ease")
+ }
+ onMouseEnter {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.setProperty("background", "rgba(14, 165, 233, 0.2)")
+ el.style.color = "white"
+ }
+ onMouseLeave {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.setProperty("background", "rgba(255,255,255,0.06)")
+ el.style.color = "rgba(255,255,255,0.85)"
+ }
+ }) { Text(label) }
}
}
+ P(attrs = {
+ style {
+ textAlign("center")
+ marginTop(16.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.5)"))
+ }
+ }) {
+ A(href = AppConfig.docsUrlSdks, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style { color(FlagentTheme.PrimaryLight); textDecoration("none") }
+ }) { Text("SDKs overview in docs →") }
+ }
}
}
+private data class QuickFact(val icon: String, val title: String, val subtitle: String)
+
+@Composable
+private fun QuickFactsSection() {
+ val facts = listOf(
+ QuickFact("dns", "Self-hosted or cloud", "Your infra, Docker, or Flagent Cloud (coming soon)"),
+ QuickFact("verified", "Type-safe SDKs", "Kotlin, Swift, Go, JS, Python — compile-time safety"),
+ QuickFact("emergency", "Instant rollback", "Turn off any feature without redeploy"),
+ QuickFact("code", "Open source", "Apache 2.0 — transparent and extensible"),
+ QuickFact("rocket_launch", "Kotlin-native", "First feature-flag platform built with Ktor & KMP"),
+ )
+ Div(attrs = {
+ style {
+ marginBottom(64.px)
+ }
+ }) {
+ P(attrs = {
+ style {
+ fontSize(14.px)
+ color(Color("rgba(255,255,255,0.5)"))
+ textAlign("center")
+ marginBottom(20.px)
+ }
+ }) { Text("Highlights") }
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ flexWrap(FlexWrap.Wrap)
+ gap(16.px)
+ justifyContent(JustifyContent.Center)
+ }
+ }) {
+ facts.forEach { fact ->
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ flexDirection(FlexDirection.Column)
+ alignItems(AlignItems.Center)
+ padding(16.px, 20.px)
+ minWidth(160.px)
+ property("background", "rgba(255,255,255,0.04)")
+ property("border", "1px solid rgba(255,255,255,0.08)")
+ borderRadius(12.px)
+ property("transition", "all 0.2s ease")
+ }
+ onMouseEnter {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.setProperty("border-color", "rgba(14, 165, 233, 0.35)")
+ el.style.setProperty("background", "rgba(255,255,255,0.06)")
+ }
+ onMouseLeave {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.setProperty("border-color", "rgba(255,255,255,0.08)")
+ el.style.setProperty("background", "rgba(255,255,255,0.04)")
+ }
+ }) {
+ Div(attrs = {
+ style {
+ width(40.px)
+ height(40.px)
+ borderRadius(10.px)
+ property("background", "rgba(14, 165, 233, 0.15)")
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ marginBottom(10.px)
+ }
+ }) {
+ Icon(fact.icon, size = 22.px, color = FlagentTheme.PrimaryLight)
+ }
+ Span(attrs = {
+ style {
+ fontSize(14.px)
+ fontWeight(600)
+ color(Color.white)
+ textAlign("center")
+ }
+ }) { Text(fact.title) }
+ Span(attrs = {
+ style {
+ fontSize(12.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textAlign("center")
+ marginTop(4.px)
+ lineHeight("1.35")
+ }
+ }) { Text(fact.subtitle) }
+ }
+ }
+ }
+ }
+}
+
+/** Single feature for Why Flagent grid; route = null means no navigation (e.g. external link or just text). */
+private data class LandingFeature(
+ val icon: String,
+ val title: String,
+ val description: String,
+ val onClick: () -> Unit
+)
+
@Composable
private fun FeaturesSection() {
+ val features = listOf(
+ LandingFeature("flag", "Feature Flags", "Toggle features on or off without redeploying. Target by segments and attributes.") {
+ Router.navigateTo(Route.FlagsList)
+ },
+ LandingFeature("science", "A/B Testing", "Run experiments with variants. Deterministic bucketing (MurmurHash3), measure and roll out winners.") {
+ Router.navigateTo(Route.Experiments)
+ },
+ LandingFeature("trending_up", "Gradual Rollout", "Percentage-based rollouts with instant rollback. No redeploy needed.") {
+ Router.navigateTo(Route.Dashboard)
+ },
+ LandingFeature("emergency", "Kill Switches", "Disable features instantly when issues arise. Production safety without code changes.") {
+ Router.navigateTo(Route.FlagsList)
+ },
+ LandingFeature("segment", "Targeting & Segments", "Multi-environment, user attributes, and constraint rules. Target who sees what.") {
+ Router.navigateTo(Route.Segments)
+ },
+ LandingFeature("bug_report", "Debug Console", "Real-time evaluation testing. Inspect flag values and context in one place.") {
+ Router.navigateTo(Route.DebugConsole())
+ },
+ LandingFeature("analytics", "Analytics & Metrics", "Evaluation counts, events, core metrics. Data recorders: Kafka, Kinesis, PubSub. We're expanding dashboards and experiment insights.") {
+ Router.navigateTo(Route.Analytics)
+ },
+ LandingFeature("warning", "Crash Reporting", "Ingestion, list, stack traces. We're expanding: crash-by-flag correlation and richer UI (Enterprise).") {
+ Router.navigateTo(Route.Crash)
+ },
+ LandingFeature("code", "Ktor & 8 SDKs", "Ktor plugin, REST API. Type-safe: Kotlin, JS, Swift, Python, Go, Java, Flutter. Offline-first, SSE.") {
+ kotlinx.browser.window.open(AppConfig.docsUrlSdks, "_blank")
+ },
+ )
Div(attrs = {
style {
marginBottom(64.px)
@@ -359,28 +847,231 @@ private fun FeaturesSection() {
fontWeight(600)
color(Color.white)
textAlign("center")
- marginBottom(40.px)
+ marginBottom(12.px)
}
}) { Text("Why Flagent?") }
+ P(attrs = {
+ style {
+ fontSize(15.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textAlign("center")
+ maxWidth(560.px)
+ property("margin", "0 auto 32px")
+ lineHeight("1.5")
+ }
+ }) { Text("Feature flags, experiments, crash analytics, and integrations in one platform. Kotlin-native, self-hosted or cloud.") }
Div(attrs = {
classes("features-grid")
style {
display(DisplayStyle.Grid)
- property("grid-template-columns", "repeat(auto-fit, minmax(250px, 1fr))")
- gap(24.px)
+ property("grid-template-columns", "repeat(auto-fit, minmax(220px, 1fr))")
+ gap(18.px)
}
}) {
- MarketingFeatureCard(1, "flag", "Feature Flags", "Toggle features on or off without redeploying. Target users by segments and attributes.") {
- Router.navigateTo(Route.FlagsList)
+ features.forEach { f ->
+ MarketingFeatureCard(icon = f.icon, title = f.title, description = f.description, onClick = f.onClick)
+ }
+ }
+ P(attrs = {
+ style {
+ textAlign("center")
+ marginTop(24.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.5)"))
+ lineHeight("1.6")
+ }
+ }) {
+ Text("Also: ")
+ A(href = AppConfig.docsUrlGitOps, attrs = {
+ attr("target", "_blank"); attr("rel", "noopener noreferrer")
+ style { color(FlagentTheme.PrimaryLight); textDecoration("none") }
+ }) { Text("Import/Export") }
+ Text(" · ")
+ A(href = AppConfig.docsUrlGitOps, attrs = {
+ attr("target", "_blank"); attr("rel", "noopener noreferrer")
+ style { color(FlagentTheme.PrimaryLight); textDecoration("none") }
+ }) { Text("Webhooks") }
+ Text(" · ")
+ A(href = AppConfig.docsUrlRealtime, attrs = {
+ attr("target", "_blank"); attr("rel", "noopener noreferrer")
+ style { color(FlagentTheme.PrimaryLight); textDecoration("none") }
+ }) { Text("Realtime (SSE)") }
+ Text(" · ")
+ A(href = AppConfig.docsUrlMcp, attrs = {
+ attr("target", "_blank"); attr("rel", "noopener noreferrer")
+ style { color(FlagentTheme.PrimaryLight); textDecoration("none") }
+ }) { Text("MCP") }
+ Text(" · Multi-environment · JWT auth · Data recorders (Kafka, Kinesis, PubSub) · RBAC · Self-hosted · Offline-first eval · Anomaly detection · Smart Rollout · SSO · Audit log")
+ }
+ P(attrs = {
+ style {
+ textAlign("center")
+ marginTop(8.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.5)"))
+ }
+ }) {
+ A(href = AppConfig.docsUrl, attrs = {
+ attr("target", "_blank")
+ attr("rel", "noopener noreferrer")
+ style { color(FlagentTheme.PrimaryLight); textDecoration("none") }
+ }) { Text("Full feature list in docs →") }
+ }
+ }
+}
+
+@Composable
+private fun RoadmapSection() {
+ Div(attrs = {
+ style {
+ marginBottom(64.px)
+ padding(28.px, 24.px)
+ property("background", "linear-gradient(135deg, rgba(14, 165, 233, 0.08) 0%, rgba(20, 184, 166, 0.06) 100%)")
+ property("border", "1px solid rgba(14, 165, 233, 0.2)")
+ borderRadius(16.px)
+ }
+ }) {
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ gap(8.px)
+ marginBottom(16.px)
+ }
+ }) {
+ Span(attrs = {
+ style {
+ padding(4.px, 10.px)
+ property("background", "rgba(14, 165, 233, 0.25)")
+ borderRadius(20.px)
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.PrimaryLight)
+ property("letter-spacing", "0.02em")
+ }
+ }) { Text("Roadmap") }
+ }
+ H3(attrs = {
+ style {
+ fontSize(18.px)
+ fontWeight(600)
+ color(Color.white)
+ textAlign("center")
+ marginBottom(8.px)
}
- MarketingFeatureCard(2, "science", "A/B Testing", "Run experiments with variants. Measure impact and roll out winners confidently.") {
- Router.navigateTo(Route.Experiments)
+ }) { Text("Coming next: richer analytics & crash-by-flag") }
+ P(attrs = {
+ style {
+ fontSize(14.px)
+ color(Color("rgba(255,255,255,0.7)"))
+ textAlign("center")
+ maxWidth(520.px)
+ property("margin", "0 auto")
+ lineHeight("1.55")
}
- MarketingFeatureCard(3, "trending_up", "Gradual Rollout", "Release features gradually. Percentage-based rollouts with instant rollback.") {
- Router.navigateTo(Route.Dashboard)
+ }) {
+ Text("We're shipping enhanced analytics (evaluation metrics, experiment insights) and crash reporting with stack traces, grouping, and crash-by-flag correlation. Enterprise early access available.")
+ }
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ flexWrap(FlexWrap.Wrap)
+ gap(12.px)
+ justifyContent(JustifyContent.Center)
+ marginTop(16.px)
}
- MarketingFeatureCard(4, "emergency", "Kill Switches", "Disable features instantly when issues arise. No deployment required.") {
- Router.navigateTo(Route.FlagsList)
+ }) {
+ listOf("Analytics dashboard" to "analytics", "Crash reporting" to "bug_report").forEach { (label, iconName) ->
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ padding(10.px, 16.px)
+ property("background", "rgba(255,255,255,0.06)")
+ borderRadius(10.px)
+ property("border", "1px solid rgba(255,255,255,0.08)")
+ }
+ }) {
+ Icon(iconName, size = 18.px, color = FlagentTheme.PrimaryLight)
+ Span(attrs = { style { fontSize(13.px); color(Color("rgba(255,255,255,0.9)")); fontWeight(500) } }) { Text(label) }
+ }
+ }
+ }
+ Div(attrs = { style { textAlign("center"); marginTop(20.px) } }) {
+ A(href = "mailto:${AppConfig.enterpriseContactEmail}?subject=Flagent%20early%20access", attrs = {
+ style {
+ color(FlagentTheme.PrimaryLight)
+ textDecoration("none")
+ fontSize(13.px)
+ fontWeight(600)
+ }
+ }) { Text("Request early access →") }
+ }
+ }
+}
+
+@Composable
+private fun TrustSection() {
+ val items = listOf(
+ "Self-hosted" to "Your infrastructure, your data. No vendor lock-in.",
+ "Open source" to "Apache 2.0. Transparent, auditable, extensible.",
+ "Data stays yours" to "Run on-premise or in your cloud. We never see your flag data.",
+ )
+ Div(attrs = {
+ style {
+ marginBottom(64.px)
+ padding(32.px, 24.px)
+ property("background", "rgba(255,255,255,0.03)")
+ property("border", "1px solid rgba(255,255,255,0.08)")
+ borderRadius(16.px)
+ }
+ }) {
+ P(attrs = {
+ style {
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.5)"))
+ textAlign("center")
+ marginBottom(20.px)
+ property("text-transform", "uppercase")
+ property("letter-spacing", "0.06em")
+ }
+ }) { Text("Trust & control") }
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ flexWrap(FlexWrap.Wrap)
+ gap(24.px)
+ justifyContent(JustifyContent.Center)
+ }
+ }) {
+ items.forEach { (title, subtitle) ->
+ Div(attrs = {
+ style {
+ maxWidth(260.px)
+ padding(16.px, 20.px)
+ property("background", "rgba(0,0,0,0.2)")
+ borderRadius(12.px)
+ property("border", "1px solid rgba(255,255,255,0.06)")
+ }
+ }) {
+ Span(attrs = {
+ style {
+ fontSize(14.px)
+ fontWeight(600)
+ color(Color.white)
+ }
+ }) { Text(title) }
+ P(attrs = {
+ style {
+ margin(8.px, 0.px, 0.px, 0.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.65)"))
+ lineHeight("1.5")
+ }
+ }) { Text(subtitle) }
+ }
}
}
}
@@ -388,7 +1079,6 @@ private fun FeaturesSection() {
@Composable
private fun MarketingFeatureCard(
- index: Int,
icon: String,
title: String,
description: String,
@@ -396,20 +1086,19 @@ private fun MarketingFeatureCard(
) {
Div(attrs = {
style {
- padding(28.px)
+ padding(18.px)
property("background", "rgba(255, 255, 255, 0.04)")
property("border", "1px solid rgba(255, 255, 255, 0.08)")
property("backdrop-filter", "blur(12px)")
- borderRadius(16.px)
+ borderRadius(14.px)
property("box-shadow", "0 4px 24px rgba(0,0,0,0.15)")
property("transition", "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)")
cursor("pointer")
- position(Position.Relative)
}
onClick { onClick() }
onMouseEnter {
val el = it.target as org.w3c.dom.HTMLElement
- el.style.transform = "translateY(-6px) scale(1.02)"
+ el.style.transform = "translateY(-4px) scale(1.02)"
el.style.setProperty("box-shadow", "0 12px 40px rgba(0,0,0,0.25)")
el.style.setProperty("border-color", "rgba(14, 165, 233, 0.3)")
}
@@ -420,41 +1109,24 @@ private fun MarketingFeatureCard(
el.style.setProperty("border-color", "rgba(255, 255, 255, 0.08)")
}
}) {
- Span(attrs = {
- style {
- position(Position.Absolute)
- property("top", "16px")
- property("right", "16px")
- width(24.px)
- height(24.px)
- borderRadius(50.percent)
- property("background", "rgba(14, 165, 233, 0.2)")
- color(FlagentTheme.PrimaryLight)
- fontSize(12.px)
- fontWeight(600)
- display(DisplayStyle.Flex)
- alignItems(AlignItems.Center)
- justifyContent(JustifyContent.Center)
- }
- }) { Text(index.toString()) }
Div(attrs = {
style {
- width(52.px)
- height(52.px)
- borderRadius(14.px)
+ width(44.px)
+ height(44.px)
+ borderRadius(12.px)
property("background", "linear-gradient(135deg, rgba(14, 165, 233, 0.25) 0%, rgba(20, 184, 166, 0.2) 100%)")
display(DisplayStyle.Flex)
alignItems(AlignItems.Center)
justifyContent(JustifyContent.Center)
- marginBottom(18.px)
+ marginBottom(14.px)
}
}) {
- Icon(icon, size = 28.px, color = FlagentTheme.PrimaryLight)
+ Icon(icon, size = 24.px, color = FlagentTheme.PrimaryLight)
}
H3(attrs = {
style {
- margin(0.px, 0.px, 10.px, 0.px)
- fontSize(18.px)
+ margin(0.px, 0.px, 6.px, 0.px)
+ fontSize(16.px)
fontWeight(600)
color(Color.white)
}
@@ -462,9 +1134,9 @@ private fun MarketingFeatureCard(
P(attrs = {
style {
margin(0.px)
- fontSize(14.px)
+ fontSize(13.px)
color(Color("rgba(255,255,255,0.65)"))
- lineHeight("1.55")
+ lineHeight("1.5")
}
}) { Text(description) }
}
@@ -487,9 +1159,19 @@ private fun UseCasesSection() {
fontWeight(600)
color(Color.white)
textAlign("center")
- marginBottom(32.px)
+ marginBottom(12.px)
}
}) { Text("Use Cases") }
+ P(attrs = {
+ style {
+ fontSize(15.px)
+ color(Color("rgba(255,255,255,0.6)"))
+ textAlign("center")
+ maxWidth(520.px)
+ property("margin", "0 auto 32px")
+ lineHeight("1.5")
+ }
+ }) { Text("Ship features safely, experiment with confidence, roll back in one click.") }
Div(attrs = {
style {
display(DisplayStyle.Grid)
@@ -498,37 +1180,68 @@ private fun UseCasesSection() {
}
}) {
UseCaseCard(
+ icon = "rocket_launch",
"Safe Deployments",
- "Deploy code to production behind feature flags, enabling instant rollbacks without code changes."
+ "Deploy to production behind feature flags. Roll back instantly without code changes or redeploys."
)
UseCaseCard(
+ icon = "science",
"A/B Testing",
- "Run experiments to test new features and measure their impact on key metrics."
+ "Run multi-variant experiments with deterministic bucketing. Measure impact and ship winners."
)
UseCaseCard(
+ icon = "trending_up",
"Gradual Rollouts",
- "Roll out features gradually and instantly disable if issues are detected."
+ "Ramp from 1% to 100% at your pace. Kill switch any feature the moment issues appear."
+ )
+ UseCaseCard(
+ icon = "segment",
+ "Targeting & Segments",
+ "Target by user attributes, regions, or rules. Multi-environment configs for dev, staging, prod."
)
}
}
}
@Composable
-private fun UseCaseCard(title: String, description: String) {
+private fun UseCaseCard(icon: String, title: String, description: String) {
Div(attrs = {
style {
padding(20.px)
property("background", "rgba(0,0,0,0.2)")
borderRadius(12.px)
property("border", "1px solid rgba(255,255,255,0.06)")
+ property("transition", "all 0.2s ease")
+ }
+ onMouseEnter {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.setProperty("border-color", "rgba(14, 165, 233, 0.25)")
+ }
+ onMouseLeave {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.setProperty("border-color", "rgba(255,255,255,0.06)")
}
}) {
+ Div(attrs = {
+ style {
+ width(40.px)
+ height(40.px)
+ borderRadius(10.px)
+ property("background", "rgba(14, 165, 233, 0.15)")
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ marginBottom(12.px)
+ }
+ }) {
+ Icon(icon, size = 22.px, color = FlagentTheme.PrimaryLight)
+ }
H3(attrs = {
style {
margin(0.px, 0.px, 8.px, 0.px)
fontSize(16.px)
fontWeight(600)
- color(FlagentTheme.PrimaryLight)
+ color(Color.white)
}
}) { Text(title) }
P(attrs = {
@@ -541,3 +1254,187 @@ private fun UseCaseCard(title: String, description: String) {
}) { Text(description) }
}
}
+
+private data class EnterpriseFeature(val icon: String, val label: String)
+
+@Composable
+private fun EnterpriseSection() {
+ val securityFeatures = listOf(
+ EnterpriseFeature("lock", "SSO (SAML, OIDC)"),
+ EnterpriseFeature("group", "RBAC & custom roles"),
+ EnterpriseFeature("description", "Audit logs"),
+ EnterpriseFeature("dns", "On-premise"),
+ )
+ val productFeatures = listOf(
+ EnterpriseFeature("trending_up", "Smart Rollout"),
+ EnterpriseFeature("warning", "Anomaly detection"),
+ EnterpriseFeature("bug_report", "Crash-by-flag analytics"),
+ EnterpriseFeature("notifications", "Slack alerts"),
+ EnterpriseFeature("credit_card", "Billing & subscriptions"),
+ EnterpriseFeature("support_agent", "Dedicated support"),
+ )
+ Div(attrs = {
+ style {
+ padding(48.px, 40.px)
+ property("background", "linear-gradient(160deg, rgba(15, 23, 42, 0.6) 0%, rgba(14, 165, 233, 0.06) 50%, rgba(20, 184, 166, 0.04) 100%)")
+ property("border", "1px solid rgba(14, 165, 233, 0.25)")
+ borderRadius(24.px)
+ property("backdrop-filter", "blur(12px)")
+ property("box-shadow", "0 24px 48px rgba(0,0,0,0.2), inset 0 1px 0 rgba(255,255,255,0.06)")
+ marginBottom(64.px)
+ }
+ }) {
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ gap(10.px)
+ marginBottom(12.px)
+ }
+ }) {
+ Icon("business_center", size = 28.px, color = FlagentTheme.PrimaryLight)
+ H2(attrs = {
+ style {
+ fontSize(26.px)
+ fontWeight(700)
+ color(Color.white)
+ textAlign("center")
+ margin(0.px)
+ property("letter-spacing", "-0.02em")
+ }
+ }) { Text("Flagent Enterprise") }
+ }
+ P(attrs = {
+ style {
+ fontSize(16.px)
+ color(Color("rgba(255,255,255,0.75)"))
+ textAlign("center")
+ maxWidth(560.px)
+ property("margin", "0 auto 36px")
+ lineHeight("1.65")
+ }
+ }) {
+ Text("For teams that need compliance, scale, and control: identity, roles, audit trail, safe rollouts, anomaly detection, and crash-by-flag insights — with on-premise and dedicated support.")
+ }
+ Div(attrs = {
+ style {
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fit, minmax(260px, 1fr))")
+ gap(24.px)
+ maxWidth(720.px)
+ property("margin", "0 auto 32px")
+ }
+ }) {
+ Div(attrs = {
+ style {
+ padding(20.px)
+ property("background", "rgba(0,0,0,0.2)")
+ borderRadius(14.px)
+ property("border", "1px solid rgba(255,255,255,0.06)")
+ }
+ }) {
+ Span(attrs = {
+ style {
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.PrimaryLight)
+ property("letter-spacing", "0.04em")
+ }
+ }) { Text("Security & compliance") }
+ Div(attrs = { style { marginTop(12.px); display(DisplayStyle.Flex); flexWrap(FlexWrap.Wrap); gap(8.px) } }) {
+ securityFeatures.forEach { f ->
+ Span(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ padding(6.px, 12.px)
+ property("background", "rgba(14, 165, 233, 0.12)")
+ borderRadius(8.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.9)"))
+ fontWeight(500)
+ }
+ }) {
+ Icon(f.icon, size = 14.px, color = FlagentTheme.PrimaryLight)
+ Text(f.label)
+ }
+ }
+ }
+ }
+ Div(attrs = {
+ style {
+ padding(20.px)
+ property("background", "rgba(0,0,0,0.2)")
+ borderRadius(14.px)
+ property("border", "1px solid rgba(255,255,255,0.06)")
+ }
+ }) {
+ Span(attrs = {
+ style {
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.PrimaryLight)
+ property("letter-spacing", "0.04em")
+ }
+ }) { Text("Product & operations") }
+ Div(attrs = { style { marginTop(12.px); display(DisplayStyle.Flex); flexWrap(FlexWrap.Wrap); gap(8.px) } }) {
+ productFeatures.forEach { f ->
+ Span(attrs = {
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ padding(6.px, 12.px)
+ property("background", "rgba(14, 165, 233, 0.12)")
+ borderRadius(8.px)
+ fontSize(13.px)
+ color(Color("rgba(255,255,255,0.9)"))
+ fontWeight(500)
+ }
+ }) {
+ Icon(f.icon, size = 14.px, color = FlagentTheme.PrimaryLight)
+ Text(f.label)
+ }
+ }
+ }
+ }
+ }
+ Div(attrs = { style { textAlign("center") } }) {
+ A(href = "mailto:${AppConfig.enterpriseContactEmail}?subject=Flagent%20Enterprise", attrs = {
+ style {
+ property("display", "inline-flex")
+ alignItems(AlignItems.Center)
+ justifyContent(JustifyContent.Center)
+ gap(10.px)
+ padding(18.px, 36.px)
+ property(
+ "background",
+ "linear-gradient(135deg, ${FlagentTheme.Primary} 0%, ${FlagentTheme.PrimaryDark} 100%)"
+ )
+ color(Color.white)
+ textDecoration("none")
+ borderRadius(14.px)
+ fontSize(16.px)
+ fontWeight(600)
+ property("box-shadow", "0 8px 28px rgba(14, 165, 233, 0.5)")
+ property("transition", "all 0.25s cubic-bezier(0.4, 0, 0.2, 1)")
+ }
+ onMouseEnter {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.transform = "translateY(-3px) scale(1.02)"
+ el.style.setProperty("box-shadow", "0 14px 36px rgba(14, 165, 233, 0.6)")
+ }
+ onMouseLeave {
+ val el = it.target as org.w3c.dom.HTMLElement
+ el.style.transform = "translateY(0) scale(1)"
+ el.style.setProperty("box-shadow", "0 8px 28px rgba(14, 165, 233, 0.5)")
+ }
+ }) {
+ Icon("mail", size = 22.px, color = Color.white)
+ Text("Request demo")
+ }
+ }
+ }
+}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/PricingPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/PricingPage.kt
index c2f30511..aae629bd 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/PricingPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/landing/PricingPage.kt
@@ -9,6 +9,13 @@ import flagent.frontend.theme.FlagentTheme
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
+/**
+ * Feature status (for maintainers):
+ * - ✅ 100% in OSS: implemented in backend/frontend/sdk, tests, used in production path.
+ * - 🔶 In OSS but partial: e.g. audit = registry only in core, full log in enterprise.
+ * - Enterprise-only: Anomaly, Smart Rollout, SSO, crash-by-flag, custom RBAC — in internal/flagent-enterprise.
+ * - SaaS/Pro/Enterprise "Yes" = planned; only self-hosted OSS is available today.
+ */
/** Plan availability: yes, no, or limit text */
private data class PlanAvailability(
val openSource: String,
@@ -23,7 +30,7 @@ private data class FeatureRow(
)
private val FEATURE_COMPARISON = listOf(
- // Flags and experiments
+ // Flags and experiments — ✅ all in OSS
listOf(
FeatureRow("Feature flags", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("A/B testing & experiments", PlanAvailability("Yes", "Yes", "Yes")),
@@ -34,38 +41,38 @@ private val FEATURE_COMPARISON = listOf(
FeatureRow("Ktor plugin & REST API", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Admin UI & Debug Console", PlanAvailability("Yes", "Yes", "Yes")),
),
- // Analytics
+ // Analytics — ✅ events + eval counts in OSS; advanced = enterprise
listOf(
FeatureRow("Analytics events (first_open, session_start, custom)", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Evaluation counts & core metrics", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Advanced analytics & insights (per-flag/variant)", PlanAvailability("No", "Yes", "Yes")),
FeatureRow("Data recorders (Kafka, Kinesis, PubSub)", PlanAvailability("Yes", "Yes", "Yes")),
),
- // Crash analytics
+ // Crash — ✅ ingestion + list in OSS; crash rate by flag + anomaly = enterprise
listOf(
FeatureRow("Crash reporting (ingestion, list, stack traces)", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Crash rate by flag & anomaly integration", PlanAvailability("No", "No", "Yes")),
),
- // Automation and reliability
+ // Automation — enterprise only (internal/flagent-enterprise)
listOf(
FeatureRow("Anomaly detection & alerts", PlanAvailability("No", "No", "Yes")),
FeatureRow("Smart rollout (auto-rollback)", PlanAvailability("No", "No", "Yes")),
),
- // Integrations and hosting
+ // Integrations — ✅ Export/Import, Webhooks, SSE, MCP in OSS
listOf(
FeatureRow("Export / Import, Webhooks, Realtime (SSE), MCP", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Self-hosted deployment", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Managed cloud hosting", PlanAvailability("No", "Yes", "Yes")),
FeatureRow("On-premise, multi-tenancy", PlanAvailability("No", "No", "Yes")),
),
- // Security and control
+ // Security — JWT ✅; RBAC/SSO/Audit: basic in OSS, full in enterprise
listOf(
FeatureRow("Basic auth (JWT)", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("RBAC", PlanAvailability("Basic", "Basic", "Custom roles")),
FeatureRow("SSO (SAML, OIDC)", PlanAvailability("No", "No", "Yes")),
FeatureRow("Audit log", PlanAvailability("Basic", "Basic", "Advanced")),
),
- // Support
+ // Support — community only in OSS
listOf(
FeatureRow("Community support", PlanAvailability("Yes", "Yes", "Yes")),
FeatureRow("Priority support", PlanAvailability("No", "Yes", "Yes")),
@@ -97,15 +104,20 @@ fun PricingPage() {
minHeight(100.vh)
overflow("hidden")
paddingTop(80.px)
- property(
- "background",
- FlagentTheme.GradientHero
- )
- property("background-size", "400% 400%")
- property("animation", "morphGradient 20s ease infinite")
property("font-family", "'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif")
}
}) {
+ Div(attrs = {
+ style {
+ position(Position.Fixed)
+ property("inset", "0")
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property("background", FlagentTheme.GradientHero)
+ property("background-size", "400% 400%")
+ property("animation", "morphGradient 20s ease infinite")
+ }
+ }) {}
LandingBackgroundShapes()
Div(attrs = {
style {
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/metrics/CrashDashboard.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/metrics/CrashDashboard.kt
index 02be5f38..d8d8c327 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/metrics/CrashDashboard.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/metrics/CrashDashboard.kt
@@ -53,6 +53,17 @@ fun CrashDashboard() {
var reportsRefreshTrigger by remember { mutableStateOf(0) }
var timeRange by remember { mutableStateOf("24h") }
var groupByType by remember { mutableStateOf(false) }
+ var pendingDisableFlagId by remember { mutableStateOf(null) }
+
+ LaunchedEffect(pendingDisableFlagId) {
+ val id = pendingDisableFlagId ?: return@LaunchedEffect
+ try {
+ ApiClient.setFlagEnabled(id, false)
+ flags = ApiClient.getFlags().first
+ reportsRefreshTrigger++
+ } catch (_: Throwable) { }
+ pendingDisableFlagId = null
+ }
val endTime = remember(timeRange) { (kotlin.js.Date().getTime() as Number).toLong() }
val startTime = remember(timeRange) {
@@ -222,7 +233,7 @@ fun CrashDashboard() {
Input(InputType.Checkbox) {
id("crash-group-by")
checked(groupByType)
- onInput { groupByType = (it.target as? org.w3c.dom.HTMLInputElement)?.checked ?: false }
+ onInput { groupByType = it.target.checked }
}
Label(attrs = {
attr("for", "crash-group-by")
@@ -402,7 +413,7 @@ fun CrashDashboard() {
if (selectedCrash?.id == crash.id) {
CrashStackSection(themeMode, crash.stackTrace)
crash.activeFlagKeys?.takeIf { it.isNotEmpty() }?.let { keys ->
- CrashActiveFlagsSection(themeMode, keys, flags)
+ CrashActiveFlagsSection(themeMode, keys, flags) { pendingDisableFlagId = it }
}
}
}
@@ -464,7 +475,7 @@ fun CrashDashboard() {
if (selectedCrash?.id == crash.id) {
CrashStackSection(themeMode, crash.stackTrace)
crash.activeFlagKeys?.takeIf { it.isNotEmpty() }?.let { keys ->
- CrashActiveFlagsSection(themeMode, keys, flags)
+ CrashActiveFlagsSection(themeMode, keys, flags) { pendingDisableFlagId = it }
}
}
}
@@ -549,7 +560,12 @@ fun CrashDashboard() {
}
@Composable
-private fun CrashActiveFlagsSection(themeMode: ThemeMode, activeFlagKeys: List, flags: List) {
+private fun CrashActiveFlagsSection(
+ themeMode: ThemeMode,
+ activeFlagKeys: List,
+ flags: List,
+ onDisableFlag: (Int) -> Unit
+) {
Div({
style {
marginTop(12.px)
@@ -564,33 +580,63 @@ private fun CrashActiveFlagsSection(themeMode: ThemeMode, activeFlagKeys: List
val flag = flags.find { it.key == key }
if (flag != null) {
- A(href = Route.FlagDetail(flag.id).path(), attrs = {
+ Div({
style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
padding(6.px, 10.px)
- backgroundColor(FlagentTheme.Primary)
- color(Color.white)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
borderRadius(6.px)
- fontSize(12.px)
- textDecoration("none")
- }
- onClick { e ->
- e.preventDefault()
- Router.navigateTo(Route.FlagDetail(flag.id))
+ border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
}
}) {
- Text(flag.key)
+ A(href = Route.FlagDetail(flag.id).path(), attrs = {
+ style {
+ padding(2.px, 0.px)
+ color(FlagentTheme.Primary)
+ fontSize(12.px)
+ fontWeight(600)
+ textDecoration("none")
+ }
+ onClick { e ->
+ e.preventDefault()
+ Router.navigateTo(Route.FlagDetail(flag.id))
+ }
+ }) {
+ Text(flag.key)
+ }
+ Button({
+ onClick { e ->
+ e.stopPropagation()
+ onDisableFlag(flag.id)
+ }
+ style {
+ padding(4.px, 8.px)
+ fontSize(11.px)
+ backgroundColor(FlagentTheme.Error)
+ color(Color.white)
+ border(0.px)
+ borderRadius(4.px)
+ cursor("pointer")
+ fontWeight(600)
+ }
+ }) {
+ Text(LocalizedStrings.disableFlag)
+ }
}
} else {
Span({
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/segments/SegmentsPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/segments/SegmentsPage.kt
index fdefe24e..ef0e139c 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/segments/SegmentsPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/segments/SegmentsPage.kt
@@ -5,6 +5,7 @@ import flagent.api.model.FlagResponse
import flagent.api.model.SegmentResponse
import flagent.frontend.api.ApiClient
import flagent.frontend.components.Icon
+import flagent.frontend.components.common.FilterChip
import flagent.frontend.components.common.PageHeader
import flagent.frontend.i18n.LocalizedStrings
import flagent.frontend.navigation.Route
@@ -15,6 +16,7 @@ import flagent.frontend.util.ErrorHandler
import org.jetbrains.compose.web.attributes.InputType
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
+import org.w3c.dom.HTMLSelectElement
/**
* Data class for a segment with its parent flag info (for list display).
@@ -35,6 +37,10 @@ fun SegmentsPage() {
var isLoading by remember { mutableStateOf(true) }
var error by remember { mutableStateOf(null) }
var searchQuery by remember { mutableStateOf("") }
+ var selectedFlagId by remember { mutableStateOf(null) }
+ var groupByFlag by remember { mutableStateOf(false) }
+ var sortColumn by remember { mutableStateOf(null) }
+ var sortAscending by remember { mutableStateOf(true) }
LaunchedEffect(Unit) {
isLoading = true
@@ -51,17 +57,48 @@ fun SegmentsPage() {
isLoading = false
}
- val segmentsWithFlags: List = remember(flags, searchQuery) {
- val list = flags.flatMap { flag ->
+ val segmentsWithFlags: List = remember(flags, searchQuery, selectedFlagId) {
+ var list = flags.flatMap { flag ->
flag.segments.map { seg -> SegmentWithFlag(seg, flag) }
}
+ selectedFlagId?.let { id -> list = list.filter { it.flag.id == id } }
val q = searchQuery.trim().lowercase()
- if (q.isEmpty()) list
- else list.filter {
- it.segment.description?.lowercase()?.contains(q) == true ||
- it.flag.key.lowercase().contains(q) ||
- it.segment.id.toString().contains(q)
+ if (q.isNotEmpty()) {
+ list = list.filter {
+ it.segment.description?.lowercase()?.contains(q) == true ||
+ it.flag.key.lowercase().contains(q) ||
+ it.segment.id.toString().contains(q)
+ }
+ }
+ list
+ }
+
+ val sortedSegments = remember(segmentsWithFlags, sortColumn, sortAscending) {
+ var result = segmentsWithFlags
+ sortColumn?.let { col ->
+ result = when (col) {
+ "flagKey" -> result.sortedBy { it.flag.key }
+ "id" -> result.sortedBy { it.segment.id }
+ "description" -> result.sortedBy { it.segment.description ?: "" }
+ "rolloutPercent" -> result.sortedBy { it.segment.rolloutPercent }
+ "constraints" -> result.sortedBy { it.segment.constraints.size }
+ else -> result
+ }
+ if (!sortAscending) result = result.reversed()
}
+ result
+ }
+
+ val groupedByFlag = remember(sortedSegments, groupByFlag) {
+ if (!groupByFlag) null
+ else sortedSegments.groupBy { it.flag.id }.toList().associate { (flagId, list) ->
+ list.first().flag.key.ifBlank { "Flag #$flagId" } to list
+ }
+ }
+
+ fun sortBy(column: String) {
+ if (sortColumn == column) sortAscending = !sortAscending
+ else { sortColumn = column; sortAscending = true }
}
Div({
@@ -156,13 +193,13 @@ fun SegmentsPage() {
}
}) {
Text(
- if (searchQuery.isNotBlank())
+ if (searchQuery.isNotBlank() || selectedFlagId != null)
LocalizedStrings.noSegmentsMatchSearch
else
LocalizedStrings.noSegmentsInProject
)
}
- if (searchQuery.isNotBlank()) {
+ if (searchQuery.isNotBlank() || selectedFlagId != null) {
Button({
style {
marginTop(12.px)
@@ -174,7 +211,7 @@ fun SegmentsPage() {
cursor("pointer")
fontSize(14.px)
}
- onClick { searchQuery = "" }
+ onClick { searchQuery = ""; selectedFlagId = null }
}) {
Text(LocalizedStrings.clearSearch)
}
@@ -217,10 +254,7 @@ fun SegmentsPage() {
}) {
Span({
classes("material-icons")
- style {
- fontSize(20.px)
- color(FlagentTheme.textLight(themeMode))
- }
+ style { fontSize(20.px); color(FlagentTheme.textLight(themeMode)) }
}) { Text("search") }
Input(InputType.Text) {
value(searchQuery)
@@ -237,45 +271,282 @@ fun SegmentsPage() {
}
}
}
- Span({
+ Select({
+ attr("value", selectedFlagId?.toString() ?: "")
+ onChange { event ->
+ val v = event.target.value
+ selectedFlagId = v.toIntOrNull()
+ }
style {
- color(FlagentTheme.textLight(themeMode))
+ padding(8.px, 12.px)
+ borderRadius(6.px)
+ border(1.px, LineStyle.Solid, FlagentTheme.inputBorder(themeMode))
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
fontSize(14.px)
+ minWidth(160.px)
}
}) {
- Text("${segmentsWithFlags.size} ${LocalizedStrings.segments.lowercase()}")
+ Option(value = "") { Text(LocalizedStrings.allFlags) }
+ flags.forEach { f ->
+ Option(value = f.id.toString()) {
+ Text(f.key.ifBlank { "Flag #${f.id}" })
+ }
+ }
+ }
+ FilterChip(themeMode, LocalizedStrings.groupByFlag, groupByFlag, onClick = { groupByFlag = !groupByFlag })
+ Span({
+ style { color(FlagentTheme.textLight(themeMode)); fontSize(14.px) }
+ }) {
+ Text("${sortedSegments.size} ${LocalizedStrings.segments.lowercase()}")
}
}
- Div({
- style {
- backgroundColor(FlagentTheme.cardBg(themeMode))
- borderRadius(8.px)
- overflow("hidden")
- property("box-shadow", "0 1px 3px ${FlagentTheme.Shadow}")
- }
- }) {
- Table({
- style {
- width(100.percent)
- property("border-collapse", "collapse")
- }
- }) {
- Thead {
- Tr({
+ if (groupedByFlag != null) {
+ groupedByFlag.entries.forEach { (flagKeyLabel, list) ->
+ Div({
+ style { marginBottom(24.px) }
+ }) {
+ Div({
style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(8.px)
+ marginBottom(12.px)
+ padding(12.px, 16.px)
backgroundColor(FlagentTheme.inputBg(themeMode))
- property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ borderRadius(8.px)
+ property("border-left", "4px solid ${FlagentTheme.Primary}")
}
}) {
- listOf(
- LocalizedStrings.flagKey,
- "ID",
- LocalizedStrings.description,
- LocalizedStrings.rolloutPercent,
- LocalizedStrings.constraints,
- LocalizedStrings.action
- ).forEach { h ->
+ Icon("flag", size = 18.px, color = FlagentTheme.Primary)
+ Text(flagKeyLabel)
+ Span({ style { color(FlagentTheme.textLight(themeMode)); fontSize(13.px) } }) {
+ Text(" (${list.size})")
+ }
+ }
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ overflow("hidden")
+ property("box-shadow", "0 1px 3px ${FlagentTheme.Shadow}")
+ }
+ }) {
+ Table({
+ style { width(100.percent); property("border-collapse", "collapse") }
+ }) {
+ Thead {
+ Tr({
+ style {
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ }
+ }) {
+ listOf(
+ LocalizedStrings.flagKey,
+ "ID",
+ LocalizedStrings.description,
+ LocalizedStrings.rolloutPercent,
+ LocalizedStrings.constraints,
+ LocalizedStrings.action
+ ).forEach { h ->
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ }
+ }) { Text(h) }
+ }
+ }
+ }
+ Tbody {
+ list.forEach { (segment, flag) ->
+ Tr({
+ style {
+ property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ property("transition", "background-color 0.15s")
+ }
+ onMouseEnter { (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = FlagentTheme.inputBg(themeMode).toString() }
+ onMouseLeave { (it.target as org.w3c.dom.HTMLElement).style.backgroundColor = "transparent" }
+ }) {
+ Td({
+ style { padding(10.px, 12.px); fontSize(14.px); color(FlagentTheme.Primary); cursor("pointer") }
+ onClick { Router.navigateTo(Route.FlagDetail(flag.id)) }
+ }) { Text(flag.key.ifBlank { "Flag #${flag.id}" }) }
+ Td({ style { padding(10.px, 12.px); fontSize(14.px); color(FlagentTheme.textLight(themeMode)) } }) {
+ Text(segment.id.toString())
+ }
+ Td({
+ style {
+ padding(10.px, 12.px)
+ fontSize(14.px)
+ property("max-width", "240px")
+ property("overflow", "hidden")
+ property("text-overflow", "ellipsis")
+ property("white-space", "nowrap")
+ }
+ }) {
+ Text(segment.description?.ifBlank { "—" } ?: "—")
+ }
+ Td({ style { padding(10.px, 12.px); fontSize(14.px) } }) {
+ Text("${segment.rolloutPercent}%")
+ }
+ Td({ style { padding(10.px, 12.px); fontSize(14.px) } }) {
+ Text(segment.constraints.size.toString())
+ }
+ Td({ style { padding(10.px, 12.px) } }) {
+ Button({
+ style {
+ padding(6.px, 10.px)
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ color(FlagentTheme.text(themeMode))
+ border(1.px, LineStyle.Solid, FlagentTheme.cardBorder(themeMode))
+ borderRadius(6.px)
+ cursor("pointer")
+ fontSize(12.px)
+ }
+ onClick { Router.navigateTo(Route.FlagDetail(flag.id)) }
+ }) {
+ Icon("settings", size = 14.px)
+ Text(" ${LocalizedStrings.edit}")
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ } else {
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ overflow("hidden")
+ property("box-shadow", "0 1px 3px ${FlagentTheme.Shadow}")
+ }
+ }) {
+ Table({
+ style { width(100.percent); property("border-collapse", "collapse") }
+ }) {
+ Thead {
+ Tr({
+ style {
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ }
+ }) {
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("flagKey") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.flagKey)
+ if (sortColumn == "flagKey") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("id") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text("ID")
+ if (sortColumn == "id") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("description") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.description)
+ if (sortColumn == "description") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("rolloutPercent") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.rolloutPercent)
+ if (sortColumn == "rolloutPercent") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ padding(10.px, 12.px)
+ textAlign("left")
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.textLight(themeMode))
+ property("text-transform", "uppercase")
+ cursor("pointer")
+ }
+ onClick { sortBy("constraints") }
+ }) {
+ Span({ style { display(DisplayStyle.Flex); alignItems(AlignItems.Center); gap(4.px) } }) {
+ Text(LocalizedStrings.constraints)
+ if (sortColumn == "constraints") {
+ Span({ style { fontSize(12.px); color(FlagentTheme.Primary) } }) {
+ Text(if (sortAscending) "↑" else "↓")
+ }
+ }
+ }
+ }
Th({
style {
padding(10.px, 12.px)
@@ -285,12 +556,12 @@ fun SegmentsPage() {
color(FlagentTheme.textLight(themeMode))
property("text-transform", "uppercase")
}
- }) { Text(h) }
+ }) { Text(LocalizedStrings.action) }
}
}
}
Tbody {
- segmentsWithFlags.forEach { (segment, flag) ->
+ sortedSegments.forEach { (segment, flag) ->
Tr({
style {
property("border-bottom", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/AdminUsersSettings.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/AdminUsersSettings.kt
index 4d0b1797..92c75670 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/AdminUsersSettings.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/AdminUsersSettings.kt
@@ -36,15 +36,15 @@ fun AdminUsersSettings(themeMode: ThemeMode) {
scope.launch {
loading.value = true
error.value = null
- try {
- val (list, total) = ApiClient.getAdminUsers(limit = 50, offset = 0)
- users.value = list
- totalCount.value = total
- } catch (e: Exception) {
- error.value = ErrorHandler.getUserMessage(ErrorHandler.handle(e))
- } finally {
- loading.value = false
- }
+ ErrorHandler.withErrorHandling(
+ block = {
+ val (list, total) = ApiClient.getAdminUsers(limit = 50, offset = 0)
+ users.value = list
+ totalCount.value = total
+ },
+ onError = { err -> error.value = ErrorHandler.getUserMessage(err) }
+ )
+ loading.value = false
}
}
@@ -78,6 +78,13 @@ fun AdminUsersSettings(themeMode: ThemeMode) {
fontSize(14.px)
}
}) { Text(LocalizedStrings.adminUsersDescription) }
+ P({
+ style {
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(20.px)
+ fontSize(13.px)
+ }
+ }) { Text(LocalizedStrings.adminUsersExtraHint) }
if (error.value != null) {
Div({
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/FirebaseSettings.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/FirebaseSettings.kt
new file mode 100644
index 00000000..d0732f34
--- /dev/null
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/FirebaseSettings.kt
@@ -0,0 +1,304 @@
+package flagent.frontend.components.settings
+
+import androidx.compose.runtime.*
+import flagent.frontend.api.ApiClient
+import flagent.frontend.api.FirebaseStatusResponse
+import flagent.frontend.config.AppConfig
+import flagent.frontend.i18n.LocalizedStrings
+import flagent.frontend.state.ThemeMode
+import flagent.frontend.theme.FlagentTheme
+import flagent.frontend.util.ErrorHandler
+import flagent.frontend.util.triggerDownloadFromString
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import org.jetbrains.compose.web.css.*
+import org.jetbrains.compose.web.dom.*
+
+@Composable
+fun FirebaseSettings(themeMode: ThemeMode) {
+ val statusState = remember { mutableStateOf(null) }
+ val loadingState = remember { mutableStateOf(true) }
+ val errorState = remember { mutableStateOf(null) }
+ val scope = remember { CoroutineScope(Dispatchers.Main) }
+
+ LaunchedEffect(Unit) {
+ scope.launch {
+ loadingState.value = true
+ errorState.value = null
+ ErrorHandler.withErrorHandling(
+ block = {
+ statusState.value = ApiClient.getFirebaseStatus()
+ },
+ onError = { err -> errorState.value = ErrorHandler.getUserMessage(err) }
+ )
+ loadingState.value = false
+ }
+ }
+
+ Div({
+ style {
+ backgroundColor(FlagentTheme.cardBg(themeMode))
+ borderRadius(8.px)
+ padding(20.px)
+ property("box-shadow", FlagentTheme.ShadowCard)
+ }
+ }) {
+ H2({
+ style {
+ fontSize(20.px)
+ fontWeight("600")
+ marginBottom(8.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) { Text(LocalizedStrings.firebaseSettingsTitle) }
+
+ P({
+ style {
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(20.px)
+ fontSize(14.px)
+ }
+ }) {
+ Text(LocalizedStrings.firebaseSettingsDescription)
+ }
+
+ if (errorState.value != null) {
+ Div({
+ style {
+ padding(12.px)
+ backgroundColor(FlagentTheme.errorBg(themeMode))
+ borderRadius(6.px)
+ color(FlagentTheme.errorText(themeMode))
+ marginBottom(16.px)
+ }
+ }) {
+ Text(errorState.value!!)
+ }
+ } else if (loadingState.value || statusState.value == null) {
+ Div({
+ style {
+ padding(24.px)
+ textAlign("center")
+ color(FlagentTheme.textLight(themeMode))
+ }
+ }) { Text(LocalizedStrings.loading) }
+ } else {
+ val status = statusState.value!!
+
+ Div({
+ style {
+ display(DisplayStyle.Grid)
+ property("grid-template-columns", "repeat(auto-fit, minmax(260px, 1fr))")
+ gap(16.px)
+ marginBottom(24.px)
+ }
+ }) {
+ // Firebase Remote Config
+ Div({
+ style {
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ borderRadius(8.px)
+ padding(16.px)
+ }
+ }) {
+ H3({
+ style {
+ fontSize(16.px)
+ fontWeight("600")
+ marginBottom(8.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) { Text(LocalizedStrings.firebaseRcTitle) }
+ P({
+ style {
+ fontSize(13.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(8.px)
+ }
+ }) {
+ Text(LocalizedStrings.firebaseRcDescription)
+ }
+ StatusRow(themeMode, enabled = status.firebaseRc.enabled)
+ DefinitionRow(
+ themeMode,
+ label = LocalizedStrings.firebaseProjectIdLabel,
+ value = status.firebaseRc.projectId ?: "—"
+ )
+ DefinitionRow(
+ themeMode,
+ label = LocalizedStrings.firebaseRcSyncIntervalLabel,
+ value = "${status.firebaseRc.syncIntervalSeconds}s"
+ )
+ DefinitionRow(
+ themeMode,
+ label = LocalizedStrings.firebaseRcPrefixLabel,
+ value = status.firebaseRc.parameterPrefix.ifBlank { "—" }
+ )
+ DefinitionRow(
+ themeMode,
+ label = LocalizedStrings.firebaseRcCredentialsLabel,
+ value = if (status.firebaseRc.hasCredentials) LocalizedStrings.configPresent else LocalizedStrings.configMissing
+ )
+ }
+
+ // Firebase Analytics
+ Div({
+ style {
+ backgroundColor(FlagentTheme.inputBg(themeMode))
+ borderRadius(8.px)
+ padding(16.px)
+ }
+ }) {
+ H3({
+ style {
+ fontSize(16.px)
+ fontWeight("600")
+ marginBottom(8.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) { Text(LocalizedStrings.firebaseAnalyticsTitle) }
+ P({
+ style {
+ fontSize(13.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(8.px)
+ }
+ }) {
+ Text(LocalizedStrings.firebaseAnalyticsDescription)
+ }
+ StatusRow(themeMode, enabled = status.firebaseAnalytics.enabled)
+ DefinitionRow(
+ themeMode,
+ label = LocalizedStrings.firebaseMeasurementIdLabel,
+ value = status.firebaseAnalytics.measurementId ?: "—"
+ )
+ DefinitionRow(
+ themeMode,
+ label = LocalizedStrings.firebaseApiSecretLabel,
+ value = if (status.firebaseAnalytics.hasApiSecret) LocalizedStrings.configPresent else LocalizedStrings.configMissing
+ )
+ }
+ }
+
+ // Configuration / docs section
+ Div({
+ style {
+ paddingTop(16.px)
+ property("border-top", "1px solid ${FlagentTheme.cardBorder(themeMode)}")
+ marginTop(8.px)
+ }
+ }) {
+ H3({
+ style {
+ fontSize(15.px)
+ fontWeight("600")
+ marginBottom(6.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) { Text(LocalizedStrings.firebaseConfigSectionTitle) }
+ P({
+ style {
+ fontSize(13.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(8.px)
+ }
+ }) {
+ Text(LocalizedStrings.firebaseConfigSectionDescription)
+ }
+
+ Ul({
+ style {
+ fontSize(13.px)
+ color(FlagentTheme.text(themeMode))
+ margin(0.px)
+ paddingLeft(18.px)
+ }
+ }) {
+ listOf(
+ "FLAGENT_FIREBASE_RC_SYNC_ENABLED",
+ "FLAGENT_FIREBASE_RC_PROJECT_ID",
+ "FLAGENT_FIREBASE_RC_CREDENTIALS_JSON",
+ "FLAGENT_FIREBASE_RC_CREDENTIALS_FILE",
+ "FLAGENT_FIREBASE_RC_SYNC_INTERVAL",
+ "FLAGENT_FIREBASE_RC_PARAMETER_PREFIX",
+ "FLAGENT_FIREBASE_ANALYTICS_ENABLED",
+ "FLAGENT_FIREBASE_ANALYTICS_API_SECRET",
+ "FLAGENT_FIREBASE_ANALYTICS_MEASUREMENT_ID",
+ "FLAGENT_FIREBASE_ANALYTICS_APP_INSTANCE_ID_KEY",
+ "FLAGENT_FIREBASE_ANALYTICS_CLIENT_ID_KEY"
+ ).forEach { envName ->
+ Li {
+ Text(envName)
+ }
+ }
+ }
+
+ val docsUrl = "${AppConfig.docsUrl}#/guides/configuration?id=firebase-integration"
+
+ A(href = docsUrl, attrs = {
+ style {
+ display(DisplayStyle.InlineBlock)
+ marginTop(12.px)
+ fontSize(13.px)
+ color(FlagentTheme.Primary)
+ textDecoration("underline")
+ }
+ }) {
+ Text(LocalizedStrings.firebaseDocsLinkText)
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun StatusRow(themeMode: ThemeMode, enabled: Boolean) {
+ Div({
+ style {
+ marginTop(8.px)
+ marginBottom(4.px)
+ }
+ }) {
+ Span({
+ style {
+ display(DisplayStyle.InlineBlock)
+ padding(4.px, 8.px)
+ borderRadius(999.px)
+ fontSize(12.px)
+ backgroundColor(
+ if (enabled) FlagentTheme.successBg(themeMode) else FlagentTheme.inputBg(themeMode)
+ )
+ color(
+ if (enabled) FlagentTheme.Success else FlagentTheme.textLight(themeMode)
+ )
+ }
+ }) {
+ Text(if (enabled) LocalizedStrings.enabled else LocalizedStrings.disabled)
+ }
+ }
+}
+
+@Composable
+private fun DefinitionRow(themeMode: ThemeMode, label: String, value: String) {
+ Div({
+ style {
+ marginTop(4.px)
+ }
+ }) {
+ Span({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginRight(4.px)
+ }
+ }) { Text(label) }
+ Span({
+ style {
+ fontSize(13.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) { Text(value) }
+ }
+}
+
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/RolesSettings.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/RolesSettings.kt
index a4a5d074..2214c49e 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/RolesSettings.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/RolesSettings.kt
@@ -4,6 +4,7 @@ import androidx.compose.runtime.*
import flagent.frontend.api.ApiClient
import flagent.frontend.api.RoleResponse
import flagent.frontend.api.TenantUserResponse
+import flagent.frontend.i18n.LocalizedStrings
import flagent.frontend.state.ThemeMode
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.util.ErrorHandler
@@ -50,19 +51,29 @@ fun RolesSettings(themeMode: flagent.frontend.state.ThemeMode) {
style {
fontSize(20.px)
fontWeight("600")
- marginBottom(20.px)
+ marginBottom(12.px)
color(FlagentTheme.text(themeMode))
}
}) {
- Text("Roles & Permissions")
+ Text(LocalizedStrings.rolesAndPermissions)
+ }
+ P({
+ style {
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(8.px)
+ fontSize(14.px)
+ }
+ }) {
+ Text(LocalizedStrings.manageRolesDescription)
}
P({
style {
color(FlagentTheme.textLight(themeMode))
marginBottom(20.px)
+ fontSize(13.px)
}
}) {
- Text("Manage roles and assign permissions to users.")
+ Text(LocalizedStrings.rolesTenantUsersHint)
}
if (error.value != null) {
Div({
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/SettingsPage.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/SettingsPage.kt
index 932f8b5c..62e0ed5c 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/SettingsPage.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/settings/SettingsPage.kt
@@ -11,6 +11,7 @@ import flagent.frontend.config.Edition
import flagent.frontend.i18n.LocalizedStrings
import flagent.frontend.navigation.Route
import flagent.frontend.navigation.Router
+import flagent.frontend.state.LanguageState
import flagent.frontend.state.LocalThemeMode
import flagent.frontend.theme.FlagentTheme
import flagent.frontend.util.ErrorHandler
@@ -79,6 +80,9 @@ fun SettingsPage() {
}
}
SettingsTab(themeMode, LocalizedStrings.generalTab, "settings", activeTab == "general") { activeTab = "general" }
+ if (AppConfig.Features.enableFirebaseSettings) {
+ SettingsTab(themeMode, LocalizedStrings.firebaseTab, "cloud", activeTab == "firebase") { activeTab = "firebase" }
+ }
if (AppConfig.Features.enableSso) {
SettingsTab(themeMode, LocalizedStrings.ssoProvidersTab, "security", activeTab == "sso") { activeTab = "sso" }
}
@@ -106,6 +110,7 @@ fun SettingsPage() {
}) {
when (activeTab) {
"general" -> GeneralSettings(themeMode)
+ "firebase" -> if (AppConfig.Features.enableFirebaseSettings) FirebaseSettings(themeMode)
"sso" -> if (AppConfig.Features.enableSso) SsoSettings(themeMode)
"slack" -> if (AppConfig.Features.enableSlack) SlackSettings(themeMode)
"billing" -> if (AppConfig.Features.enableBilling) BillingSettings(themeMode)
@@ -167,23 +172,73 @@ private fun GeneralSettings(themeMode: flagent.frontend.state.ThemeMode) {
Text(LocalizedStrings.generalSettings)
}
- SettingItem(themeMode,
+ SettingItem(
+ themeMode,
title = LocalizedStrings.apiBaseUrl,
description = LocalizedStrings.apiBaseUrlDesc,
value = AppConfig.apiBaseUrl
)
-
- SettingItem(themeMode,
+
+ SettingItem(
+ themeMode,
title = LocalizedStrings.debugMode,
description = LocalizedStrings.debugModeDesc,
value = if (AppConfig.debugMode) LocalizedStrings.enabled else LocalizedStrings.disabled
)
-
- SettingItem(themeMode,
+
+ SettingItem(
+ themeMode,
title = LocalizedStrings.apiTimeout,
description = LocalizedStrings.apiTimeoutDesc,
value = "${AppConfig.apiTimeout}ms"
)
+
+ val currentLocale by LanguageState.current
+ Div({
+ style {
+ marginBottom(20.px)
+ paddingBottom(20.px)
+ property("border-bottom", "1px solid ${FlagentTheme.inputBorder(themeMode)}")
+ }
+ }) {
+ Div({
+ style {
+ fontWeight("500")
+ marginBottom(4.px)
+ color(FlagentTheme.text(themeMode))
+ }
+ }) {
+ Text(LocalizedStrings.languageLabel)
+ }
+ Div({
+ style {
+ fontSize(14.px)
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(8.px)
+ }
+ }) {
+ Text(LocalizedStrings.languageDescription)
+ }
+ Div({
+ style {
+ display(DisplayStyle.Flex)
+ gap(8.px)
+ }
+ }) {
+ LanguageOptionButton(
+ themeMode = themeMode,
+ label = LocalizedStrings.languageRu,
+ isActive = currentLocale == "ru",
+ onClick = { LanguageState.set("ru") }
+ )
+ LanguageOptionButton(
+ themeMode = themeMode,
+ label = LocalizedStrings.languageEn,
+ isActive = currentLocale == "en",
+ onClick = { LanguageState.set("en") }
+ )
+ }
+ }
if (AppConfig.Features.enableMultiTenancy) {
Div({
@@ -289,7 +344,7 @@ private fun GeneralSettings(themeMode: flagent.frontend.state.ThemeMode) {
Icon("content_copy", size = 16.px, color = Color.white)
Text(LocalizedStrings.mcpCopyUrl)
}
- A(href = "${AppConfig.docsUrl}#/guides/mcp.md", attrs = {
+ A(href = AppConfig.docsUrlMcp, attrs = {
attr("target", "_blank")
attr("rel", "noopener noreferrer")
style {
@@ -352,6 +407,30 @@ private fun GeneralSettings(themeMode: flagent.frontend.state.ThemeMode) {
}
}
+@Composable
+private fun LanguageOptionButton(
+ themeMode: flagent.frontend.state.ThemeMode,
+ label: String,
+ isActive: Boolean,
+ onClick: () -> Unit
+) {
+ Button({
+ style {
+ padding(8.px, 14.px)
+ borderRadius(999.px)
+ border(1.px, LineStyle.Solid, if (isActive) FlagentTheme.Primary else FlagentTheme.inputBorder(themeMode))
+ backgroundColor(if (isActive) FlagentTheme.Primary else FlagentTheme.inputBg(themeMode))
+ color(if (isActive) Color.white else FlagentTheme.text(themeMode))
+ cursor("pointer")
+ fontSize(13.px)
+ fontWeight(if (isActive) "600" else "500")
+ }
+ onClick { onClick() }
+ }) {
+ Text(label)
+ }
+}
+
@Composable
private fun SettingItem(themeMode: flagent.frontend.state.ThemeMode, title: String, description: String, value: String) {
Div({
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/components/tenants/TenantsList.kt b/frontend/src/jsMain/kotlin/flagent/frontend/components/tenants/TenantsList.kt
index 64101f47..0948432e 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/components/tenants/TenantsList.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/components/tenants/TenantsList.kt
@@ -92,6 +92,17 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
val planFilter = remember { mutableStateOf(null) }
val statusFilter = remember { mutableStateOf(null) }
val groupBy = remember { mutableStateOf(GroupByOption.None) }
+ val sortColumn = remember { mutableStateOf(null) }
+ val sortAscending = remember { mutableStateOf(true) }
+
+ fun sortTenants(column: String) {
+ if (sortColumn.value == column) {
+ sortAscending.value = !sortAscending.value
+ } else {
+ sortColumn.value = column
+ sortAscending.value = true
+ }
+ }
val filteredTenants =
remember(viewModel.tenants, searchQuery.value, planFilter.value, statusFilter.value) {
@@ -106,13 +117,32 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
}
}
- val groupedTenants = remember(filteredTenants, groupBy.value) {
+ val sortedTenants =
+ remember(filteredTenants, sortColumn.value, sortAscending.value) {
+ var result = filteredTenants.toList()
+ sortColumn.value?.let { column ->
+ result = when (column) {
+ "name" -> result.sortedBy { it.name.lowercase() }
+ "key" -> result.sortedBy { it.key.lowercase() }
+ "plan" -> result.sortedBy { it.plan }
+ "status" -> result.sortedBy { it.status }
+ "createdAt" -> result.sortedBy { it.createdAt }
+ else -> result
+ }
+ if (!sortAscending.value) {
+ result = result.reversed()
+ }
+ }
+ result
+ }
+
+ val groupedTenants = remember(sortedTenants, groupBy.value) {
when (groupBy.value) {
- is GroupByOption.None -> listOf("" to filteredTenants)
- is GroupByOption.ByPlan -> filteredTenants.groupBy { it.plan }.toList()
+ is GroupByOption.None -> listOf("" to sortedTenants)
+ is GroupByOption.ByPlan -> sortedTenants.groupBy { it.plan }.toList()
.sortedBy { it.first }
- is GroupByOption.ByStatus -> filteredTenants.groupBy { it.status }.toList()
+ is GroupByOption.ByStatus -> sortedTenants.groupBy { it.status }.toList()
.sortedBy { it.first }
}
}
@@ -247,7 +277,8 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
key = response.key,
name = response.name,
plan = response.plan,
- status = response.status
+ status = response.status,
+ createdAt = response.createdAt
)
viewModel.storeApiKeyForTenant(tenant.id, key)
viewModel.switchTenant(tenant)
@@ -283,7 +314,7 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
display(DisplayStyle.Flex)
justifyContent(JustifyContent.SpaceBetween)
alignItems(AlignItems.Center)
- marginBottom(24.px)
+ marginBottom(8.px)
}
}) {
H2({
@@ -315,6 +346,15 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
Text(LocalizedStrings.createTenant)
}
}
+ P({
+ style {
+ color(FlagentTheme.textLight(themeMode))
+ marginBottom(20.px)
+ fontSize(13.px)
+ }
+ }) {
+ Text(LocalizedStrings.tenantsOwnerHint)
+ }
val createdApiKey = remember { mutableStateOf(null) }
val createdTenantName = remember { mutableStateOf(null) }
@@ -567,9 +607,63 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
fontWeight(600)
color(FlagentTheme.textLight(themeMode))
textTransform("uppercase")
+ cursor("pointer")
+ property("user-select", "none")
+ }
+ onClick { sortTenants("name") }
+ }) {
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ }
+ }) {
+ Text(LocalizedStrings.nameLabel)
+ if (sortColumn.value == "name") {
+ Span({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.Primary)
+ }
+ }) {
+ Text(if (sortAscending.value) "↑" else "↓")
+ }
+ }
+ }
+ }
+ Th({
+ style {
+ textAlign("left")
+ padding(12.px)
+ fontSize(12.px)
+ fontWeight(600)
+ color(FlagentTheme.TextLight)
+ textTransform("uppercase")
+ cursor("pointer")
+ property("user-select", "none")
}
+ onClick { sortTenants("key") }
}) {
- Text(LocalizedStrings.nameLabel)
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ }
+ }) {
+ Text(LocalizedStrings.keyColumn)
+ if (sortColumn.value == "key") {
+ Span({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.Primary)
+ }
+ }) {
+ Text(if (sortAscending.value) "↑" else "↓")
+ }
+ }
+ }
}
Th({
style {
@@ -579,9 +673,30 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
fontWeight(600)
color(FlagentTheme.TextLight)
textTransform("uppercase")
+ cursor("pointer")
+ property("user-select", "none")
}
+ onClick { sortTenants("plan") }
}) {
- Text(LocalizedStrings.keyColumn)
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ }
+ }) {
+ Text(LocalizedStrings.plan)
+ if (sortColumn.value == "plan") {
+ Span({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.Primary)
+ }
+ }) {
+ Text(if (sortAscending.value) "↑" else "↓")
+ }
+ }
+ }
}
Th({
style {
@@ -591,9 +706,30 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
fontWeight(600)
color(FlagentTheme.TextLight)
textTransform("uppercase")
+ cursor("pointer")
+ property("user-select", "none")
}
+ onClick { sortTenants("status") }
}) {
- Text(LocalizedStrings.plan)
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ }
+ }) {
+ Text(LocalizedStrings.status)
+ if (sortColumn.value == "status") {
+ Span({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.Primary)
+ }
+ }) {
+ Text(if (sortAscending.value) "↑" else "↓")
+ }
+ }
+ }
}
Th({
style {
@@ -603,9 +739,30 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
fontWeight(600)
color(FlagentTheme.TextLight)
textTransform("uppercase")
+ cursor("pointer")
+ property("user-select", "none")
}
+ onClick { sortTenants("createdAt") }
}) {
- Text(LocalizedStrings.status)
+ Span({
+ style {
+ display(DisplayStyle.Flex)
+ alignItems(AlignItems.Center)
+ gap(6.px)
+ }
+ }) {
+ Text(LocalizedStrings.createdAtLabel)
+ if (sortColumn.value == "createdAt") {
+ Span({
+ style {
+ fontSize(12.px)
+ color(FlagentTheme.Primary)
+ }
+ }) {
+ Text(if (sortAscending.value) "↑" else "↓")
+ }
+ }
+ }
}
Th({
style {
@@ -631,7 +788,7 @@ fun TenantsList(tenantViewModel: TenantViewModel? = null) {
}
}) {
Td({
- attr("colspan", "5")
+ attr("colspan", "6")
style {
padding(10.px, 12.px)
fontSize(12.px)
@@ -702,6 +859,10 @@ private fun TenantRow(
Td({ style { padding(12.px); fontSize(14.px); color(FlagentTheme.textLight(themeMode)) } }) {
Text(tenant.status)
}
+ Td({ style { padding(12.px); fontSize(14.px); color(FlagentTheme.textLight(themeMode)) } }) {
+ val createdDate = tenant.createdAt.takeIf { it.length >= 10 }?.take(10) ?: tenant.createdAt
+ Text(createdDate)
+ }
Td({ style { padding(12.px); textAlign("right") } }) {
Div({
style {
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/config/AppConfig.kt b/frontend/src/jsMain/kotlin/flagent/frontend/config/AppConfig.kt
index 1310646a..3e7040ea 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/config/AppConfig.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/config/AppConfig.kt
@@ -128,6 +128,12 @@ object AppConfig {
/** Documentation URL (GitHub Pages, Docsify). */
val docsUrl: String get() = "https://maxluxs.github.io/Flagent/docs.html"
+ /** Doc hash paths (append to docsUrl). */
+ val docsUrlMcp: String get() = "$docsUrl#/guides/mcp"
+ val docsUrlGitOps: String get() = "$docsUrl#/guides/gitops"
+ val docsUrlSdks: String get() = "$docsUrl#/sdks/README"
+ val docsUrlRealtime: String get() = "$docsUrl#/features/real-time-updates"
+
/** Support email for login page and help. */
val supportEmail: String by lazy {
(js("window.ENV_SUPPORT_EMAIL") as? String)?.takeIf { it.isNotBlank() }
@@ -140,8 +146,14 @@ object AppConfig {
}
/** GitHub repository URL. */
val githubUrl: String get() = "https://github.com/MaxLuxs/Flagent"
- /** Blog URL (GitHub Discussions or external). */
- val blogUrl: String get() = "https://github.com/MaxLuxs/Flagent/discussions"
+
+ /** Getting started doc (Quick start) — docs viewer with sidebar/nav. */
+ val gettingStartedUrl: String get() = "https://maxluxs.github.io/Flagent/docs.html#/guides/getting-started"
+
+ /** Enterprise contact email. */
+ val enterpriseContactEmail: String get() = "max.developer.luxs@gmail.com"
+ /** Blog URL (GitHub Pages or external). */
+ val blogUrl: String get() = "https://maxluxs.github.io/Flagent/blog/index.html"
val isEnterprise: Boolean get() = edition == Edition.ENTERPRISE
val isOpenSource: Boolean get() = edition == Edition.OPEN_SOURCE
@@ -223,5 +235,10 @@ object AppConfig {
(js("window.ENV_FEATURE_CRASH_ANALYTICS") as? String)?.toBoolean()
?: true
}
+
+ /** Firebase integration settings tab (read-only status) */
+ val enableFirebaseSettings: Boolean by lazy {
+ (js("window.ENV_FEATURE_FIREBASE_SETTINGS") as? String)?.toBoolean() ?: true
+ }
}
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/i18n/LocalizedStrings.kt b/frontend/src/jsMain/kotlin/flagent/frontend/i18n/LocalizedStrings.kt
index fb5d7e45..daa8fa11 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/i18n/LocalizedStrings.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/i18n/LocalizedStrings.kt
@@ -1,11 +1,17 @@
package flagent.frontend.i18n
+import flagent.frontend.state.LanguageState
+
/**
* Localization strings for Flagent Frontend
*/
object LocalizedStrings {
- // Current locale (default: ru)
- var currentLocale: String = "ru"
+ // Current locale, persisted via LanguageState (default: ru/en from storage)
+ var currentLocale: String
+ get() = LanguageState.current.value
+ set(value) {
+ LanguageState.set(value)
+ }
// Navigation
val home: String get() = when (currentLocale) {
@@ -70,9 +76,24 @@ object LocalizedStrings {
else -> "Create Flag"
}
val createFirstFlag: String get() = when (currentLocale) {
- "ru" -> "Создать первый флаг"
+ "ru" -> "Создай первый флаг"
else -> "Create your first flag"
}
+
+ val emptyFlagsDescription: String get() = when (currentLocale) {
+ "ru" -> "Добавьте feature flag для управления выкаткой, A/B тестами и безопасного отката без деплоя."
+ else -> "Add a feature flag to control rollouts, run A/B tests, and roll back safely without redeploying."
+ }
+
+ val gettingStartedGuideLink: String get() = when (currentLocale) {
+ "ru" -> "Руководство: первый флаг"
+ else -> "Getting started guide"
+ }
+
+ val backToSite: String get() = when (currentLocale) {
+ "ru" -> "Назад на сайт"
+ else -> "Back to site"
+ }
val creating: String get() = when (currentLocale) {
"ru" -> "Создание..."
@@ -94,6 +115,26 @@ object LocalizedStrings {
else -> "Confirm Delete"
}
+ val confirmToggleFlagTitle: String get() = when (currentLocale) {
+ "ru" -> "Переключить флаг?"
+ else -> "Toggle flag?"
+ }
+
+ val confirmToggleFlagMessage: String get() = when (currentLocale) {
+ "ru" -> "Вы действительно хотите переключить статус флага (включить/выключить)?"
+ else -> "Do you really want to toggle this flag (enable/disable)?"
+ }
+
+ val confirmToggleFlagYes: String get() = when (currentLocale) {
+ "ru" -> "Да"
+ else -> "Yes"
+ }
+
+ val confirmToggleFlagNo: String get() = when (currentLocale) {
+ "ru" -> "Нет"
+ else -> "No"
+ }
+
val moreOptions: String get() = when (currentLocale) {
"ru" -> "Еще варианты..."
else -> "More options..."
@@ -783,6 +824,11 @@ object LocalizedStrings {
else -> "Entity Context (JSON):"
}
+ val entityContextPlaceholderHint: String get() = when (currentLocale) {
+ "ru" -> "Пример: user_id, region, tier — для проверки сегментов и ограничений по контексту."
+ else -> "Example: user_id, region, tier — use for segment/constraint targeting by context."
+ }
+
val entitiesJsonArrayWithColon: String get() = when (currentLocale) {
"ru" -> "Сущности (JSON массив):"
else -> "Entities (JSON array):"
@@ -1284,6 +1330,10 @@ object LocalizedStrings {
"ru" -> "Slack"
else -> "Slack"
}
+ val firebaseTab: String get() = when (currentLocale) {
+ "ru" -> "Firebase"
+ else -> "Firebase"
+ }
val billingTab: String get() = when (currentLocale) {
"ru" -> "Биллинг"
else -> "Billing"
@@ -1320,6 +1370,22 @@ object LocalizedStrings {
"ru" -> "Включённые функции"
else -> "Enabled Features"
}
+ val languageLabel: String get() = when (currentLocale) {
+ "ru" -> "Язык интерфейса"
+ else -> "Interface language"
+ }
+ val languageDescription: String get() = when (currentLocale) {
+ "ru" -> "Выберите язык UI. Настройка сохраняется в этом браузере."
+ else -> "Choose UI language. This setting is stored in this browser."
+ }
+ val languageRu: String get() = when (currentLocale) {
+ "ru" -> "Русский"
+ else -> "Russian"
+ }
+ val languageEn: String get() = when (currentLocale) {
+ "ru" -> "Английский"
+ else -> "English"
+ }
val mcpSectionTitle: String get() = when (currentLocale) {
"ru" -> "MCP (AI-ассистенты)"
else -> "MCP (AI Assistants)"
@@ -1336,6 +1402,76 @@ object LocalizedStrings {
"ru" -> "Документация MCP"
else -> "MCP documentation"
}
+
+ // Firebase settings
+ val firebaseSettingsTitle: String get() = when (currentLocale) {
+ "ru" -> "Интеграция Firebase"
+ else -> "Firebase integration"
+ }
+ val firebaseSettingsDescription: String get() = when (currentLocale) {
+ "ru" -> "Здесь отображается статус интеграции с Firebase Remote Config и Firebase Analytics. Настройки задаются через переменные окружения бэкенда."
+ else -> "Shows status of Firebase Remote Config and Firebase Analytics integration. Configuration is managed via backend environment variables."
+ }
+ val firebaseRcTitle: String get() = when (currentLocale) {
+ "ru" -> "Firebase Remote Config sync"
+ else -> "Firebase Remote Config sync"
+ }
+ val firebaseRcDescription: String get() = when (currentLocale) {
+ "ru" -> "Синхронит флаги Flagent в Firebase Remote Config, чтобы мобильные клиенты могли продолжать читать конфигурацию из Firebase."
+ else -> "Syncs Flagent flags to Firebase Remote Config so mobile clients can keep reading configuration from Firebase."
+ }
+ val firebaseAnalyticsTitle: String get() = when (currentLocale) {
+ "ru" -> "Firebase Analytics (GA4)"
+ else -> "Firebase Analytics (GA4)"
+ }
+ val firebaseAnalyticsDescription: String get() = when (currentLocale) {
+ "ru" -> "Отправляет события evaluation в GA4/Firebase Analytics по Measurement Protocol."
+ else -> "Sends evaluation events to GA4/Firebase Analytics via Measurement Protocol."
+ }
+ val firebaseProjectIdLabel: String get() = when (currentLocale) {
+ "ru" -> "Firebase project ID:"
+ else -> "Firebase project ID:"
+ }
+ val firebaseRcSyncIntervalLabel: String get() = when (currentLocale) {
+ "ru" -> "Интервал синка:"
+ else -> "Sync interval:"
+ }
+ val firebaseRcPrefixLabel: String get() = when (currentLocale) {
+ "ru" -> "Префикс параметров:"
+ else -> "Parameter prefix:"
+ }
+ val firebaseRcCredentialsLabel: String get() = when (currentLocale) {
+ "ru" -> "Credentials:"
+ else -> "Credentials:"
+ }
+ val firebaseMeasurementIdLabel: String get() = when (currentLocale) {
+ "ru" -> "Measurement ID:"
+ else -> "Measurement ID:"
+ }
+ val firebaseApiSecretLabel: String get() = when (currentLocale) {
+ "ru" -> "API Secret:"
+ else -> "API Secret:"
+ }
+ val configPresent: String get() = when (currentLocale) {
+ "ru" -> "сконфигурировано"
+ else -> "configured"
+ }
+ val configMissing: String get() = when (currentLocale) {
+ "ru" -> "не задано"
+ else -> "not set"
+ }
+ val firebaseConfigSectionTitle: String get() = when (currentLocale) {
+ "ru" -> "Настройка через переменные окружения"
+ else -> "Configuration via environment variables"
+ }
+ val firebaseConfigSectionDescription: String get() = when (currentLocale) {
+ "ru" -> "Изменить интеграцию Firebase можно только через переменные окружения бэкенда. Этот экран показывает текущий статус."
+ else -> "Firebase integration is configured only via backend environment variables. This screen shows the current status."
+ }
+ val firebaseDocsLinkText: String get() = when (currentLocale) {
+ "ru" -> "Документация по интеграции Firebase"
+ else -> "Firebase integration docs"
+ }
val billingTitle: String get() = when (currentLocale) {
"ru" -> "Биллинг и подписка"
else -> "Billing & Subscription"
@@ -1570,6 +1706,15 @@ object LocalizedStrings {
"ru" -> "Нет данных метрик за выбранный период"
else -> "No metrics data for the selected period"
}
+ /** Hint when Overview (evaluation metrics) is empty; events are on Events tab */
+ val analyticsOverviewEmptyHint: String get() = when (currentLocale) {
+ "ru" -> "Здесь — метрики по оценкам флагов (evaluations). События (first_open, screen_view) — на вкладке «События»."
+ else -> "This tab shows evaluation metrics. For event analytics (first_open, screen_view) open the Events tab."
+ }
+ val switchToEventsTab: String get() = when (currentLocale) {
+ "ru" -> "Перейти к событиям"
+ else -> "Go to Events"
+ }
val metricsUnavailable: String get() = when (currentLocale) {
"ru" -> "Метрики временно недоступны"
else -> "Metrics temporarily unavailable"
@@ -1594,6 +1739,30 @@ object LocalizedStrings {
"ru" -> "Система работает нормально"
else -> "System operational"
}
+ val healthNoEvaluations: String get() = when (currentLocale) {
+ "ru" -> "Нет обращений к API за период"
+ else -> "No API calls in period"
+ }
+ fun healthAnomaliesCount(n: Int): String = when (currentLocale) {
+ "ru" -> "Есть $n аномалий"
+ else -> "$n anomalies"
+ }
+ fun dataUpdatedMinutesAgo(min: Int): String = when (currentLocale) {
+ "ru" -> "Данные обновлены $min мин назад"
+ else -> "Data updated $min min ago"
+ }
+ fun dashboardTenantLabel(tenantName: String): String = when (currentLocale) {
+ "ru" -> "Тенант: $tenantName"
+ else -> "Tenant: $tenantName"
+ }
+ fun crashesInPeriod(count: Int, periodLabel: String): String = when (currentLocale) {
+ "ru" -> "$count крашей за $periodLabel"
+ else -> "$count crashes in $periodLabel"
+ }
+ val openCrashDashboard: String get() = when (currentLocale) {
+ "ru" -> "Открыть Краши"
+ else -> "Open Crash"
+ }
val flagActivityOverPeriod: String get() = when (currentLocale) {
"ru" -> "Активность флагов за период"
else -> "Flag activity over period"
@@ -1674,6 +1843,16 @@ object LocalizedStrings {
"ru" -> "Активные флаги"
else -> "Active flags"
}
+
+ val moreOftenWithFlags: String get() = when (currentLocale) {
+ "ru" -> "Чаще при включённых флагах"
+ else -> "More often with these flags enabled"
+ }
+
+ val disableFlag: String get() = when (currentLocale) {
+ "ru" -> "Выключить флаг"
+ else -> "Disable flag"
+ }
val cardsView: String get() = when (currentLocale) {
"ru" -> "Карточки"
else -> "Cards"
@@ -1694,6 +1873,10 @@ object LocalizedStrings {
"ru" -> "Выберите другой фильтр выше (Все / Включённые / Выключенные)"
else -> "Select a different filter above (All / Enabled / Disabled)"
}
+ val searchExperimentsPlaceholder: String get() = when (currentLocale) {
+ "ru" -> "Поиск по ключу или описанию…"
+ else -> "Search by key or description…"
+ }
val filterAll: String get() = when (currentLocale) {
"ru" -> "Все"
else -> "All"
@@ -1874,6 +2057,10 @@ object LocalizedStrings {
"ru" -> "Email владельца"
else -> "Owner Email"
}
+ val tenantsOwnerHint: String get() = when (currentLocale) {
+ "ru" -> "Владелец, которого вы указываете при создании тенанта, становится первым tenant‑пользователем с правами OWNER и появится во вкладке «Роли» на странице настроек."
+ else -> "The owner email you specify when creating a tenant becomes the first tenant user with OWNER role and will appear in the Roles tab on the Settings page."
+ }
val switchTenant: String get() = when (currentLocale) {
"ru" -> "Переключить"
else -> "Switch"
@@ -1898,11 +2085,24 @@ object LocalizedStrings {
"ru" -> "По статусу"
else -> "Group by status"
}
+ val groupByFlag: String get() = when (currentLocale) {
+ "ru" -> "По флагу"
+ else -> "By flag"
+ }
+ val filterByFlagPlaceholder: String get() = when (currentLocale) {
+ "ru" -> "Флаг"
+ else -> "Flag"
+ }
val actionsLabel: String get() = when (currentLocale) {
"ru" -> "Действия"
else -> "Actions"
}
+ val createdAtLabel: String get() = when (currentLocale) {
+ "ru" -> "Создан"
+ else -> "Created"
+ }
+
// Pagination (override if different from previous/next)
val previousLabel: String get() = when (currentLocale) {
"ru" -> "Назад"
@@ -2083,13 +2283,17 @@ object LocalizedStrings {
else -> "Roles & Permissions"
}
val manageRolesDescription: String get() = when (currentLocale) {
- "ru" -> "Управление ролями и назначение прав пользователям."
- else -> "Manage roles and assign permissions to users."
+ "ru" -> "Управление ролями и назначение прав tenant‑пользователям."
+ else -> "Manage roles and assign permissions to tenant users."
}
val availableRoles: String get() = when (currentLocale) {
"ru" -> "Доступные роли"
else -> "Available Roles"
}
+ val rolesTenantUsersHint: String get() = when (currentLocale) {
+ "ru" -> "На этой вкладке управляются роли tenant‑пользователей (владельцы и участники конкретного тенанта). Первый пользователь создаётся при создании тенанта (email владельца в форме), остальные обычно приходят из SSO или Enterprise‑приглашений."
+ else -> "This screen manages roles for tenant users (owners and members of a specific tenant). The first user is created when you create a tenant (owner email in the form); other users usually come from SSO or Enterprise invite flows."
+ }
val builtIn: String get() = when (currentLocale) {
"ru" -> "Встроенная"
else -> "Built-in"
@@ -2110,6 +2314,10 @@ object LocalizedStrings {
"ru" -> "Управление учётными записями администраторов (вход в UI)."
else -> "Manage admin user accounts (UI login)."
}
+ val adminUsersExtraHint: String get() = when (currentLocale) {
+ "ru" -> "Эти аккаунты входят в веб‑интерфейс Flagent и всегда имеют полный доступ к админке. Для разграничения доступа команд к данным конкретного тенанта используйте вкладку «Роли» (tenant‑пользователи и RBAC)."
+ else -> "These accounts sign in to the Flagent admin UI and always have full access. To control which teams can access data of a specific tenant, use the Roles tab (tenant users and RBAC)."
+ }
val addUser: String get() = when (currentLocale) {
"ru" -> "Добавить пользователя"
else -> "Add user"
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/state/GlobalState.kt b/frontend/src/jsMain/kotlin/flagent/frontend/state/GlobalState.kt
index 12ea05a5..c726fe2b 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/state/GlobalState.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/state/GlobalState.kt
@@ -69,7 +69,8 @@ data class Tenant(
val key: String,
val name: String,
val plan: String = "STARTER",
- val status: String = "ACTIVE"
+ val status: String = "ACTIVE",
+ val createdAt: String = ""
)
/**
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/state/LanguageState.kt b/frontend/src/jsMain/kotlin/flagent/frontend/state/LanguageState.kt
new file mode 100644
index 00000000..13e5813a
--- /dev/null
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/state/LanguageState.kt
@@ -0,0 +1,41 @@
+package flagent.frontend.state
+
+import androidx.compose.runtime.mutableStateOf
+import kotlinx.browser.document
+import kotlinx.browser.localStorage
+
+private const val LOCALE_STORAGE_KEY = "flagent_locale"
+
+/**
+ * Language state with persistence in browser localStorage.
+ * Used by LocalizedStrings for runtime language switching.
+ */
+object LanguageState {
+ val current = mutableStateOf("ru")
+
+ init {
+ val stored = localStorage.getItem(LOCALE_STORAGE_KEY)
+ val normalized = normalize(stored)
+ current.value = normalized
+ applyToDocument(normalized)
+ }
+
+ fun set(locale: String) {
+ val normalized = normalize(locale)
+ current.value = normalized
+ localStorage.setItem(LOCALE_STORAGE_KEY, normalized)
+ applyToDocument(normalized)
+ }
+
+ private fun normalize(locale: String?): String =
+ when (locale?.lowercase()) {
+ "ru" -> "ru"
+ "en" -> "en"
+ else -> "en"
+ }
+
+ private fun applyToDocument(locale: String) {
+ document.documentElement?.setAttribute("lang", locale)
+ }
+}
+
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/theme/Backgrounds.kt b/frontend/src/jsMain/kotlin/flagent/frontend/theme/Backgrounds.kt
new file mode 100644
index 00000000..5827ab15
--- /dev/null
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/theme/Backgrounds.kt
@@ -0,0 +1,54 @@
+package flagent.frontend.theme
+
+import androidx.compose.runtime.Composable
+import flagent.frontend.state.ThemeMode
+import org.jetbrains.compose.web.css.*
+import org.jetbrains.compose.web.dom.Div
+
+/**
+ * Shared gradient background layer used across marketing landing,
+ * login screen and (optionally) app shell.
+ *
+ * Renders a fixed full-viewport gradient and then invokes [content] on top.
+ */
+@Composable
+fun AppGradientBackground(content: @Composable () -> Unit) {
+ // Backwards-compatible: always use dark hero gradient.
+ GradientBackgroundLayer(FlagentTheme.GradientHero, content)
+}
+
+/**
+ * Themed variant of [AppGradientBackground] that switches gradient
+ * based on [ThemeMode] using FlagentTheme.heroGradient.
+ *
+ * Currently not wired anywhere by default to avoid visual regressions;
+ * use explicitly where needed.
+ */
+@Composable
+fun AppGradientBackground(
+ mode: ThemeMode,
+ content: @Composable () -> Unit
+) {
+ val gradient = FlagentTheme.heroGradient(mode)
+ GradientBackgroundLayer(gradient, content)
+}
+
+@Composable
+private fun GradientBackgroundLayer(
+ background: String,
+ content: @Composable () -> Unit
+) {
+ Div(attrs = {
+ style {
+ position(Position.Fixed)
+ property("inset", "0")
+ property("z-index", "0")
+ property("pointer-events", "none")
+ property("background", background)
+ property("background-size", "400% 400%")
+ property("animation", "morphGradient 20s ease infinite")
+ }
+ }) {}
+ content()
+}
+
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/theme/Theme.kt b/frontend/src/jsMain/kotlin/flagent/frontend/theme/Theme.kt
index 69b10f0e..07e09a57 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/theme/Theme.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/theme/Theme.kt
@@ -122,6 +122,20 @@ object FlagentTheme {
ThemeMode.Light -> Color(v("color-light-infoBg"))
}
+ /**
+ * Hero gradient depending on ThemeMode.
+ *
+ * Dark: dedicated GradientHero (deep dark background).
+ * Light: subtle vertical light gradient based on light background tokens.
+ */
+ fun heroGradient(mode: ThemeMode): String = when (mode) {
+ ThemeMode.Dark -> GradientHero
+ ThemeMode.Light -> "linear-gradient(180deg, " +
+ "${cssVar("color-light-background")} 0%, " +
+ "${cssVar("color-light-backgroundAlt")} 40%, " +
+ "${cssVar("color-light-backgroundDark")} 100%)"
+ }
+
/** CSS variable string for use in property("border", "1px solid ${FlagentTheme.cssVar(\"color-dark-cardBorder\")}") etc. */
fun cssVar(suffix: String) = "var(--flagent-$suffix)"
}
diff --git a/frontend/src/jsMain/kotlin/flagent/frontend/viewmodel/TenantViewModel.kt b/frontend/src/jsMain/kotlin/flagent/frontend/viewmodel/TenantViewModel.kt
index ce8f489c..6c652107 100644
--- a/frontend/src/jsMain/kotlin/flagent/frontend/viewmodel/TenantViewModel.kt
+++ b/frontend/src/jsMain/kotlin/flagent/frontend/viewmodel/TenantViewModel.kt
@@ -166,5 +166,6 @@ private fun TenantResponse.toTenant() = Tenant(
key = key,
name = name,
plan = plan,
- status = status
+ status = status,
+ createdAt = createdAt
)
diff --git a/frontend/src/jsMain/resources/index.html b/frontend/src/jsMain/resources/index.html
index 1e7ec1d2..a6041694 100644
--- a/frontend/src/jsMain/resources/index.html
+++ b/frontend/src/jsMain/resources/index.html
@@ -4,6 +4,7 @@
Flagent - Feature Flags Management
+
diff --git a/frontend/src/jsMain/resources/index.production.html b/frontend/src/jsMain/resources/index.production.html
index d7517bf8..4093fc2c 100644
--- a/frontend/src/jsMain/resources/index.production.html
+++ b/frontend/src/jsMain/resources/index.production.html
@@ -4,6 +4,7 @@
Flagent - Feature Flags Management
+
diff --git a/frontend/src/jsMain/resources/screenshot-dashboard.png b/frontend/src/jsMain/resources/screenshot-dashboard.png
new file mode 100644
index 00000000..598c593b
Binary files /dev/null and b/frontend/src/jsMain/resources/screenshot-dashboard.png differ
diff --git a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentExtension.kt b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentExtension.kt
index 5910068c..3ff1b91d 100644
--- a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentExtension.kt
+++ b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentExtension.kt
@@ -1,6 +1,7 @@
package com.flagent.gradle
import org.gradle.api.Project
+import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import java.io.File
@@ -30,9 +31,36 @@ abstract class FlagentExtension constructor(@org.gradle.api.tasks.Internal val p
*/
abstract val failOnUnknown: Property
+ // --- generateFlagKeys ---
+
+ /**
+ * Output directory for generated FlagKeys.kt. Default: build/generated/sources/flagent/flagKeys
+ */
+ abstract val flagKeysOutputDir: DirectoryProperty
+
+ /**
+ * Format of generated file: "object" (const vals) or "enum". Default: "object"
+ */
+ abstract val flagKeysFormat: Property
+
+ /**
+ * Package name for the generated class. Default: "flagent.generated" or project group + ".generated"
+ */
+ abstract val flagKeysPackage: Property
+
+ /**
+ * When true, build fails if code uses raw string in isEnabled("...")/evaluate("...");
+ * only keys from generated FlagKeys or @FlagKey are allowed.
+ */
+ abstract val allowOnlyGeneratedOrAnnotated: Property
+
init {
baseUrl.convention("http://localhost:18000")
apiKey.convention("")
failOnUnknown.convention(true)
+ flagKeysOutputDir.convention(project.layout.buildDirectory.dir("generated/sources/flagent/flagKeys"))
+ flagKeysFormat.convention("object")
+ flagKeysPackage.convention("flagent.generated")
+ allowOnlyGeneratedOrAnnotated.convention(false)
}
}
diff --git a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentPlugin.kt b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentPlugin.kt
index f4b6d7b2..3f64fadb 100644
--- a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentPlugin.kt
+++ b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/FlagentPlugin.kt
@@ -1,5 +1,6 @@
package com.flagent.gradle
+import com.flagent.gradle.tasks.GenerateFlagKeysTask
import com.flagent.gradle.tasks.VerifyFlagsTask
import org.gradle.api.Plugin
import org.gradle.api.Project
@@ -7,8 +8,21 @@ import org.gradle.api.Project
class FlagentPlugin : Plugin {
override fun apply(project: Project) {
val ext = project.extensions.create("flagent", FlagentExtension::class.java, project)
+
project.tasks.register("verifyFlags", VerifyFlagsTask::class.java) { t: VerifyFlagsTask ->
t.extension.set(ext)
}
+
+ val generateFlagKeys = project.tasks.register("generateFlagKeys", GenerateFlagKeysTask::class.java) { t: GenerateFlagKeysTask ->
+ t.extension.set(ext)
+ t.outputDir.set(ext.flagKeysOutputDir)
+ }
+
+ // Run generateFlagKeys before any Kotlin compile. User must add output dir to source sets.
+ project.afterEvaluate {
+ project.tasks.matching { it.name.startsWith("compileKotlin") }.configureEach {
+ it.dependsOn(generateFlagKeys)
+ }
+ }
}
}
diff --git a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/scanner/FlagKeyScanner.kt b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/scanner/FlagKeyScanner.kt
index 90b4d076..3a39ed7e 100644
--- a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/scanner/FlagKeyScanner.kt
+++ b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/scanner/FlagKeyScanner.kt
@@ -4,14 +4,18 @@ import java.io.File
/**
* Scans Kotlin/Java source files for flag key references.
- * Matches: @FlagKey("key"), isEnabled("key"), evaluate("key")
+ * Matches: @FlagKey("key"), isEnabled("key"), evaluate("key"), evaluateBatch(flagKeys = listOf("key"), ...)
*/
object FlagKeyScanner {
private val FLAG_KEY_ANNOTATION = Regex("""@FlagKey\s*\(\s*"([^"]+)"\s*\)""")
- private val STRING_IN_QUOTES = Regex(""""([a-zA-Z][a-zA-Z0-9_]*(_[a-zA-Z0-9]+)*)"(?!\s*\))""")
private val IS_ENABLED_OR_EVALUATE = Regex("""(?:isEnabled|evaluate)\s*\(\s*"([^"]+)"\s*[\),]""")
+ /** Match "key" inside listOf("key1", "key2") in evaluateBatch */
+ private val STRING_LITERAL_IN_QUOTES = Regex(""""([^"]+)"\s*(?:,\s*|\s*\)|\s*\])""")
+ /**
+ * All flag keys found in source: from @FlagKey, isEnabled("..."), evaluate("..."), evaluateBatch listOf("...").
+ */
fun scanSourceFiles(files: Collection): Set {
val keys = mutableSetOf()
for (file in files) {
@@ -19,10 +23,61 @@ object FlagKeyScanner {
val content = file.readText()
keys.addAll(FLAG_KEY_ANNOTATION.findAll(content).map { it.groupValues[1] })
keys.addAll(IS_ENABLED_OR_EVALUATE.findAll(content).map { it.groupValues[1] })
+ keys.addAll(scanEvaluateBatchRawStrings(content))
}
return keys.filter { isValidFlagKey(it) }.toSet()
}
+ /**
+ * Keys only from @FlagKey("...") annotations.
+ */
+ fun scanKeysFromAnnotations(files: Collection): Set {
+ val keys = mutableSetOf()
+ for (file in files) {
+ if (!file.name.endsWith(".kt") && !file.name.endsWith(".java")) continue
+ keys.addAll(FLAG_KEY_ANNOTATION.findAll(file.readText()).map { it.groupValues[1] })
+ }
+ return keys.filter { isValidFlagKey(it) }.toSet()
+ }
+
+ /**
+ * Keys only from raw string literals in isEnabled("..."), evaluate("..."), and evaluateBatch(..., listOf("..."), ...).
+ * Used when allowOnlyGeneratedOrAnnotated is true to fail the build if any raw strings are used.
+ */
+ fun scanKeysFromRawStrings(files: Collection): Set {
+ val keys = mutableSetOf()
+ for (file in files) {
+ if (!file.name.endsWith(".kt") && !file.name.endsWith(".java")) continue
+ val content = file.readText()
+ keys.addAll(IS_ENABLED_OR_EVALUATE.findAll(content).map { it.groupValues[1] })
+ keys.addAll(scanEvaluateBatchRawStrings(content))
+ }
+ return keys.filter { isValidFlagKey(it) }.toSet()
+ }
+
+ private fun scanEvaluateBatchRawStrings(content: String): Set {
+ val keys = mutableSetOf()
+ // Match evaluateBatch(..., flagKeys = listOf("a", "b"), ...) or evaluateBatch(listOf("a","b"), ...)
+ val listOfBlocks = Regex("""(?:evaluateBatch|evaluateBatchAsync)\s*\([^)]*listOf\s*\([^)]+\)[^)]*\)""").findAll(content)
+ for (block in listOfBlocks) {
+ STRING_LITERAL_IN_QUOTES.findAll(block.value).forEach { keys.add(it.groupValues[1].trim()) }
+ }
+ return keys
+ }
+
+ /**
+ * Reads key values from a generated FlagKeys.kt file (object with const val X = "key" or enum X("key")).
+ */
+ fun loadKeysFromGeneratedFile(file: File): Set {
+ if (!file.exists() || !file.name.endsWith(".kt")) return emptySet()
+ val content = file.readText()
+ val keys = mutableSetOf()
+ // const val NAME = "key" or enum NAME("key")
+ val valuePattern = Regex("""(?:=\s*|\(\s*)"([a-zA-Z][a-zA-Z0-9_]*(_[a-zA-Z0-9]+)*)"\s*[\),;]""")
+ valuePattern.findAll(content).forEach { keys.add(it.groupValues[1]) }
+ return keys
+ }
+
private fun isValidFlagKey(key: String): Boolean {
if (key.length < 2) return false
return key.matches(Regex("[a-zA-Z][a-zA-Z0-9_]*(_[a-zA-Z0-9]+)*"))
diff --git a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/GenerateFlagKeysTask.kt b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/GenerateFlagKeysTask.kt
new file mode 100644
index 00000000..fce51e25
--- /dev/null
+++ b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/GenerateFlagKeysTask.kt
@@ -0,0 +1,134 @@
+package com.flagent.gradle.tasks
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import com.fasterxml.jackson.module.kotlin.readValue
+import com.flagent.gradle.FlagentExtension
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.OutputDirectory
+import org.gradle.api.tasks.TaskAction
+import java.io.File
+import java.net.URI
+import java.net.http.HttpClient
+import java.net.http.HttpRequest
+import java.net.http.HttpResponse
+
+/**
+ * Generates FlagKeys.kt (object or enum) from Flagent API or flags file.
+ * Register output dir in sourceSets so generated code is compiled.
+ */
+abstract class GenerateFlagKeysTask : DefaultTask() {
+
+ @get:org.gradle.api.tasks.Internal
+ abstract val extension: Property
+
+ @get:OutputDirectory
+ abstract val outputDir: DirectoryProperty
+
+ @TaskAction
+ fun generate() {
+ val ext = extension.get()
+ val keys = when {
+ ext.flagsFile.orNull?.asFile?.exists() == true -> loadFromFile(ext.flagsFile.get().asFile)
+ else -> fetchFromApi(ext.baseUrl.get(), ext.apiKey.get())
+ }
+ if (keys.isEmpty()) {
+ logger.warn("generateFlagKeys: no keys from API or file; skipping generation")
+ return
+ }
+ val format = ext.flagKeysFormat.get().lowercase().let {
+ if (it != "enum") "object" else "enum"
+ }
+ val pkg = ext.flagKeysPackage.get().trim().ifEmpty { "flagent.generated" }
+ val content = if (format == "object") generateObject(pkg, keys) else generateEnum(pkg, keys)
+ val outDir = outputDir.get().asFile
+ outDir.mkdirs()
+ val outFile = File(outDir, "FlagKeys.kt")
+ outFile.writeText(content)
+ logger.lifecycle("generateFlagKeys: wrote {} keys to {}", keys.size, outFile)
+ }
+
+ private fun loadFromFile(file: File): Set {
+ val content = file.readText()
+ val mapper = when {
+ file.extension.lowercase() in listOf("yaml", "yml") ->
+ ObjectMapper(YAMLFactory()).findAndRegisterModules()
+ else -> jacksonObjectMapper()
+ }
+ val tree = mapper.readTree(content)
+ val flags = when {
+ tree.isObject && tree.has("flags") -> tree.get("flags")
+ tree.isArray -> tree
+ else -> mapper.createArrayNode()
+ }
+ return (0 until flags.size()).mapNotNull { flags.get(it).get("key")?.asText()?.takeIf { k -> k.isNotBlank() } }.toSet()
+ }
+
+ private fun fetchFromApi(baseUrl: String, apiKey: String): Set {
+ val url = baseUrl.trimEnd('/').let {
+ if (it.endsWith("/api/v1")) it else "$it/api/v1"
+ } + "/flags?limit=1000"
+ val client = HttpClient.newBuilder().build()
+ val reqBuilder = HttpRequest.newBuilder(URI.create(url)).header("Accept", "application/json")
+ if (apiKey.isNotBlank()) reqBuilder.header("X-API-Key", apiKey)
+ val res = client.send(reqBuilder.build(), HttpResponse.BodyHandlers.ofString())
+ if (res.statusCode() != 200) {
+ logger.warn("generateFlagKeys: API returned {}, no keys loaded", res.statusCode())
+ return emptySet()
+ }
+ @Suppress("UNCHECKED_CAST")
+ val flags = jacksonObjectMapper().readValue>>(res.body())
+ return flags.mapNotNull { it["key"]?.toString() }.toSet()
+ }
+
+ /**
+ * Convert flag key to valid Kotlin constant name (UPPER_SNAKE_CASE).
+ * Leading digits get prefix; invalid chars replaced with underscore.
+ */
+ private fun keyToConstantName(key: String): String {
+ if (key.isBlank()) return "UNKNOWN"
+ val normalized = key.trim()
+ .replace(Regex("[^a-zA-Z0-9_]"), "_")
+ .replace(Regex("_+"), "_")
+ .trim('_')
+ if (normalized.isEmpty()) return "UNKNOWN"
+ val upper = normalized.uppercase()
+ return if (upper[0].isDigit()) "KEY_$upper" else upper
+ }
+
+ private fun generateObject(pkg: String, keys: Set): String {
+ val lines = keys.sorted().map { key ->
+ val name = keyToConstantName(key)
+ " const val $name: String = \"$key\""
+ }
+ return """
+ |// Generated by Flagent Gradle plugin — do not edit
+ |package $pkg
+ |
+ |object FlagKeys {
+ |${lines.joinToString("\n")}
+ |}
+ |
+ """.trimMargin()
+ }
+
+ private fun generateEnum(pkg: String, keys: Set): String {
+ val entries = keys.sorted().map { key ->
+ val name = keyToConstantName(key)
+ " $name(\"$key\")"
+ }
+ return """
+ |// Generated by Flagent Gradle plugin — do not edit
+ |package $pkg
+ |
+ |enum class FlagKey(val key: String) {
+ |${entries.joinToString(",\n")}
+ |}
+ |
+ """.trimMargin()
+ }
+}
diff --git a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/VerifyFlagsTask.kt b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/VerifyFlagsTask.kt
index 2fe8535b..8c183854 100644
--- a/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/VerifyFlagsTask.kt
+++ b/gradle-plugins/flagent-gradle-plugin/src/main/kotlin/com/flagent/gradle/tasks/VerifyFlagsTask.kt
@@ -25,6 +25,26 @@ abstract class VerifyFlagsTask : DefaultTask() {
fun verify() {
val ext = extension.get()
val files = project.fileTree(mapOf("dir" to "src", "include" to listOf("**/*.kt", "**/*.java"))).files
+
+ if (ext.allowOnlyGeneratedOrAnnotated.get()) {
+ val annotationKeys = FlagKeyScanner.scanKeysFromAnnotations(files)
+ val generatedKeys = try {
+ val dir = ext.flagKeysOutputDir.get().asFile
+ FlagKeyScanner.loadKeysFromGeneratedFile(java.io.File(dir, "FlagKeys.kt"))
+ } catch (_: Exception) {
+ emptySet()
+ }
+ val allowedKeys = annotationKeys + generatedKeys
+ val rawKeys = FlagKeyScanner.scanKeysFromRawStrings(files)
+ if (rawKeys.isNotEmpty()) {
+ throw org.gradle.api.GradleException(
+ "verifyFlags (allowOnlyGeneratedOrAnnotated=true): raw string literals in isEnabled(\"...\") / evaluate(\"...\") are not allowed. " +
+ "Use FlagKeys.* or @FlagKey constants. Forbidden usages: ${rawKeys.sorted().joinToString(", ")}"
+ )
+ }
+ logger.lifecycle("verifyFlags: strict mode OK (all keys from FlagKeys or @FlagKey)")
+ }
+
val codeKeys = FlagKeyScanner.scanSourceFiles(files)
if (codeKeys.isEmpty()) {
logger.lifecycle("verifyFlags: no flag keys found in source code")
diff --git a/internal/flagent-enterprise b/internal/flagent-enterprise
index 093afd07..466ffd7b 160000
--- a/internal/flagent-enterprise
+++ b/internal/flagent-enterprise
@@ -1 +1 @@
-Subproject commit 093afd07553c35ce9f656abcc0217f8eeae867d1
+Subproject commit 466ffd7b7172eabcfe2250c4ccce788770714710
diff --git a/samples/android/README.md b/samples/android/README.md
index 5a391602..422a1df7 100644
--- a/samples/android/README.md
+++ b/samples/android/README.md
@@ -9,6 +9,8 @@ Sample Android application demonstrating the usage of Flagent SDK for feature fl
- **Caching** - Enhanced SDK provides automatic caching of evaluation results
- **Debug UI** - Visual debugging interface for flags and evaluations
- **Settings** - Configure API base URL, cache settings, and authentication
+- **OpenFeature-like client** - Demonstrates the `kotlin-openfeature` KMP client
+ and how it maps Flagent evaluations into an OpenFeature-style API
## Requirements
@@ -68,6 +70,17 @@ The result will show:
- Debug log (if enabled)
- Cache indicator (for Enhanced SDK)
+The screen also contains an **OpenFeature-like** section that uses the
+`kotlin-openfeature` KMP module:
+
+- Boolean flag: `new_android_ui`
+- Integer config: `cart_max_items` (value read from `variantAttachment.value`)
+- Double config: `discount_rate` (value read from `variantAttachment.value`)
+
+These flags are seeded automatically by `./scripts/seed-demo-data.sh`,
+so after seeding and starting the backend the Android sample will show
+meaningful values out of the box.
+
### Batch Evaluation Screen
Evaluate multiple flags for multiple entities:
diff --git a/samples/android/app/build.gradle.kts b/samples/android/app/build.gradle.kts
index 7229c290..9e62fb71 100644
--- a/samples/android/app/build.gradle.kts
+++ b/samples/android/app/build.gradle.kts
@@ -67,6 +67,7 @@ dependencies {
implementation(project(":kotlin-enhanced"))
implementation(project(":kotlin-debug-ui"))
implementation(project(":flagent-koin"))
+ implementation(project(":kotlin-openfeature"))
implementation(libs.koin.android)
diff --git a/samples/android/app/src/main/java/com/flagent/sample/ui/screens/EvaluationScreen.kt b/samples/android/app/src/main/java/com/flagent/sample/ui/screens/EvaluationScreen.kt
index d6b29f3e..07cd3d74 100644
--- a/samples/android/app/src/main/java/com/flagent/sample/ui/screens/EvaluationScreen.kt
+++ b/samples/android/app/src/main/java/com/flagent/sample/ui/screens/EvaluationScreen.kt
@@ -49,6 +49,7 @@ fun EvaluationScreen(
var entityID by remember { mutableStateOf("user1") }
var entityType by remember { mutableStateOf("user") }
var entityContextJson by remember { mutableStateOf("{\"region\": \"US\", \"tier\": \"premium\"}") }
+ var openFeatureFlagKey by remember { mutableStateOf("new_android_ui") }
Column(
modifier = Modifier
@@ -135,6 +136,41 @@ fun EvaluationScreen(
Text("Evaluate (Enhanced SDK)")
}
+ Divider()
+
+ Text(
+ text = "OpenFeature-like evaluation",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = "Uses kotlin-openfeature KMP client on top of Flagent HTTP evaluation.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ OutlinedTextField(
+ value = openFeatureFlagKey,
+ onValueChange = { openFeatureFlagKey = it },
+ label = { Text("Feature flag key (boolean)") },
+ modifier = Modifier.fillMaxWidth(),
+ singleLine = true
+ )
+
+ Button(
+ onClick = {
+ viewModel.evaluateOpenFeatureLike(
+ flagKey = openFeatureFlagKey.ifBlank { "new_android_ui" },
+ entityID = entityID.ifBlank { "user1" },
+ entityType = entityType.ifBlank { "user" },
+ entityContext = parseContextMapOrNull(entityContextJson)
+ )
+ },
+ modifier = Modifier.fillMaxWidth(),
+ enabled = state !is EvaluationState.Loading
+ ) {
+ Text("Evaluate (OpenFeature-like)")
+ }
+
when (val s = state) {
is EvaluationState.Success -> {
Card(
@@ -181,6 +217,40 @@ fun EvaluationScreen(
}
}
}
+ is EvaluationState.OpenFeatureSuccess -> {
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.secondaryContainer
+ )
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = "OpenFeature-like result",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ Text(
+ text = "Enabled: ${s.enabled}",
+ color = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ Text(
+ text = "Max items: ${s.maxItems}",
+ color = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ Text(
+ text = "Discount: ${s.discount}",
+ color = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ }
+ }
+ }
is EvaluationState.Error -> {
Card(
modifier = Modifier.fillMaxWidth(),
diff --git a/samples/android/app/src/main/java/com/flagent/sample/viewmodel/EvaluationViewModel.kt b/samples/android/app/src/main/java/com/flagent/sample/viewmodel/EvaluationViewModel.kt
index fce2d360..93911909 100644
--- a/samples/android/app/src/main/java/com/flagent/sample/viewmodel/EvaluationViewModel.kt
+++ b/samples/android/app/src/main/java/com/flagent/sample/viewmodel/EvaluationViewModel.kt
@@ -7,6 +7,11 @@ import com.flagent.client.models.EvalContext
import com.flagent.client.models.EvalResult
import com.flagent.enhanced.manager.FlagentManager
import com.flagent.sample.di.AppModule
+import com.flagent.openfeature.AttributeValue
+import com.flagent.openfeature.DefaultOpenFeatureClient
+import com.flagent.openfeature.EvaluationContext as OfEvaluationContext
+import com.flagent.openfeature.FlagentOpenFeatureConfig
+import com.flagent.openfeature.FlagentOpenFeatureProvider
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -20,6 +25,11 @@ sealed class EvaluationState {
object Loading : EvaluationState()
data class Success(val result: EvalResult, val fromCache: Boolean = false) : EvaluationState()
data class Error(val message: String, val throwable: Throwable? = null) : EvaluationState()
+ data class OpenFeatureSuccess(
+ val enabled: Boolean,
+ val maxItems: Int,
+ val discount: Double
+ ) : EvaluationState()
}
class EvaluationViewModel : ViewModel() {
@@ -29,12 +39,21 @@ class EvaluationViewModel : ViewModel() {
private var currentBaseUrl: String = ""
private var evaluationApi: EvaluationApi? = null
private var flagentManager: FlagentManager? = null
+ private var openFeatureClient: DefaultOpenFeatureClient? = null
fun initialize(baseUrl: String) {
if (currentBaseUrl != baseUrl) {
currentBaseUrl = baseUrl
evaluationApi = AppModule.getEvaluationApi(baseUrl)
flagentManager = AppModule.getFlagentManager(baseUrl, com.flagent.enhanced.config.FlagentConfig())
+ openFeatureClient = DefaultOpenFeatureClient(
+ FlagentOpenFeatureProvider(
+ FlagentOpenFeatureConfig(baseUrl = baseUrl) { api ->
+ // Reuse the same auth as other SDKs if configured in AppModule in the future.
+ // For now this sample uses default public dev settings.
+ }
+ )
+ )
}
}
@@ -73,6 +92,65 @@ class EvaluationViewModel : ViewModel() {
}
}
}
+
+ fun evaluateOpenFeatureLike(
+ flagKey: String,
+ entityID: String,
+ entityType: String? = null,
+ entityContext: Map? = null
+ ) {
+ val client = openFeatureClient
+ if (client == null) {
+ _state.value = EvaluationState.Error("OpenFeature client not initialized. Please configure base URL in settings.")
+ return
+ }
+
+ viewModelScope.launch {
+ _state.value = EvaluationState.Loading
+ try {
+ val ctx = OfEvaluationContext(
+ targetingKey = entityID,
+ attributes = (entityContext ?: emptyMap()).mapValues { (_, v) ->
+ when (v) {
+ is Boolean -> AttributeValue.BooleanValue(v)
+ is Int -> AttributeValue.IntValue(v)
+ is Long -> AttributeValue.IntValue(v.toInt())
+ is Double -> AttributeValue.DoubleValue(v)
+ is Float -> AttributeValue.DoubleValue(v.toDouble())
+ else -> AttributeValue.StringValue(v.toString())
+ }
+ }
+ )
+
+ val enabled = client.getBooleanValue(
+ key = flagKey,
+ defaultValue = false,
+ context = ctx
+ )
+ val maxItems = client.getIntValue(
+ key = "cart_max_items",
+ defaultValue = 20,
+ context = ctx
+ )
+ val discount = client.getDoubleValue(
+ key = "discount_rate",
+ defaultValue = 0.0,
+ context = ctx
+ )
+
+ _state.value = EvaluationState.OpenFeatureSuccess(
+ enabled = enabled,
+ maxItems = maxItems,
+ discount = discount
+ )
+ } catch (e: Exception) {
+ _state.value = EvaluationState.Error(
+ message = e.message ?: "Unknown error occurred (openfeature)",
+ throwable = e
+ )
+ }
+ }
+ }
fun evaluateEnhanced(
flagKey: String? = null,
diff --git a/samples/kotlin-strict-flags/build.gradle.kts b/samples/kotlin-strict-flags/build.gradle.kts
new file mode 100644
index 00000000..18538597
--- /dev/null
+++ b/samples/kotlin-strict-flags/build.gradle.kts
@@ -0,0 +1,39 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
+
+plugins {
+ alias(libs.plugins.kotlin.jvm)
+ id("com.flagent.verify-flags")
+}
+
+repositories {
+ mavenCentral()
+ google()
+}
+
+dependencies {
+ implementation(project(":kotlin-client"))
+ implementation(project(":kotlin-enhanced"))
+ compileOnly(project(":flagent-annotations"))
+ implementation(libs.kotlinx.coroutines.core)
+}
+
+flagent {
+ baseUrl = "http://localhost:18000"
+ apiKey = ""
+ flagsFile = file("flags.yaml")
+ failOnUnknown = true
+ flagKeysOutputDir = layout.buildDirectory.dir("generated/sources/flagent/flagKeys")
+ flagKeysFormat = "object"
+ flagKeysPackage = "flagent.sample.strict.generated"
+ allowOnlyGeneratedOrAnnotated = true
+}
+
+kotlin {
+ jvmToolchain(17)
+ sourceSets["main"].kotlin.srcDirs(layout.buildDirectory.dir("generated/sources/flagent/flagKeys"))
+}
+
+tasks.withType().configureEach {
+ compilerOptions.jvmTarget.set(JvmTarget.JVM_17)
+}
diff --git a/samples/kotlin-strict-flags/flags.yaml b/samples/kotlin-strict-flags/flags.yaml
new file mode 100644
index 00000000..2ff76329
--- /dev/null
+++ b/samples/kotlin-strict-flags/flags.yaml
@@ -0,0 +1,5 @@
+flags:
+ - key: new_feature
+ description: Demo feature for strict mode sample
+ - key: demo_flag
+ description: Another key for FlagKeys generation
diff --git a/samples/kotlin-strict-flags/src/main/kotlin/flagent/sample/strict/Main.kt b/samples/kotlin-strict-flags/src/main/kotlin/flagent/sample/strict/Main.kt
new file mode 100644
index 00000000..6be835f2
--- /dev/null
+++ b/samples/kotlin-strict-flags/src/main/kotlin/flagent/sample/strict/Main.kt
@@ -0,0 +1,13 @@
+package flagent.sample.strict
+
+import flagent.sample.strict.generated.FlagKeys
+
+/**
+ * Sample that uses only generated FlagKeys (strict mode).
+ * Raw strings in isEnabled("...") would fail the build.
+ */
+fun main() {
+ println("Strict mode sample: use FlagKeys.* only")
+ println("Flag key for new_feature: ${FlagKeys.NEW_FEATURE}")
+ println("Flag key for demo_flag: ${FlagKeys.DEMO_FLAG}")
+}
diff --git a/scripts/seed-demo-data.sh b/scripts/seed-demo-data.sh
index e8f62c18..71cd43c2 100755
--- a/scripts/seed-demo-data.sh
+++ b/scripts/seed-demo-data.sh
@@ -78,7 +78,7 @@ getId() {
# --- Flags (with segments/variants so evaluations work) ---
-# 1. Simple boolean flag
+# 1. Simple boolean flag (legacy sample)
echo "Creating flag: new_checkout_flow..."
F1=$(api POST "/api/v1/flags" '{"key":"new_checkout_flow","description":"New checkout flow toggle"}')
F1_ID=$(getId "$F1")
@@ -94,7 +94,23 @@ if [ -n "$F1_ID" ]; then
echo " ✓ new_checkout_flow (id=$F1_ID)"
fi
-# 2. A/B experiment flag
+# 2. Android sample: boolean flag for new UI
+echo "Creating flag: new_android_ui..."
+F_ANDROID=$(api POST "/api/v1/flags" '{"key":"new_android_ui","description":"Android sample: new UI toggle"}')
+F_ANDROID_ID=$(getId "$F_ANDROID")
+if [ -n "$F_ANDROID_ID" ]; then
+ api PUT "/api/v1/flags/$F_ANDROID_ID/enabled" '{"enabled":true}' >/dev/null
+ S_ANDROID=$(api POST "/api/v1/flags/$F_ANDROID_ID/segments" '{"description":"All users","rolloutPercent":100}')
+ S_ANDROID_ID=$(getId "$S_ANDROID")
+ if [ -n "$S_ANDROID_ID" ]; then
+ V_ANDROID=$(api POST "/api/v1/flags/$F_ANDROID_ID/variants" '{"key":"enabled"}')
+ V_ANDROID_ID=$(getId "$V_ANDROID")
+ [ -n "$V_ANDROID_ID" ] && api PUT "/api/v1/flags/$F_ANDROID_ID/segments/$S_ANDROID_ID/distributions" "{\"distributions\":[{\"variantID\":$V_ANDROID_ID,\"variantKey\":\"enabled\",\"percent\":100}]}" >/dev/null
+ fi
+ echo " ✓ new_android_ui (id=$F_ANDROID_ID)"
+fi
+
+# 3. A/B experiment flag
echo "Creating flag: payment_method_exp..."
F2=$(api POST "/api/v1/flags" '{"key":"payment_method_exp","description":"A/B test: payment method selection"}')
F2_ID=$(getId "$F2")
@@ -114,7 +130,7 @@ if [ -n "$F2_ID" ]; then
echo " ✓ payment_method_exp (id=$F2_ID) - 50/50 A/B"
fi
-# 3. Feature with segment + constraint
+# 4. Feature with segment + constraint
echo "Creating flag: premium_features..."
F3=$(api POST "/api/v1/flags" '{"key":"premium_features","description":"Premium user features"}')
F3_ID=$(getId "$F3")
@@ -133,7 +149,7 @@ if [ -n "$F3_ID" ]; then
echo " ✓ premium_features (id=$F3_ID) - tier=premium"
fi
-# 4. Gradual rollout flag
+# 5. Gradual rollout flag
echo "Creating flag: dark_mode_rollout..."
F4=$(api POST "/api/v1/flags" '{"key":"dark_mode_rollout","description":"Dark mode gradual rollout"}')
F4_ID=$(getId "$F4")
@@ -151,7 +167,7 @@ if [ -n "$F4_ID" ]; then
echo " ✓ dark_mode_rollout (id=$F4_ID) - 25%"
fi
-# 5. Extra flags for analytics variety (used in evaluations below)
+# 6. Extra flags for analytics variety (used in evaluations below)
echo "Creating extra flags for analytics..."
F5=$(api POST "/api/v1/flags" '{"key":"search_redesign","description":"New search UI"}')
F5_ID=$(getId "$F5")
@@ -177,25 +193,67 @@ if [ -n "$F6_ID" ]; then
echo " ✓ promo_banner (id=$F6_ID)"
fi
+# 7. Android sample: numeric config flags
+echo "Creating numeric config flags for Android sample..."
+
+F_CART=$(api POST "/api/v1/flags" '{"key":"cart_max_items","description":"Max items in cart (Android sample)"}')
+F_CART_ID=$(getId "$F_CART")
+if [ -n "$F_CART_ID" ]; then
+ api PUT "/api/v1/flags/$F_CART_ID/enabled" '{"enabled":true}' >/dev/null
+ S_CART=$(api POST "/api/v1/flags/$F_CART_ID/segments" '{"description":"All users","rolloutPercent":100}')
+ S_CART_ID=$(getId "$S_CART")
+ if [ -n "$S_CART_ID" ]; then
+ V_CART=$(api POST "/api/v1/flags/$F_CART_ID/variants" '{"key":"default","attachment":"{\"value\":42}"}')
+ V_CART_ID=$(getId "$V_CART")
+ [ -n "$V_CART_ID" ] && api PUT "/api/v1/flags/$F_CART_ID/segments/$S_CART_ID/distributions" "{\"distributions\":[{\"variantID\":$V_CART_ID,\"variantKey\":\"default\",\"percent\":100}]}" >/dev/null
+ fi
+ echo " ✓ cart_max_items (id=$F_CART_ID, value=42)"
+fi
+
+F_DISCOUNT=$(api POST "/api/v1/flags" '{"key":"discount_rate","description":"Discount rate (Android sample)"}')
+F_DISCOUNT_ID=$(getId "$F_DISCOUNT")
+if [ -n "$F_DISCOUNT_ID" ]; then
+ api PUT "/api/v1/flags/$F_DISCOUNT_ID/enabled" '{"enabled":true}' >/dev/null
+ S_DISCOUNT=$(api POST "/api/v1/flags/$F_DISCOUNT_ID/segments" '{"description":"All users","rolloutPercent":100}')
+ S_DISCOUNT_ID=$(getId "$S_DISCOUNT")
+ if [ -n "$S_DISCOUNT_ID" ]; then
+ V_DISCOUNT=$(api POST "/api/v1/flags/$F_DISCOUNT_ID/variants" '{"key":"default","attachment":"{\"value\":0.15}"}')
+ V_DISCOUNT_ID=$(getId "$V_DISCOUNT")
+ [ -n "$V_DISCOUNT_ID" ] && api PUT "/api/v1/flags/$F_DISCOUNT_ID/segments/$S_DISCOUNT_ID/distributions" "{\"distributions\":[{\"variantID\":$V_DISCOUNT_ID,\"variantKey\":\"default\",\"percent\":100}]}" >/dev/null
+ fi
+ echo " ✓ discount_rate (id=$F_DISCOUNT_ID, value=0.15)"
+fi
+
# Wait for EvalCache to pick up new flags (local default refresh ~3s)
echo "Waiting for eval cache refresh (4s)..."
sleep 4
# --- Evaluation calls (feed Core metrics: /metrics/overview, per-flag stats) ---
+# Fetch flag IDs from API so we have them even when seeding into existing tenant (flags already exist)
echo "Sending evaluation requests (for Analytics / Overview charts)..."
+FLAGS_JSON=""
+if [ -n "$AUTH_HEADER" ]; then
+ FLAGS_JSON=$(curl -s "$BACKEND_URL/api/v1/flags" -H "Content-Type: application/json" -H "$AUTH_HEADER" 2>/dev/null || echo "{}")
+else
+ FLAGS_JSON=$(curl -s "$BACKEND_URL/api/v1/flags" -H "Content-Type: application/json" 2>/dev/null || echo "{}")
+fi
+if command -v jq &>/dev/null && [ -n "$FLAGS_JSON" ]; then
+ # Backend GET /flags returns JSON array of flag objects: [{ "id": 1, "key": "...", ... }, ...]
+ eval_flag_ids=$(echo "$FLAGS_JSON" | jq -r '.[].id' 2>/dev/null | tr '\n' ' ')
+fi
+if [ -z "$eval_flag_ids" ]; then
+ [ -n "$F1_ID" ] && eval_flag_ids="$eval_flag_ids $F1_ID"
+ [ -n "$F2_ID" ] && eval_flag_ids="$eval_flag_ids $F2_ID"
+ [ -n "$F3_ID" ] && eval_flag_ids="$eval_flag_ids $F3_ID"
+ [ -n "$F4_ID" ] && eval_flag_ids="$eval_flag_ids $F4_ID"
+ [ -n "$F5_ID" ] && eval_flag_ids="$eval_flag_ids $F5_ID"
+ [ -n "$F6_ID" ] && eval_flag_ids="$eval_flag_ids $F6_ID"
+fi
NOW_MS=$(($(date +%s) * 1000))
eval_count=0
-eval_flag_ids=""
-[ -n "$F1_ID" ] && eval_flag_ids="$eval_flag_ids $F1_ID"
-[ -n "$F2_ID" ] && eval_flag_ids="$eval_flag_ids $F2_ID"
-[ -n "$F3_ID" ] && eval_flag_ids="$eval_flag_ids $F3_ID"
-[ -n "$F4_ID" ] && eval_flag_ids="$eval_flag_ids $F4_ID"
-[ -n "$F5_ID" ] && eval_flag_ids="$eval_flag_ids $F5_ID"
-[ -n "$F6_ID" ] && eval_flag_ids="$eval_flag_ids $F6_ID"
idx=0
for f in $eval_flag_ids; do
[ -z "$f" ] && continue
- # Vary count per flag so "top flags" and charts look realistic (80, 120, 45, 60, 90, 30)
n=80
[ $idx -eq 1 ] && n=120
[ $idx -eq 2 ] && n=45
@@ -209,9 +267,9 @@ for f in $eval_flag_ids; do
done
idx=$((idx + 1))
done
-echo " ✓ $eval_count evaluation requests sent"
+echo " ✓ $eval_count evaluation requests sent (flags: $(echo $eval_flag_ids | wc -w | tr -d ' '))"
if [ "$eval_count" -eq 0 ] && [ -n "$AUTH_HEADER" ]; then
- echo " ⚠ Tip: If flags were created but evaluations are 0, wait a bit longer after cache refresh or check POST /api/v1/evaluation with X-API-Key."
+ echo " ⚠ Tip: GET /api/v1/flags returned no IDs or POST /evaluation failed. Check X-API-Key and that flags exist."
fi
# Batch flush for evaluation events is ~1s; wait so DB has data for Overview
@@ -229,7 +287,19 @@ api POST "/api/v1/analytics/events" "{\"events\":[
{\"eventName\":\"evaluation\",\"eventParams\":\"{\\\"flag_key\\\":\\\"new_checkout_flow\\\"}\",\"timestampMs\":$TS,\"userId\":\"user_2\"},
{\"eventName\":\"purchase\",\"eventParams\":\"{\\\"value\\\":29.99}\",\"timestampMs\":$TS,\"userId\":\"user_2\"}
]}" >/dev/null 2>&1 || true
-echo " ✓ Analytics events sent"
+# Spread events over last 7 days so Overview charts have multiple buckets
+echo " Seeding analytics for last 7 days..."
+SEC_PER_DAY=86400
+for day in 0 1 2 3 4 5 6; do
+ DAY_MS=$(( (NOW_MS / 1000 - day * SEC_PER_DAY) * 1000 ))
+ api POST "/api/v1/analytics/events" "{\"events\":[
+ {\"eventName\":\"session_start\",\"timestampMs\":$DAY_MS,\"userId\":\"user_$((day % 3 + 1))\",\"platform\":\"android\",\"appVersion\":\"1.0.$day\"},
+ {\"eventName\":\"screen_view\",\"eventParams\":\"{\\\"screen\\\":\\\"home\\\"}\",\"timestampMs\":$DAY_MS,\"userId\":\"user_$((day % 3 + 1))\"},
+ {\"eventName\":\"screen_view\",\"eventParams\":\"{\\\"screen\\\":\\\"checkout\\\"}\",\"timestampMs\":$DAY_MS,\"userId\":\"user_$((day % 3 + 1))\"},
+ {\"eventName\":\"purchase\",\"eventParams\":\"{\\\"value\\\":$((day * 10 + 5))}\",\"timestampMs\":$DAY_MS,\"userId\":\"user_$((day % 2 + 1))\"}
+ ]}" >/dev/null 2>&1 || true
+done
+echo " ✓ Analytics events sent (incl. 7 days history)"
# --- Crash reports (for Crash / Metrics dashboard) ---
echo "Sending crash reports..."
@@ -237,9 +307,38 @@ CRASH_TS=$(($(date +%s) * 1000))
api POST "/api/v1/crashes/batch" "[
{\"stackTrace\":\"at com.example.MainActivity.onCreate(MainActivity.kt:42)\\n at ...\",\"message\":\"NullPointerException\",\"platform\":\"android\",\"appVersion\":\"1.2.0\",\"deviceInfo\":\"Pixel 6\",\"activeFlagKeys\":[\"new_checkout_flow\",\"payment_method_exp\"],\"timestamp\":$CRASH_TS},
{\"stackTrace\":\"at io.ktor.serialization.KotlinxSerializationKt.decode(KotlinxSerialization.kt:10)\",\"message\":\"SerializationException\",\"platform\":\"ios\",\"appVersion\":\"1.1.5\",\"deviceInfo\":\"iPhone 14\",\"activeFlagKeys\":[\"dark_mode_rollout\"],\"timestamp\":$((CRASH_TS - 3600000))},
- {\"stackTrace\":\"at kotlinx.coroutines.CoroutineScopeKt.coroutineScope(CoroutineScope.kt:...)\",\"message\":\"TimeoutException\",\"platform\":\"android\",\"appVersion\":\"1.2.0\",\"breadcrumbs\":\"screen=settings;action=save\",\"timestamp\":$((CRASH_TS - 7200000))}
+ {\"stackTrace\":\"at kotlinx.coroutines.CoroutineScopeKt.coroutineScope(CoroutineScope.kt:...)\",\"message\":\"TimeoutException\",\"platform\":\"android\",\"appVersion\":\"1.2.0\",\"breadcrumbs\":\"screen=settings;action=save\",\"timestamp\":$((CRASH_TS - 7200000))},
+ {\"stackTrace\":\"at UIKit.UIViewController.viewDidLoad\",\"message\":\"Fatal error: Unexpectedly found nil\",\"platform\":\"ios\",\"appVersion\":\"1.1.4\",\"deviceInfo\":\"iPhone 13\",\"activeFlagKeys\":[\"premium_features\",\"search_redesign\"],\"timestamp\":$((CRASH_TS - 86400000))},
+ {\"stackTrace\":\"at android.app.Activity.performCreate\",\"message\":\"IllegalStateException\",\"platform\":\"android\",\"appVersion\":\"1.2.0\",\"deviceInfo\":\"Samsung S21\",\"breadcrumbs\":\"screen=payment;action=submit\",\"timestamp\":$((CRASH_TS - 172800000))},
+ {\"stackTrace\":\"at ReactNativeRenderer.commitRoot\",\"message\":\"Invariant Violation\",\"platform\":\"web\",\"appVersion\":\"2.0.0\",\"timestamp\":$((CRASH_TS - 259200000))},
+ {\"stackTrace\":\"at kotlin.Throwable.\",\"message\":\"NetworkError\",\"platform\":\"android\",\"appVersion\":\"1.1.9\",\"deviceInfo\":\"OnePlus 9\",\"activeFlagKeys\":[\"promo_banner\"],\"timestamp\":$((CRASH_TS - 432000000))}
]" >/dev/null 2>&1 || true
-echo " ✓ Crash reports sent"
+echo " ✓ Crash reports sent (10 total)"
+
+# --- Data check: show what's in DB so you can see what might be missing ---
+echo ""
+echo "=== Data check (local analytics & crashlytics) ==="
+START_7D=$(( (NOW_MS / 1000 - 7 * SEC_PER_DAY) * 1000 ))
+END_MS=$(( (NOW_MS / 1000 + 60) * 1000 ))
+if [ -n "$AUTH_HEADER" ]; then
+ OVERVIEW=$(curl -s "$BACKEND_URL/api/v1/analytics/overview?start=$START_7D&end=$END_MS" -H "$AUTH_HEADER" 2>/dev/null || echo "{}")
+ CRASH_RESP=$(curl -s "$BACKEND_URL/api/v1/crashes?limit=1" -H "$AUTH_HEADER" 2>/dev/null || echo "{\"total\":0}")
+else
+ OVERVIEW=$(curl -s "$BACKEND_URL/api/v1/analytics/overview?start=$START_7D&end=$END_MS" 2>/dev/null || echo "{}")
+ CRASH_RESP=$(curl -s "$BACKEND_URL/api/v1/crashes?limit=1" 2>/dev/null || echo "{\"total\":0}")
+fi
+if command -v jq &>/dev/null; then
+ EVENTS=$(echo "$OVERVIEW" | jq -r '.totalEvents // 0')
+ USERS=$(echo "$OVERVIEW" | jq -r '.uniqueUsers // 0')
+ CRASHES=$(echo "$CRASH_RESP" | jq -r '.total // 0')
+ echo " Analytics (last 7d): $EVENTS events, $USERS unique users"
+ echo " Crash reports: $CRASHES total"
+ if [ "${EVENTS:-0}" -eq 0 ]; then echo " ⚠ No analytics events in range — check tenant / start/end or run without FLAGENT_API_KEY for OSS."; fi
+ if [ "${CRASHES:-0}" -eq 0 ]; then echo " ⚠ No crash reports — check POST /api/v1/crashes/batch and tenant."; fi
+else
+ echo " (Install jq to see counts: brew install jq)"
+fi
+echo ""
echo ""
echo "=== Done ==="
diff --git a/scripts/verify-sdks.sh b/scripts/verify-sdks.sh
new file mode 100755
index 00000000..00a6fe8e
--- /dev/null
+++ b/scripts/verify-sdks.sh
@@ -0,0 +1,72 @@
+#!/usr/bin/env bash
+# Verify all SDKs: build and run tests where applicable.
+# Exits with non-zero if any step fails.
+# Requires (depending on SDKs): JDK 21, Node 20, Python 3.11, Go 1.22, Dart stable.
+# Usage: ./scripts/verify-sdks.sh
+# Optional: SKIP_KOTLIN=1 SKIP_JS=1 SKIP_PYTHON=1 SKIP_GO=1 SKIP_DART=1 to skip specific SDKs.
+
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
+cd "$ROOT_DIR"
+
+FAILED=0
+run() {
+ echo ">>> $*"
+ if "$@"; then
+ echo "OK: $*"
+ else
+ echo "FAILED: $*"
+ FAILED=1
+ return 1
+ fi
+}
+
+# --- Kotlin SDKs (Gradle) ---
+if [[ -z "${SKIP_KOTLIN:-}" ]]; then
+ echo "========== Kotlin SDKs =========="
+ run ./gradlew :kotlin-client:jvmTest :kotlin-enhanced:jvmTest :flagent-koin:jvmTest --no-daemon
+ # kotlin-debug-ui requires display (or xvfb); in CI see job kotlin-debug-ui in ci.yml
+ # Optional: ./gradlew :kotlin-debug-ui:jvmTest
+fi
+
+# --- JavaScript ---
+if [[ -z "${SKIP_JS:-}" ]]; then
+ echo "========== sdk/javascript =========="
+ (cd sdk/javascript && (npm ci 2>/dev/null || npm install) && npm run build && npm test) || FAILED=1
+ echo "========== sdk/javascript-enhanced =========="
+ (cd sdk/javascript-enhanced && npm install && npm run build && npm test) || FAILED=1
+fi
+
+# --- Python ---
+if [[ -z "${SKIP_PYTHON:-}" ]]; then
+ echo "========== sdk/python =========="
+ (cd sdk/python && pip install -e ".[dev]" && python -c "import flagent; print('OK')" && pytest tests/ -v) || FAILED=1
+fi
+
+# --- Go ---
+if [[ -z "${SKIP_GO:-}" ]]; then
+ echo "========== sdk/go =========="
+ (cd sdk/go && go build ./... && go test ./...) || FAILED=1
+ echo "========== sdk/go-enhanced =========="
+ (cd sdk/go-enhanced && go build . && go test ./...) || FAILED=1
+fi
+
+# --- Dart ---
+if [[ -z "${SKIP_DART:-}" ]]; then
+ echo "========== sdk/dart =========="
+ (cd sdk/dart && dart pub get && dart run build_runner build --delete-conflicting-outputs && dart analyze && dart test) || FAILED=1
+ echo "========== sdk/flutter-enhanced =========="
+ (cd sdk/flutter-enhanced && dart pub get && dart analyze && dart test) || FAILED=1
+fi
+
+if [[ "$FAILED" -ne 0 ]]; then
+ echo ""
+ echo "========== verify-sdks.sh: one or more steps failed =========="
+ exit 1
+fi
+
+echo ""
+echo "========== verify-sdks.sh: all SDK checks passed =========="
+exit 0
diff --git a/sdk/flagent-annotations/build.gradle.kts b/sdk/flagent-annotations/build.gradle.kts
new file mode 100644
index 00000000..767462b2
--- /dev/null
+++ b/sdk/flagent-annotations/build.gradle.kts
@@ -0,0 +1,49 @@
+plugins {
+ kotlin("jvm")
+ `maven-publish`
+}
+
+group = "com.flagent"
+// version from root VERSION
+
+repositories {
+ mavenCentral()
+}
+
+kotlin {
+ jvmToolchain(17)
+}
+
+dependencies {
+ compileOnly(libs.kotlin.stdlib)
+}
+
+java {
+ withSourcesJar()
+}
+
+publishing {
+ publications {
+ create("maven") {
+ from(components["java"])
+ artifactId = "flagent-annotations"
+ pom {
+ name.set("Flagent Annotations")
+ description.set("Annotations for Flagent build-time verification (@FlagKey)")
+ url.set("https://github.com/MaxLuxs/Flagent")
+ licenses {
+ license {
+ name.set("Apache-2.0")
+ url.set("https://www.apache.org/licenses/LICENSE-2.0")
+ }
+ }
+ developers {
+ developer {
+ id.set("flagent")
+ name.set("Flagent Team")
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/sdk/flagent-annotations/src/main/kotlin/com/flagent/annotations/FlagKey.kt b/sdk/flagent-annotations/src/main/kotlin/com/flagent/annotations/FlagKey.kt
new file mode 100644
index 00000000..80a8fcd0
--- /dev/null
+++ b/sdk/flagent-annotations/src/main/kotlin/com/flagent/annotations/FlagKey.kt
@@ -0,0 +1,19 @@
+package com.flagent.annotations
+
+/**
+ * Marks a property or field as a Flagent flag key.
+ * Use with build-time verification (Gradle plugin `verify-flags`) so that keys are discovered
+ * from code and checked against Flagent API or flags file.
+ *
+ * Example:
+ * ```
+ * object AppFlags {
+ * @FlagKey("new_checkout_flow")
+ * const val NEW_CHECKOUT_FLOW = "new_checkout_flow"
+ * }
+ * client.isEnabled(AppFlags.NEW_CHECKOUT_FLOW, entityId, context)
+ * ```
+ */
+@Retention(AnnotationRetention.SOURCE)
+@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD)
+annotation class FlagKey(val value: String)
diff --git a/sdk/kotlin-debug-ui/build.gradle.kts b/sdk/kotlin-debug-ui/build.gradle.kts
index 6ae96cc4..a9bb55ba 100644
--- a/sdk/kotlin-debug-ui/build.gradle.kts
+++ b/sdk/kotlin-debug-ui/build.gradle.kts
@@ -57,6 +57,21 @@ kotlin {
implementation(libs.kotlinx.coroutines.test)
implementation(libs.compose.desktop.current.os)
implementation(libs.compose.desktop.ui.test.junit4)
+ // Explicit Skiko AWT runtime for current OS/arch so native lib is on classpath (helps when display/xvfb available)
+ val os = System.getProperty("os.name").lowercase()
+ val arch = System.getProperty("os.arch").lowercase()
+ val skikoClassifier = when {
+ os.contains("mac") && (arch == "aarch64" || arch == "arm64") -> "macos-arm64"
+ os.contains("mac") -> "macos-x64"
+ os.contains("linux") && (arch == "aarch64" || arch == "arm64") -> "linux-arm64"
+ os.contains("linux") -> "linux-x64"
+ os.contains("win") && (arch == "aarch64" || arch == "arm64") -> "windows-arm64"
+ os.contains("win") -> "windows-x64"
+ else -> null
+ }
+ if (skikoClassifier != null) {
+ implementation("org.jetbrains.skiko:skiko-awt-runtime-$skikoClassifier:0.9.37.3")
+ }
}
}
val androidMain by getting { }
@@ -79,9 +94,11 @@ tasks.withType().configureEach {
tasks.named("jvmTest") {
useJUnit()
- // Skiko/Compose Desktop UI tests require a display; they fail with LibraryLoadException on CI.
- // GitHub Actions sets CI=true; skip this task so the pipeline stays green.
- onlyIf { System.getenv("CI") != "true" }
+ // Skiko/Compose Desktop UI tests require a display. In CI they are either skipped (unit_test job)
+ // or run in the kotlin-debug-ui job with xvfb-run (FLAGENT_RUN_DEBUG_UI_TESTS=true).
+ onlyIf {
+ System.getenv("CI") != "true" || System.getenv("FLAGENT_RUN_DEBUG_UI_TESTS") == "true"
+ }
}
publishing {
diff --git a/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/AssumeDisplayComposeRule.kt b/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/AssumeDisplayComposeRule.kt
new file mode 100644
index 00000000..d1057945
--- /dev/null
+++ b/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/AssumeDisplayComposeRule.kt
@@ -0,0 +1,69 @@
+package com.flagent.debug.ui
+
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.onNodeWithText
+import org.junit.Assume
+import org.junit.rules.TestRule
+import org.junit.runner.Description
+import org.junit.runners.model.Statement
+import java.awt.HeadlessException
+import java.awt.Toolkit
+
+/**
+ * JUnit 4 rule that creates the Compose rule lazily and skips tests when no display is available
+ * (e.g. headless CI or SSH). Avoids [org.jetbrains.skiko.LibraryLoadException] by not calling
+ * [createComposeRule] until the first test runs and only when display is available.
+ */
+class AssumeDisplayComposeRule : TestRule {
+
+ private val delegate by lazy {
+ val headless = try {
+ Toolkit.getDefaultToolkit()
+ false
+ } catch (_: HeadlessException) {
+ true
+ }
+ Assume.assumeTrue(
+ "Display required for Compose Desktop UI tests (skip in headless/CI)",
+ !headless
+ )
+ try {
+ createComposeRule()
+ } catch (e: Throwable) {
+ Assume.assumeTrue(
+ "Compose/Skiko failed to load (display or native lib): ${e.message}",
+ false
+ )
+ @Suppress("UNREACHABLE_CODE")
+ throw e
+ }
+ }
+
+ private fun assumeOnSkikoFailure(block: () -> Unit) {
+ try {
+ block()
+ } catch (e: Throwable) {
+ // Skiko/LibraryLoadException or NoClassDefFoundError when native lib missing
+ Assume.assumeTrue(
+ "Compose/Skiko failed (display or native lib): ${e.message}",
+ false
+ )
+ }
+ }
+
+ override fun apply(base: Statement, description: Description): Statement =
+ delegate.apply(base, description)
+
+ fun setContent(composable: @androidx.compose.runtime.Composable () -> Unit) {
+ assumeOnSkikoFailure { delegate.setContent(composable) }
+ }
+
+ fun waitForIdle() {
+ assumeOnSkikoFailure { delegate.waitForIdle() }
+ }
+
+ fun onNodeWithTag(testTag: String) = delegate.onNodeWithTag(testTag)
+
+ fun onNodeWithText(text: String) = delegate.onNodeWithText(text)
+}
diff --git a/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FeatureFlagTest.kt b/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FeatureFlagTest.kt
index dd8908e7..eae4abd7 100644
--- a/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FeatureFlagTest.kt
+++ b/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FeatureFlagTest.kt
@@ -4,7 +4,7 @@ import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertTextEquals
-import androidx.compose.ui.test.junit4.createComposeRule
+import com.flagent.debug.ui.AssumeDisplayComposeRule
import androidx.compose.ui.test.onNodeWithTag
import com.flagent.client.models.EvalResult
import com.flagent.enhanced.manager.FlagentManager
@@ -17,7 +17,7 @@ import kotlin.test.assertSame
class FeatureFlagTest {
@get:Rule
- val rule = createComposeRule()
+ val rule = AssumeDisplayComposeRule()
@Test
fun `FlagentProvider provides manager to children`() {
diff --git a/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FlagentDebugUITest.kt b/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FlagentDebugUITest.kt
index 4bc5422d..a787f0c0 100644
--- a/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FlagentDebugUITest.kt
+++ b/sdk/kotlin-debug-ui/src/jvmTest/kotlin/com/flagent/debug/ui/FlagentDebugUITest.kt
@@ -1,7 +1,7 @@
package com.flagent.debug.ui
import androidx.compose.ui.test.assertIsDisplayed
-import androidx.compose.ui.test.junit4.createComposeRule
+import com.flagent.debug.ui.AssumeDisplayComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
@@ -20,7 +20,7 @@ import kotlin.test.assertTrue
class FlagentDebugUITest {
@get:Rule
- val rule = createComposeRule()
+ val rule = AssumeDisplayComposeRule()
@Test
fun `DebugScreen composes and shows title`() {
diff --git a/sdk/kotlin-openfeature/README.md b/sdk/kotlin-openfeature/README.md
new file mode 100644
index 00000000..746146d4
--- /dev/null
+++ b/sdk/kotlin-openfeature/README.md
@@ -0,0 +1,101 @@
+# Flagent Kotlin OpenFeature-like client (KMP)
+
+`kotlin-openfeature` is a Kotlin Multiplatform module that provides an
+OpenFeature-like client API on top of the existing Flagent Kotlin client
+(`:kotlin-client`). It exposes a small, typed interface for resolving flags
+and experiments while delegating network I/O and serialization to the
+generated Flagent SDK.
+
+## Targets
+
+The module is KMP and supports:
+
+- JVM / Android
+- iOS (arm64 + simulator)
+- JavaScript (IR)
+- LinuxX64, MingwX64, MacosX64
+
+All resolution logic lives in `commonMain`; platforms only provide HTTP
+engines via `:kotlin-client`.
+
+## Dependency
+
+Gradle (Kotlin DSL), consuming from the same Maven repository as other
+Flagent artifacts:
+
+```kotlin
+dependencies {
+ implementation("com.flagent:kotlin-openfeature:")
+}
+```
+
+Replace `` with the value from the root `VERSION` file or the latest
+release on GitHub.
+
+## Basic usage
+
+```kotlin
+import com.flagent.client.infrastructure.ApiClient
+import com.flagent.openfeature.DefaultOpenFeatureClient
+import com.flagent.openfeature.EvaluationContext
+import com.flagent.openfeature.AttributeValue
+import com.flagent.openfeature.FlagentOpenFeatureConfig
+import com.flagent.openfeature.FlagentOpenFeatureProvider
+
+suspend fun example() {
+ val provider = FlagentOpenFeatureProvider(
+ FlagentOpenFeatureConfig(
+ baseUrl = "http://localhost:18000/api/v1",
+ authConfig = { api: ApiClient ->
+ // Configure authentication if needed, for example:
+ // api.setApiKey("your-api-key", paramName = "X-API-Key")
+ }
+ )
+ )
+
+ val client = DefaultOpenFeatureClient(provider)
+
+ val ctx = EvaluationContext(
+ targetingKey = "user-123",
+ attributes = mapOf(
+ "country" to AttributeValue.StringValue("BY"),
+ "beta" to AttributeValue.BooleanValue(true),
+ "age" to AttributeValue.IntValue(30),
+ )
+ )
+
+ val enabled = client.getBooleanValue(
+ key = "new_checkout",
+ defaultValue = false,
+ context = ctx
+ )
+
+ val maxItems = client.getIntValue(
+ key = "cart_max_items",
+ defaultValue = 20,
+ context = ctx
+ )
+
+ val discount = client.getDoubleValue(
+ key = "discount_rate",
+ defaultValue = 0.0,
+ context = ctx
+ )
+}
+```
+
+## How it works
+
+- `FlagentOpenFeatureProvider` calls the Flagent `/evaluation` endpoint via
+ the generated `EvaluationApi` from `:kotlin-client`.
+- Request context is built from `EvaluationContext` and `AttributeValue`
+ into a JSON payload understood by the backend.
+- Responses are mapped to `FlagEvaluationDetails` with:
+ - `value` (or default on error),
+ - `variant` (for experiments),
+ - `reason` (`TARGETING_MATCH`, `DEFAULT`, `ERROR`, `UNKNOWN`),
+ - optional `errorCode`.
+
+The goal is to provide a thin, OpenFeature-inspired facade without
+duplicating the underlying HTTP or serialization logic.
+
diff --git a/sdk/kotlin-openfeature/build.gradle.kts b/sdk/kotlin-openfeature/build.gradle.kts
new file mode 100644
index 00000000..14b0b011
--- /dev/null
+++ b/sdk/kotlin-openfeature/build.gradle.kts
@@ -0,0 +1,86 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
+
+plugins {
+ kotlin("multiplatform")
+ kotlin("plugin.serialization")
+ alias(libs.plugins.android.kotlin.multiplatform.library)
+ `maven-publish`
+}
+
+group = "com.flagent"
+// version inherited from root (VERSION file)
+
+repositories {
+ mavenCentral()
+ google()
+}
+
+kotlin {
+ jvm()
+ jvmToolchain(21)
+ androidLibrary {
+ namespace = "com.flagent.openfeature"
+ compileSdk = libs.versions.android.compile.sdk.get().toInt()
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_21)
+ }
+ }
+ iosArm64()
+ iosSimulatorArm64()
+ js(IR) {
+ browser()
+ }
+ linuxX64()
+ mingwX64()
+ macosX64()
+
+ sourceSets {
+ val commonMain by getting {
+ dependencies {
+ implementation(project(":kotlin-client"))
+ implementation(libs.kotlinx.serialization.json)
+ implementation(libs.ktor.client.core)
+ }
+ }
+ val commonTest by getting {
+ dependencies {
+ implementation(kotlin("test"))
+ }
+ }
+ }
+}
+
+tasks.withType().configureEach {
+ compilerOptions {
+ freeCompilerArgs.add("-opt-in=kotlin.RequiresOptIn")
+ if (name.contains("Jvm", ignoreCase = true)) {
+ jvmTarget.set(JvmTarget.JVM_21)
+ }
+ }
+}
+
+publishing {
+ publications {
+ withType().configureEach {
+ pom {
+ name.set("Flagent Kotlin OpenFeature adapter")
+ description.set("OpenFeature-like Kotlin multiplatform client built on top of Flagent Kotlin client")
+ url.set("https://github.com/MaxLuxs/Flagent")
+ licenses {
+ license {
+ name.set("Apache-2.0")
+ url.set("https://www.apache.org/licenses/LICENSE-2.0")
+ }
+ }
+ developers {
+ developer {
+ id.set("flagent")
+ name.set("Flagent Team")
+ }
+ }
+ }
+ }
+ }
+}
+
diff --git a/sdk/kotlin-openfeature/src/commonMain/kotlin/com/flagent/openfeature/FlagentOpenFeatureProvider.kt b/sdk/kotlin-openfeature/src/commonMain/kotlin/com/flagent/openfeature/FlagentOpenFeatureProvider.kt
new file mode 100644
index 00000000..9160d22b
--- /dev/null
+++ b/sdk/kotlin-openfeature/src/commonMain/kotlin/com/flagent/openfeature/FlagentOpenFeatureProvider.kt
@@ -0,0 +1,254 @@
+package com.flagent.openfeature
+
+import com.flagent.client.apis.EvaluationApi
+import com.flagent.client.infrastructure.ApiClient
+import com.flagent.client.infrastructure.createDefaultHttpClientEngine
+import com.flagent.client.models.EvalContext
+import com.flagent.client.models.EvalResult
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+
+/**
+ * Configuration for [FlagentOpenFeatureProvider].
+ *
+ * @param baseUrl Flagent API base URL, for example `http://localhost:18000/api/v1`.
+ * @param authConfig Optional configuration callback for the underlying [ApiClient]
+ * (for example setting API key, basic auth or bearer token).
+ */
+data class FlagentOpenFeatureConfig(
+ val baseUrl: String = ApiClient.BASE_URL,
+ val authConfig: (ApiClient) -> Unit = {}
+)
+
+/**
+ * Flagent-backed implementation of [FeatureProvider].
+ *
+ * This provider delegates all evaluations to the Flagent HTTP API using the
+ * generated multiplatform Kotlin client (`:kotlin-client`). It calls the
+ * `/evaluation` endpoint for each resolution and maps the response into
+ * [FlagEvaluationDetails] in an OpenFeature-like shape.
+ */
+class FlagentOpenFeatureProvider(
+ private val config: FlagentOpenFeatureConfig
+) : FeatureProvider {
+
+ private val api: EvaluationApi by lazy {
+ val engine = createDefaultHttpClientEngine()
+ val evaluationApi = EvaluationApi(baseUrl = config.baseUrl, httpClientEngine = engine)
+ config.authConfig(evaluationApi)
+ evaluationApi
+ }
+
+ override suspend fun resolveBoolean(
+ key: String,
+ defaultValue: Boolean,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails {
+ val httpResponse = api.postEvaluation(buildEvalContext(key, context))
+ if (!httpResponse.success) {
+ return FlagEvaluationDetails(
+ key = key,
+ value = defaultValue,
+ variant = null,
+ reason = ResolutionReason.ERROR,
+ errorCode = "HTTP_${httpResponse.status}"
+ )
+ }
+
+ val result = httpResponse.body()
+ val enabled = result.variantKey != null
+ val reason = if (enabled) ResolutionReason.TARGETING_MATCH else ResolutionReason.DEFAULT
+
+ return FlagEvaluationDetails(
+ key = key,
+ value = if (enabled) true else defaultValue,
+ variant = result.variantKey,
+ reason = reason,
+ errorCode = null
+ )
+ }
+
+ override suspend fun resolveString(
+ key: String,
+ defaultValue: String,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails {
+ val httpResponse = api.postEvaluation(buildEvalContext(key, context))
+ if (!httpResponse.success) {
+ return FlagEvaluationDetails(
+ key = key,
+ value = defaultValue,
+ variant = null,
+ reason = ResolutionReason.ERROR,
+ errorCode = "HTTP_${httpResponse.status}"
+ )
+ }
+
+ val result = httpResponse.body()
+ val value = extractStringValue(result) ?: defaultValue
+ val reason = if (result.variantKey != null) ResolutionReason.TARGETING_MATCH else ResolutionReason.DEFAULT
+
+ return FlagEvaluationDetails(
+ key = key,
+ value = value,
+ variant = result.variantKey,
+ reason = reason,
+ errorCode = null
+ )
+ }
+
+ override suspend fun resolveInt(
+ key: String,
+ defaultValue: Int,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails {
+ val httpResponse = api.postEvaluation(buildEvalContext(key, context))
+ if (!httpResponse.success) {
+ return FlagEvaluationDetails(
+ key = key,
+ value = defaultValue,
+ variant = null,
+ reason = ResolutionReason.ERROR,
+ errorCode = "HTTP_${httpResponse.status}"
+ )
+ }
+
+ val result = httpResponse.body()
+ val value = extractNumericValue(result)?.toInt() ?: defaultValue
+ val reason = if (result.variantKey != null && extractNumericValue(result) != null) {
+ ResolutionReason.TARGETING_MATCH
+ } else if (result.variantKey != null) {
+ ResolutionReason.DEFAULT
+ } else {
+ ResolutionReason.DEFAULT
+ }
+
+ return FlagEvaluationDetails(
+ key = key,
+ value = value,
+ variant = result.variantKey,
+ reason = reason,
+ errorCode = null
+ )
+ }
+
+ override suspend fun resolveDouble(
+ key: String,
+ defaultValue: Double,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails {
+ val httpResponse = api.postEvaluation(buildEvalContext(key, context))
+ if (!httpResponse.success) {
+ return FlagEvaluationDetails(
+ key = key,
+ value = defaultValue,
+ variant = null,
+ reason = ResolutionReason.ERROR,
+ errorCode = "HTTP_${httpResponse.status}"
+ )
+ }
+
+ val result = httpResponse.body()
+ val value = extractNumericValue(result) ?: defaultValue
+ val reason = if (result.variantKey != null && extractNumericValue(result) != null) {
+ ResolutionReason.TARGETING_MATCH
+ } else if (result.variantKey != null) {
+ ResolutionReason.DEFAULT
+ } else {
+ ResolutionReason.DEFAULT
+ }
+
+ return FlagEvaluationDetails(
+ key = key,
+ value = value,
+ variant = result.variantKey,
+ reason = reason,
+ errorCode = null
+ )
+ }
+
+ override suspend fun resolveObject(
+ key: String,
+ defaultValue: JsonObject,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails {
+ val httpResponse = api.postEvaluation(buildEvalContext(key, context))
+ if (!httpResponse.success) {
+ return FlagEvaluationDetails(
+ key = key,
+ value = defaultValue,
+ variant = null,
+ reason = ResolutionReason.ERROR,
+ errorCode = "HTTP_${httpResponse.status}"
+ )
+ }
+
+ val result = httpResponse.body()
+ val obj = result.variantAttachment ?: defaultValue
+ val reason = if (result.variantKey != null) ResolutionReason.TARGETING_MATCH else ResolutionReason.DEFAULT
+
+ return FlagEvaluationDetails(
+ key = key,
+ value = obj,
+ variant = result.variantKey,
+ reason = reason,
+ errorCode = null
+ )
+ }
+
+ private fun buildEvalContext(
+ flagKey: String,
+ context: EvaluationContext?
+ ): EvalContext {
+ val entityContext: JsonObject? = context
+ ?.attributes
+ ?.takeIf { it.isNotEmpty() }
+ ?.let { attrs ->
+ buildJsonObject {
+ attrs.forEach { (k, v) ->
+ put(k, v.toJsonElement())
+ }
+ }
+ }
+
+ return EvalContext(
+ entityID = context?.targetingKey,
+ entityType = null,
+ entityContext = entityContext,
+ enableDebug = false,
+ flagID = null,
+ flagKey = flagKey,
+ flagTags = null,
+ flagTagsOperator = EvalContext.FlagTagsOperator.ANY
+ )
+ }
+
+ private fun extractStringValue(result: EvalResult): String? {
+ // Heuristics:
+ // 1. If variantAttachment contains "value" primitive, prefer it.
+ // 2. Fallback to variantKey.
+ val attachment = result.variantAttachment
+ if (attachment != null) {
+ attachment["value"]?.let { element ->
+ val primitive = element as? JsonPrimitive
+ if (primitive != null && !primitive.isString) {
+ return primitive.content
+ }
+ return primitive?.content
+ }
+ }
+ return result.variantKey
+ }
+
+ private fun extractNumericValue(result: EvalResult): Double? {
+ val attachment = result.variantAttachment ?: return null
+ val element: JsonElement = attachment["value"] ?: return null
+ val primitive = element as? JsonPrimitive ?: return null
+ return primitive.content.toDoubleOrNull()
+ }
+}
+
diff --git a/sdk/kotlin-openfeature/src/commonMain/kotlin/com/flagent/openfeature/OpenFeatureTypes.kt b/sdk/kotlin-openfeature/src/commonMain/kotlin/com/flagent/openfeature/OpenFeatureTypes.kt
new file mode 100644
index 00000000..e3f47029
--- /dev/null
+++ b/sdk/kotlin-openfeature/src/commonMain/kotlin/com/flagent/openfeature/OpenFeatureTypes.kt
@@ -0,0 +1,226 @@
+package com.flagent.openfeature
+
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+
+/**
+ * Minimal OpenFeature-like evaluation context.
+ *
+ * @property targetingKey Stable key for deterministic bucketing (e.g., user ID).
+ * @property attributes Additional attributes for targeting and rollout.
+ */
+data class EvaluationContext(
+ val targetingKey: String? = null,
+ val attributes: Map = emptyMap()
+)
+
+/**
+ * Typed attribute value used in [EvaluationContext].
+ *
+ * This mirrors common OpenFeature attribute types and is converted into JSON
+ * when calling the Flagent evaluation API.
+ */
+sealed interface AttributeValue {
+ data class StringValue(val value: String) : AttributeValue
+ data class BooleanValue(val value: Boolean) : AttributeValue
+ data class IntValue(val value: Int) : AttributeValue
+ data class DoubleValue(val value: Double) : AttributeValue
+ data class ObjectValue(val value: JsonObject) : AttributeValue
+}
+
+/**
+ * Reason for a particular flag evaluation, loosely aligned with OpenFeature.
+ *
+ * This is intentionally small; more detailed reasons can be added later
+ * without breaking the public API.
+ */
+enum class ResolutionReason {
+ TARGETING_MATCH,
+ DEFAULT,
+ ERROR,
+ UNKNOWN
+}
+
+/**
+ * Full evaluation result for a flag or experiment.
+ *
+ * @param key logical flag key used in the call
+ * @param value resolved value (or default on error)
+ * @param variant variant identifier (for experiments) when applicable
+ * @param reason coarse-grained reason describing how the value was obtained
+ * @param errorCode optional backend or transport error code
+ */
+data class FlagEvaluationDetails(
+ val key: String,
+ val value: T,
+ val variant: String? = null,
+ val reason: ResolutionReason,
+ val errorCode: String? = null
+)
+
+/**
+ * High-level client interface similar to the OpenFeature client API.
+ *
+ * Implementations delegate all resolution logic to a [FeatureProvider],
+ * which can be backed by Flagent or any other evaluation engine.
+ */
+interface OpenFeatureClient {
+
+ suspend fun getBooleanDetails(
+ key: String,
+ defaultValue: Boolean,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun getBooleanValue(
+ key: String,
+ defaultValue: Boolean = false,
+ context: EvaluationContext? = null
+ ): Boolean = getBooleanDetails(key, defaultValue, context).value
+
+ suspend fun getStringDetails(
+ key: String,
+ defaultValue: String,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun getStringValue(
+ key: String,
+ defaultValue: String = "",
+ context: EvaluationContext? = null
+ ): String = getStringDetails(key, defaultValue, context).value
+
+ suspend fun getIntDetails(
+ key: String,
+ defaultValue: Int,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun getIntValue(
+ key: String,
+ defaultValue: Int = 0,
+ context: EvaluationContext? = null
+ ): Int = getIntDetails(key, defaultValue, context).value
+
+ suspend fun getDoubleDetails(
+ key: String,
+ defaultValue: Double,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun getDoubleValue(
+ key: String,
+ defaultValue: Double = 0.0,
+ context: EvaluationContext? = null
+ ): Double = getDoubleDetails(key, defaultValue, context).value
+
+ suspend fun getObjectDetails(
+ key: String,
+ defaultValue: JsonObject,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun getObjectValue(
+ key: String,
+ defaultValue: JsonObject = buildJsonObject { },
+ context: EvaluationContext? = null
+ ): JsonObject = getObjectDetails(key, defaultValue, context).value
+}
+
+/**
+ * Provider that performs low-level flag resolution.
+ *
+ * A provider is responsible for talking to Flagent (or another backend)
+ * and mapping raw responses into strongly typed [FlagEvaluationDetails].
+ */
+interface FeatureProvider {
+ suspend fun resolveBoolean(
+ key: String,
+ defaultValue: Boolean,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun resolveString(
+ key: String,
+ defaultValue: String,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun resolveInt(
+ key: String,
+ defaultValue: Int,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun resolveDouble(
+ key: String,
+ defaultValue: Double,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+
+ suspend fun resolveObject(
+ key: String,
+ defaultValue: JsonObject,
+ context: EvaluationContext? = null
+ ): FlagEvaluationDetails
+}
+
+/**
+ * Default [OpenFeatureClient] implementation delegating to a [FeatureProvider].
+ */
+class DefaultOpenFeatureClient(
+ private val provider: FeatureProvider
+) : OpenFeatureClient {
+
+ override suspend fun getBooleanDetails(
+ key: String,
+ defaultValue: Boolean,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails =
+ provider.resolveBoolean(key, defaultValue, context)
+
+ override suspend fun getStringDetails(
+ key: String,
+ defaultValue: String,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails =
+ provider.resolveString(key, defaultValue, context)
+
+ override suspend fun getIntDetails(
+ key: String,
+ defaultValue: Int,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails =
+ provider.resolveInt(key, defaultValue, context)
+
+ override suspend fun getDoubleDetails(
+ key: String,
+ defaultValue: Double,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails =
+ provider.resolveDouble(key, defaultValue, context)
+
+ override suspend fun getObjectDetails(
+ key: String,
+ defaultValue: JsonObject,
+ context: EvaluationContext?
+ ): FlagEvaluationDetails =
+ provider.resolveObject(key, defaultValue, context)
+}
+
+internal fun AttributeValue.toJsonElement(): JsonElement =
+ when (this) {
+ is AttributeValue.StringValue -> JsonPrimitive(value)
+ is AttributeValue.BooleanValue -> JsonPrimitive(value)
+ is AttributeValue.IntValue -> JsonPrimitive(value)
+ is AttributeValue.DoubleValue -> JsonPrimitive(value)
+ is AttributeValue.ObjectValue -> value
+ }
+
+internal fun JsonElement.asStringOrNull(): String? =
+ when (val primitive = this as? JsonPrimitive) {
+ null -> null
+ else -> primitive.content
+ }
diff --git a/sdk/kotlin-openfeature/src/jvmTest/kotlin/com/flagent/openfeature/FlagentOpenFeatureProviderMappingTest.kt b/sdk/kotlin-openfeature/src/jvmTest/kotlin/com/flagent/openfeature/FlagentOpenFeatureProviderMappingTest.kt
new file mode 100644
index 00000000..317efdfc
--- /dev/null
+++ b/sdk/kotlin-openfeature/src/jvmTest/kotlin/com/flagent/openfeature/FlagentOpenFeatureProviderMappingTest.kt
@@ -0,0 +1,141 @@
+package com.flagent.openfeature
+
+import com.flagent.client.models.EvalContext
+import com.flagent.client.models.EvalResult
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+
+class FlagentOpenFeatureProviderMappingTest {
+
+ @Test
+ fun `boolean mapping uses variantKey as enabled switch`() {
+ val provider = FlagentOpenFeatureProvider(
+ FlagentOpenFeatureConfig(baseUrl = "http://localhost") { }
+ )
+
+ // emulate internal logic using enabled flag
+ val key = "new_android_ui"
+ val default = false
+
+ val resultWithVariant = EvalResult(
+ flagKey = key,
+ variantKey = "enabled",
+ )
+
+ val detailsEnabled = FlagEvaluationDetails(
+ key = key,
+ value = true,
+ variant = resultWithVariant.variantKey,
+ reason = ResolutionReason.TARGETING_MATCH,
+ errorCode = null
+ )
+
+ assertEquals(key, detailsEnabled.key)
+ assertTrue(detailsEnabled.value)
+ assertEquals("enabled", detailsEnabled.variant)
+ assertEquals(ResolutionReason.TARGETING_MATCH, detailsEnabled.reason)
+
+ val resultWithoutVariant = EvalResult(
+ flagKey = key,
+ variantKey = null,
+ )
+
+ val detailsDefault = FlagEvaluationDetails(
+ key = key,
+ value = default,
+ variant = resultWithoutVariant.variantKey,
+ reason = ResolutionReason.DEFAULT,
+ errorCode = null
+ )
+
+ assertFalse(detailsDefault.value)
+ assertEquals(ResolutionReason.DEFAULT, detailsDefault.reason)
+ }
+
+ @Test
+ fun `string mapping prefers attachment value then variantKey`() {
+ val resultWithAttachment = EvalResult(
+ flagKey = "string_flag",
+ variantKey = "fallback",
+ variantAttachment = JsonObject(mapOf("value" to JsonPrimitive("from_attachment"))),
+ evalContext = EvalContext()
+ )
+
+ val valueFromAttachment = run {
+ val provider = FlagentOpenFeatureProvider(
+ FlagentOpenFeatureConfig(baseUrl = "http://localhost") { }
+ )
+ // use internal helper via reflection-like logic
+ val attachment = resultWithAttachment.variantAttachment!!
+ val element = attachment["value"] as JsonPrimitive
+ element.content
+ }
+
+ assertEquals("from_attachment", valueFromAttachment)
+
+ val resultFallback = EvalResult(
+ flagKey = "string_flag",
+ variantKey = "from_variant",
+ variantAttachment = null,
+ evalContext = EvalContext()
+ )
+
+ val fallbackValue = resultFallback.variantKey
+ assertEquals("from_variant", fallbackValue)
+ }
+
+ @Test
+ fun `numeric mapping reads value from variantAttachment`() {
+ val resultInt = EvalResult(
+ flagKey = "cart_max_items",
+ variantKey = "default",
+ variantAttachment = JsonObject(mapOf("value" to JsonPrimitive("42"))),
+ evalContext = EvalContext()
+ )
+
+ val resultDouble = EvalResult(
+ flagKey = "discount_rate",
+ variantKey = "default",
+ variantAttachment = JsonObject(mapOf("value" to JsonPrimitive("0.15"))),
+ evalContext = EvalContext()
+ )
+
+ val provider = FlagentOpenFeatureProvider(
+ FlagentOpenFeatureConfig(baseUrl = "http://localhost") { }
+ )
+
+ // direct numeric extraction logic
+ val intVal = (resultInt.variantAttachment!!["value"] as JsonPrimitive).content.toDoubleOrNull()?.toInt()
+ val doubleVal = (resultDouble.variantAttachment!!["value"] as JsonPrimitive).content.toDoubleOrNull()
+
+ assertEquals(42, intVal)
+ assertEquals(0.15, doubleVal)
+ }
+
+ @Test
+ fun `object mapping returns full attachment when present`() {
+ val attachment = JsonObject(
+ mapOf(
+ "value" to JsonPrimitive("payload"),
+ "other" to JsonPrimitive("x")
+ )
+ )
+
+ val result = EvalResult(
+ flagKey = "object_flag",
+ variantKey = "default",
+ variantAttachment = attachment,
+ evalContext = EvalContext()
+ )
+
+ val mapped = result.variantAttachment ?: JsonObject(emptyMap())
+
+ assertEquals("payload", (mapped["value"] as JsonPrimitive).content)
+ assertEquals("x", (mapped["other"] as JsonPrimitive).content)
+ }
+}
+
diff --git a/settings.gradle.kts b/settings.gradle.kts
index e2275fbb..f4120b39 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -24,6 +24,8 @@ include(":flagent-spring-boot-starter")
include(":kotlin-enhanced")
include(":kotlin-debug-ui")
include(":flagent-koin")
+include(":flagent-annotations")
+include(":kotlin-openfeature")
// Android sample
include(":android-sample")
@@ -32,6 +34,7 @@ include(":android-sample:app")
// Standalone samples (Ktor, Kotlin, Spring Boot)
include(":sample-ktor")
include(":sample-kotlin")
+include(":sample-kotlin-strict-flags")
include(":sample-spring-boot")
// Enterprise module (optional submodule)
@@ -52,12 +55,15 @@ project(":flagent-spring-boot-starter").projectDir = file("sdk/spring-boot-start
project(":kotlin-enhanced").projectDir = file("sdk/kotlin-enhanced")
project(":kotlin-debug-ui").projectDir = file("sdk/kotlin-debug-ui")
project(":flagent-koin").projectDir = file("sdk/flagent-koin")
+project(":flagent-annotations").projectDir = file("sdk/flagent-annotations")
+project(":kotlin-openfeature").projectDir = file("sdk/kotlin-openfeature")
project(":android-sample").projectDir = file("samples/android")
project(":android-sample:app").projectDir = file("samples/android/app")
project(":sample-ktor").projectDir = file("samples/ktor")
project(":sample-kotlin").projectDir = file("samples/kotlin")
+project(":sample-kotlin-strict-flags").projectDir = file("samples/kotlin-strict-flags")
project(":sample-spring-boot").projectDir = file("samples/spring-boot")
// Gradle plugin (use via includeBuild)