commit
Build the System app: a native client for the plural system site
Kotlin and Compose, talking to the Doughmination API the website uses (/v2/plural/*) and its live socket. Members with search and tag/identity filters, mental state, who's fronting, member pages with partners and crushes, the rotating relationship map, and metrics, all public. Sign-in uses the API's new app flow (one-time code + PKCE) and adds the admin and owner tools: switching, mental state, statuses, tags, pride, relationships, users, and force refresh. Adds an emulator smoke test that installs the signed APK, walks the tabs and screenshots each step.
diff --git a/.github/scripts/plural-smoke.sh b/.github/scripts/plural-smoke.sh
new file mode 100644
index 0000000..359deb5
--- /dev/null
+++ b/.github/scripts/plural-smoke.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# Installs the Plural APK on the running emulator, walks through the app the
+# way a person would, and saves a screenshot (plus the UI tree) of each step.
+# Fails if the APK won't install, the app won't launch, or it crashes.
+#
+# plural-smoke.sh <apk> <output dir>
+set -euo pipefail
+
+apk=$1
+out=$2
+pkg=gay.doughmination.plural
+mkdir -p "$out"
+
+ui() { adb exec-out uiautomator dump /dev/tty 2>/dev/null | sed 's/UI hierch*ary dumped to.*//' || true; }
+
+shot() {
+ sleep "${2:-2}"
+ adb exec-out screencap -p > "$out/$1.png"
+ ui > "$out/$1.xml"
+ echo "saved $1"
+}
+
+# Taps the middle of the first element whose text (or description) is exactly $1.
+tap_text() {
+ local bounds
+ bounds=$(ui | grep -oE "(text|content-desc)=\"$1\"[^>]*bounds=\"\[[0-9]+,[0-9]+\]\[[0-9]+,[0-9]+\]\"" | head -1 \
+ | grep -oE 'bounds="[^"]+"' | grep -oE '[0-9]+' | tr '\n' ' ' || true)
+ if [ -z "$bounds" ]; then
+ echo "::warning::Couldn't find \"$1\" on screen"
+ return 1
+ fi
+ set -- $bounds
+ adb shell input tap $(( ($1 + $3) / 2 )) $(( ($2 + $4) / 2 ))
+}
+
+alive() {
+ if ! adb shell pidof "$pkg" > /dev/null; then
+ echo "::error::$pkg isn't running after: $1"
+ adb logcat -d -b crash > "$out/crash.txt" || true
+ cat "$out/crash.txt"
+ exit 1
+ fi
+}
+
+adb logcat -c
+adb install -r "$apk"
+adb shell dumpsys package "$pkg" | grep -E "versionCode|versionName" | head -2
+
+adb shell am start -W -n "$pkg/.MainActivity"
+# The first load fetches members, fronters, the system and relationships.
+shot 01-members 10
+alive "launch"
+
+size=$(adb shell wm size | grep -oE '[0-9]+x[0-9]+' | tail -1)
+width=${size%x*}
+height=${size#*x}
+
+adb shell input swipe $(( width / 2 )) $(( height * 3 / 4 )) $(( width / 2 )) $(( height / 4 )) 400
+shot 02-members-scrolled 2
+alive "scrolling the members"
+
+# Open whichever member card is in the middle of the screen.
+adb shell input tap $(( width / 4 )) $(( height / 2 ))
+shot 03-member 4
+alive "opening a member"
+adb shell input keyevent 4
+
+tap_text "Filters" && shot 04-filters 2 && adb shell input keyevent 4 || true
+alive "the filters"
+
+tap_text "Relationships" && shot 05-relationships 5
+alive "relationships"
+adb shell input swipe $(( width / 2 )) $(( height * 3 / 4 )) $(( width / 2 )) $(( height / 4 )) 400
+shot 06-relationships-pairs 2
+
+tap_text "Metrics" && shot 07-metrics 8
+alive "metrics"
+adb shell input swipe $(( width / 2 )) $(( height * 3 / 4 )) $(( width / 2 )) $(( height / 4 )) 400
+shot 08-metrics-scrolled 2
+
+tap_text "Account" && shot 09-account 2
+alive "account"
+
+# Background and foreground again: the socket reconnects and data refreshes.
+adb shell input keyevent 3
+sleep 3
+adb shell am start -W -n "$pkg/.MainActivity"
+shot 10-resumed 5
+alive "coming back from the background"
+
+adb logcat -d > "$out/logcat.txt"
+if grep -q "FATAL EXCEPTION" "$out/logcat.txt"; then
+ echo "::error::The app crashed"
+ grep -A 30 "FATAL EXCEPTION" "$out/logcat.txt"
+ exit 1
+fi
+echo "Smoke test passed"
diff --git a/.github/workflows/plural-smoke.yml b/.github/workflows/plural-smoke.yml
new file mode 100644
index 0000000..dd1d70e
--- /dev/null
+++ b/.github/workflows/plural-smoke.yml
@@ -0,0 +1,70 @@
+# Builds Plural's signed release APK and runs it on an Android emulator:
+# install, launch, walk the tabs, screenshot each step, fail on a crash.
+# Screenshots and the APK are uploaded with the run.
+name: Plural smoke test
+
+on:
+ workflow_dispatch:
+ pull_request:
+ paths: ["plural/**", ".github/workflows/plural-smoke.yml", ".github/scripts/plural-smoke.sh"]
+
+jobs:
+ emulator:
+ runs-on: ubuntu-latest
+ timeout-minutes: 40
+ env:
+ HAS_SIGNING_KEY: ${{ secrets.PLURAL_KEYSTORE_BASE64 != '' }}
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: 17
+
+ - uses: gradle/actions/setup-gradle@v4
+
+ - name: Restore signing key
+ if: env.HAS_SIGNING_KEY == 'true'
+ env:
+ KEYSTORE_BASE64: ${{ secrets.PLURAL_KEYSTORE_BASE64 }}
+ STORE_PASSWORD: ${{ secrets.PLURAL_STORE_PASSWORD }}
+ KEY_ALIAS: ${{ secrets.PLURAL_KEY_ALIAS }}
+ KEY_PASSWORD: ${{ secrets.PLURAL_KEY_PASSWORD }}
+ run: |
+ echo "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.p12"
+ {
+ echo "SIGNING_STORE_FILE=$RUNNER_TEMP/release.p12"
+ echo "SIGNING_STORE_PASSWORD=$STORE_PASSWORD"
+ echo "SIGNING_KEY_ALIAS=$KEY_ALIAS"
+ echo "SIGNING_KEY_PASSWORD=$KEY_PASSWORD"
+ } >> "$GITHUB_ENV"
+
+ - name: Build
+ run: ./gradlew :plural:app:assembleRelease --console=plain
+
+ - name: Enable KVM
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
+ sudo udevadm control --reload-rules
+ sudo udevadm trigger --name-match=kvm
+
+ - name: Run on an emulator
+ uses: reactivecircus/android-emulator-runner@v2
+ with:
+ api-level: 34
+ target: google_apis
+ arch: x86_64
+ profile: pixel_6
+ disable-animations: true
+ emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
+ script: bash .github/scripts/plural-smoke.sh plural/app/build/outputs/apk/release/app-release.apk smoke
+
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: plural-smoke
+ path: |
+ smoke/
+ plural/app/build/outputs/apk/release/app-release.apk
+ if-no-files-found: warn
diff --git a/plural/app/build.gradle.kts b/plural/app/build.gradle.kts
index 99b16d5..7544765 100644
--- a/plural/app/build.gradle.kts
+++ b/plural/app/build.gradle.kts
@@ -2,8 +2,12 @@ plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
}
+// The Doughmination API the app talks to; -PapiUrl=https://... points a build elsewhere.
+val apiUrl = (findProperty("apiUrl") as String?) ?: "https://doughmination.uk/v2"
+
android {
namespace = "gay.doughmination.plural"
compileSdk = libs.versions.compileSdk.get().toInt()
@@ -17,6 +21,9 @@ android {
// CI sets these (see docs/releasing.md); local builds use the fallbacks.
versionCode = System.getenv("VERSION_CODE")?.toInt() ?: 1
versionName = System.getenv("VERSION_NAME") ?: "0.1.0"
+ buildConfigField("String", "API_URL", "\"$apiUrl\"")
+ // Member pages on the website, for sharing.
+ buildConfigField("String", "SITE_URL", "\"https://doughmination.co.uk\"")
}
// Same convention as Device Reporter: CI passes the key through SIGNING_*
@@ -42,6 +49,7 @@ android {
buildFeatures {
compose = true
+ buildConfig = true
}
compileOptions {
@@ -57,10 +65,19 @@ android {
dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.material3)
+ implementation(libs.androidx.compose.material.icons.extended)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.tooling.preview)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.activity.compose)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
+ implementation(libs.androidx.lifecycle.runtime.compose)
+ implementation(libs.androidx.lifecycle.process)
+ implementation(libs.androidx.browser)
+
+ implementation(libs.okhttp)
+ implementation(libs.kotlinx.serialization.json)
+ implementation(libs.kotlinx.coroutines.android)
}
diff --git a/plural/app/src/main/AndroidManifest.xml b/plural/app/src/main/AndroidManifest.xml
index 8dbf531..fdaf1ca 100644
--- a/plural/app/src/main/AndroidManifest.xml
+++ b/plural/app/src/main/AndroidManifest.xml
@@ -1,7 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.INTERNET" />
+
<application
+ android:name=".SystemApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
@@ -9,11 +12,21 @@
android:theme="@style/Theme.App">
<activity
android:name=".MainActivity"
- android:exported="true">
+ android:exported="true"
+ android:launchMode="singleTask"
+ android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
+
+ <!-- Where the API sends the browser tab after SSO sign-in. -->
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="gay.doughmination.plural" android:host="auth" />
+ </intent-filter>
</activity>
</application>
diff --git a/plural/app/src/main/java/gay/doughmination/plural/MainActivity.kt b/plural/app/src/main/java/gay/doughmination/plural/MainActivity.kt
index 1d362f7..bf01652 100644
--- a/plural/app/src/main/java/gay/doughmination/plural/MainActivity.kt
+++ b/plural/app/src/main/java/gay/doughmination/plural/MainActivity.kt
@@ -1,41 +1,59 @@
package gay.doughmination.plural
+import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.padding
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Scaffold
-import androidx.compose.material3.Text
-import androidx.compose.material3.darkColorScheme
-import androidx.compose.material3.lightColorScheme
-import androidx.compose.foundation.isSystemInDarkTheme
-import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.res.stringResource
-
-/** Placeholder screen until the app's real features are designed. */
+import androidx.activity.viewModels
+import gay.doughmination.plural.ui.AppRoot
+import gay.doughmination.plural.ui.SystemTheme
+import gay.doughmination.plural.ui.SystemViewModel
+
class MainActivity : ComponentActivity() {
+ private val vm: SystemViewModel by viewModels()
+
+ /** A sign-in tab is open; coming back without a code means it was closed. */
+ private var awaitingLogin = false
+
override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
enableEdgeToEdge()
- setContent {
- MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) {
- Placeholder()
- }
- }
+ super.onCreate(savedInstanceState)
+ setContent { SystemTheme { AppRoot(vm) } }
+ // A recreated activity (rotation) has already handled its launch intent.
+ if (savedInstanceState == null) handle(intent)
}
-}
-@Composable
-private fun Placeholder() {
- Scaffold { padding ->
- Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
- Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ handle(intent)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ awaitingLogin = vm.signingIn
+ }
+
+ override fun onResume() {
+ super.onResume()
+ // Back from the browser tab without a redirect: the tab was closed.
+ if (awaitingLogin && vm.signingIn && intent?.data == null) vm.loginAbandoned()
+ awaitingLogin = false
+ }
+
+ private fun handle(intent: Intent?) {
+ val data = intent?.data ?: return
+ // The end of sign-in: gay.doughmination.plural://auth?code=… (or ?error=…)
+ if (data.scheme == "gay.doughmination.plural" && data.host == "auth") {
+ awaitingLogin = false
+ val code = data.getQueryParameter("code")
+ val error = data.getQueryParameter("error")
+ when {
+ code != null -> vm.finishLogin(code)
+ error != null -> vm.loginFailed(error)
+ }
}
+ // Handled once: a rotation or a later resume mustn't replay it.
+ this.intent = Intent(this.intent).setData(null)
}
}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/SystemApp.kt b/plural/app/src/main/java/gay/doughmination/plural/SystemApp.kt
new file mode 100644
index 0000000..4483ca8
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/SystemApp.kt
@@ -0,0 +1,48 @@
+package gay.doughmination.plural
+
+import android.app.Application
+import androidx.lifecycle.DefaultLifecycleObserver
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.ProcessLifecycleOwner
+import gay.doughmination.plural.data.Api
+import gay.doughmination.plural.data.Auth
+import gay.doughmination.plural.data.Live
+import gay.doughmination.plural.data.TokenStore
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+/** Holds the app-wide pieces; there's one of each per process. */
+class SystemApp : Application() {
+ lateinit var tokens: TokenStore
+ private set
+ lateinit var api: Api
+ private set
+ lateinit var auth: Auth
+ private set
+ lateinit var live: Live
+ private set
+
+ private val _signedIn = MutableStateFlow(false)
+ val signedIn: StateFlow<Boolean> = _signedIn
+
+ override fun onCreate() {
+ super.onCreate()
+ tokens = TokenStore(this)
+ api = Api(BuildConfig.API_URL, tokens) { _signedIn.value = false }
+ auth = Auth(api, tokens)
+ live = Live(api, MainScope())
+ _signedIn.value = tokens.token != null
+
+ // Live updates are public, so the socket runs whenever the app is on
+ // screen, signed in or not, as on the website.
+ ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
+ override fun onStart(owner: LifecycleOwner) = live.start()
+ override fun onStop(owner: LifecycleOwner) = live.stop()
+ })
+ }
+
+ fun setSignedIn(value: Boolean) {
+ _signedIn.value = value
+ }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Api.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Api.kt
new file mode 100644
index 0000000..9487b84
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Api.kt
@@ -0,0 +1,229 @@
+package gay.doughmination.plural.data
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.ExperimentalSerializationApi
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+import okhttp3.HttpUrl
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+/** The API said no, or couldn't be reached; `message` is fit to show. */
+class ApiException(message: String, val status: Int) : Exception(message)
+
+/**
+ * The Doughmination API's plural system routes (/v2/plural/*). Reads are
+ * public, exactly as the website makes them; writes carry the signed-in
+ * user's token. Bodies come back bare, and errors as { detail }.
+ */
+class Api(val baseUrl: String, private val tokens: TokenStore, private val onSignedOut: () -> Unit) {
+ val http: OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .build()
+
+ @OptIn(ExperimentalSerializationApi::class)
+ val json = Json {
+ ignoreUnknownKeys = true
+ coerceInputValues = true
+ explicitNulls = false
+ encodeDefaults = true
+ }
+
+ /** The realtime socket: https://…/v2 -> wss://…/v2/ws, as react-api derives it. */
+ val socketUrl: String get() = baseUrl.replaceFirst("http", "ws") + "/ws"
+
+ private val jsonType = "application/json".toMediaType()
+
+ /** A URL under /plural, each segment encoded (member names can hold anything). */
+ private fun plural(vararg segments: String): HttpUrl.Builder =
+ "$baseUrl/plural".toHttpUrl().newBuilder().apply { segments.forEach { addPathSegment(it) } }
+
+ private suspend fun send(request: Request, signedIn: Boolean): String = withContext(Dispatchers.IO) {
+ val builder = request.newBuilder()
+ if (signedIn) {
+ val token = tokens.token ?: throw ApiException("Please sign in again.", 401)
+ builder.header("Authorization", "Bearer $token")
+ }
+ val response = try {
+ http.newCall(builder.build()).execute()
+ } catch (e: IOException) {
+ throw ApiException("Couldn't reach the server. Check your connection.", 0)
+ }
+ response.use { res ->
+ val body = res.body?.string().orEmpty()
+ if (signedIn && res.code == 401) {
+ tokens.token = null
+ onSignedOut()
+ throw ApiException(errorMessage(body) ?: "Your session ended. Please sign in again.", 401)
+ }
+ if (!res.isSuccessful) throw ApiException(errorMessage(body) ?: "Request failed (${res.code})", res.code)
+ body
+ }
+ }
+
+ /** The API's own message: { detail } (a string, or zod issues), { error: { message } } or { message }. */
+ private fun errorMessage(body: String): String? {
+ val obj = runCatching { json.parseToJsonElement(body).jsonObject }.getOrNull() ?: return null
+ fun text(element: JsonElement?): String? = when (element) {
+ is JsonPrimitive -> element.contentOrNull
+ is JsonArray -> element.mapNotNull { (it as? JsonObject)?.get("message")?.let(::text) }
+ .joinToString("; ").ifBlank { null }
+ is JsonObject -> text(element["message"])
+ else -> null
+ }
+ return text(obj["detail"]) ?: text(obj["error"]) ?: text(obj["message"])
+ }
+
+ private suspend inline fun <reified T> get(url: HttpUrl, signedIn: Boolean = false): T =
+ json.decodeFromString(send(Request.Builder().url(url).build(), signedIn))
+
+ private suspend inline fun <reified B> write(method: String, url: HttpUrl, body: B): String =
+ send(Request.Builder().url(url).method(method, json.encodeToString(body).toRequestBody(jsonType)).build(), true)
+
+ private suspend fun delete(url: HttpUrl): String = send(Request.Builder().url(url).delete().build(), true)
+
+ // ---- Public reads ---------------------------------------------------------
+
+ suspend fun members(): List<Member> = get(plural("members").build())
+ suspend fun member(identifier: String): Member = get(plural("member", identifier).build())
+ suspend fun memberStatus(identifier: String): MemberStatus? =
+ get<MemberStatusResponse>(plural("members", identifier, "status").build()).status
+ suspend fun fronters(): Fronters = get(plural("fronters").build())
+ suspend fun system(): PluralSystem = get(plural("system").build())
+ suspend fun mentalState(): MentalState = get(plural("mental-state").build())
+ suspend fun relationships(): List<Relationship> =
+ get<RelationshipsResponse>(plural("relationships").build()).relationships
+ suspend fun frontingMetrics(days: Int = 30): FrontingMetrics =
+ get(plural("metrics", "fronting-time").addQueryParameter("days", "$days").build())
+ suspend fun switchMetrics(days: Int = 30): SwitchMetrics =
+ get(plural("metrics", "switch-frequency").addQueryParameter("days", "$days").build())
+
+ // ---- Sign-in ----------------------------------------------------------------
+
+ /** Where a native sign-in starts (see the API's routes/auth.ts). */
+ fun appLoginUrl(challenge: String): String =
+ plural("auth", "sso", "login").addQueryParameter("app", challenge).build().toString()
+
+ @Serializable private data class CodeSwap(val code: String, val verifier: String)
+ @Serializable private data class AccessToken(val access_token: String)
+
+ /** Swaps the one-time code from the sign-in redirect, plus our PKCE verifier, for the token. */
+ suspend fun exchangeCode(code: String, verifier: String): String {
+ val request = Request.Builder().url(plural("auth", "app", "token").build())
+ .post(json.encodeToString(CodeSwap(code, verifier)).toRequestBody(jsonType)).build()
+ return json.decodeFromString<AccessToken>(send(request, false)).access_token
+ }
+
+ /** Ends the session on the API too. Best effort: signing out here stands either way. */
+ suspend fun logout(token: String) {
+ runCatching {
+ withContext(Dispatchers.IO) {
+ http.newCall(
+ Request.Builder().url(plural("auth", "logout").build())
+ .header("Authorization", "Bearer $token")
+ .post("{}".toRequestBody(jsonType)).build(),
+ ).execute().close()
+ }
+ }
+ }
+
+ suspend fun userInfo(): User = get(plural("user_info").build(), signedIn = true)
+
+ // ---- Admin writes (the website's /admin pages) --------------------------------
+
+ @Serializable private data class MemberIds(val member_ids: List<String>)
+ @Serializable private data class MentalInput(val level: String, val notes: String?)
+ @Serializable private data class StatusInput(val text: String, val emoji: String?)
+ @Serializable private data class TagInput(val tag: String)
+ @Serializable private data class PrideInput(val identity: String)
+ @Serializable private data class RelationshipInput(
+ val memberA: String,
+ val memberB: String,
+ val type: String,
+ val since: String?,
+ )
+
+ suspend fun multiSwitch(memberIds: List<String>) { write("POST", plural("multi_switch").build(), MemberIds(memberIds)) }
+ suspend fun setMentalState(level: String, notes: String?) {
+ write("POST", plural("mental-state").build(), MentalInput(level, notes))
+ }
+ suspend fun setStatus(member: String, text: String, emoji: String?) {
+ write("POST", plural("members", member, "status").build(), StatusInput(text, emoji))
+ }
+ suspend fun clearStatus(member: String) { delete(plural("members", member, "status").build()) }
+ suspend fun addTag(member: String, tag: String) { write("POST", plural("member-tags", member, "add").build(), TagInput(tag)) }
+ suspend fun removeTag(member: String, tag: String) { delete(plural("member-tags", member, tag).build()) }
+ suspend fun addPride(member: String, identity: String) {
+ write("POST", plural("member-pride", member, "add").build(), PrideInput(identity))
+ }
+ suspend fun removePride(member: String, identity: String) { delete(plural("member-pride", member, identity).build()) }
+ suspend fun addRelationship(memberA: String, memberB: String, type: String, since: String?) {
+ write("POST", plural("relationships").build(), RelationshipInput(memberA, memberB, type, since))
+ }
+ suspend fun removeRelationship(id: String) { delete(plural("relationships", id).build()) }
+ suspend fun forceRefresh() { write("POST", plural("admin", "refresh").build(), JsonObject(emptyMap())) }
+
+ // ---- Users (profile, and the owner's user management) ---------------------------
+
+ /**
+ * A user update as the website sends it: blank text clears a field with an
+ * explicit null, and fields left out (email, unless it changed; the role
+ * switches, except for admins) are untouched.
+ */
+ class UserUpdate(
+ val displayName: String?,
+ val avatarUrl: String?,
+ val email: Optional<String?> = Optional.Unset,
+ val isAdmin: Boolean? = null,
+ val isPet: Boolean? = null,
+ ) {
+ fun toJson(): JsonObject = buildJsonObject {
+ put("display_name", displayName)
+ put("avatar_url", avatarUrl)
+ if (email is Optional.Set) put("email", email.value)
+ isAdmin?.let { put("is_admin", it) }
+ isPet?.let { put("is_pet", it) }
+ }
+ }
+
+ /** A field that is either left out of a request or sent, possibly as null. */
+ sealed interface Optional<out T> {
+ data object Unset : Optional<Nothing>
+ data class Set<T>(val value: T) : Optional<T>
+ }
+
+ @Serializable
+ data class UserCreate(
+ val username: String,
+ val display_name: String?,
+ val email: String?,
+ val is_admin: Boolean,
+ val is_pet: Boolean,
+ )
+
+ suspend fun users(): List<User> = get(plural("users").build(), signedIn = true)
+ suspend fun updateUser(id: String, update: UserUpdate): User =
+ json.decodeFromString(write("PUT", plural("users", id).build(), update.toJson()))
+ suspend fun createUser(input: UserCreate) { write("POST", plural("users").build(), input) }
+ suspend fun deleteUser(id: String) { delete(plural("users", id).build()) }
+
+ /** Reads a socket event's type, or null when it isn't one. */
+ fun eventType(text: String): String? =
+ runCatching { json.parseToJsonElement(text).jsonObject["type"]?.jsonPrimitive?.contentOrNull }.getOrNull()
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Auth.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Auth.kt
new file mode 100644
index 0000000..5c5d4ae
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Auth.kt
@@ -0,0 +1,47 @@
+package gay.doughmination.plural.data
+
+import android.content.Context
+import android.net.Uri
+import android.util.Base64
+import androidx.browser.customtabs.CustomTabsIntent
+import java.security.MessageDigest
+import java.security.SecureRandom
+
+/**
+ * Sign-in goes through the API's own SSO flow in a browser tab (a real one,
+ * so passkeys work), the same way Inbox does it:
+ *
+ * 1. open /v2/plural/auth/sso/login?app=<challenge>, keeping the PKCE verifier here;
+ * 2. once the SSO is happy, the API redirects to
+ * gay.doughmination.plural://auth?code=<one-time code> (never the token);
+ * 3. MainActivity gets that, and [finish] swaps code + verifier for the token.
+ *
+ * Only this app holds the verifier, so another app that grabs the redirect
+ * can't use the code, and the code dies after one use or a minute.
+ */
+class Auth(private val api: Api, private val tokens: TokenStore) {
+ fun start(context: Context) {
+ val verifier = b64url(ByteArray(32).also { SecureRandom().nextBytes(it) })
+ val challenge = b64url(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray()))
+ tokens.pendingVerifier = verifier
+ CustomTabsIntent.Builder()
+ .setShowTitle(true)
+ .build()
+ .launchUrl(context, Uri.parse(api.appLoginUrl(challenge)))
+ }
+
+ suspend fun finish(code: String) {
+ val verifier = tokens.pendingVerifier ?: throw ApiException("That sign-in has expired. Try again.", 400)
+ tokens.pendingVerifier = null
+ tokens.token = api.exchangeCode(code, verifier)
+ }
+
+ suspend fun signOut() {
+ val token = tokens.token
+ tokens.token = null
+ if (token != null) api.logout(token)
+ }
+
+ private fun b64url(bytes: ByteArray): String =
+ Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Colour.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Colour.kt
new file mode 100644
index 0000000..1a96af5
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Colour.kt
@@ -0,0 +1,94 @@
+package gay.doughmination.plural.data
+
+import androidx.compose.ui.graphics.Color
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.roundToInt
+
+// Member colours, as system/src/lib/colour.ts handles them: PluralKit stores
+// hex without the "#", and a name drawn in a very dark colour gets lifted
+// until it reads on the dark theme, without washing out to white.
+
+/** A member's colour, or null when they have none (or it isn't hex). */
+fun memberColour(hex: String?): Color? {
+ val rgb = hexToRgb(hex ?: return null) ?: return null
+ return Color(rgb[0], rgb[1], rgb[2])
+}
+
+/** The member's colour, lifted if needed so it reads on the dark backgrounds. */
+fun readableOnDark(hex: String?, fallback: Color): Color {
+ val rgb = hexToRgb(hex ?: return fallback) ?: return fallback
+ if (luminance(rgb) >= MIN_LUMINANCE) return Color(rgb[0], rgb[1], rgb[2])
+
+ val (h, s, startL) = rgbToHsl(rgb)
+ var l = startL
+ var out = rgb
+ // Walk lightness up until it clears the floor, capped well short of white.
+ while (l < 0.85 && luminance(out) < MIN_LUMINANCE) {
+ l = min(0.85, l + 0.04)
+ out = hslToRgb(h, s, l)
+ }
+ return Color(out[0], out[1], out[2])
+}
+
+private const val MIN_LUMINANCE = 0.18
+
+private fun hexToRgb(raw: String): IntArray? {
+ var hex = raw.trim().removePrefix("#")
+ if (hex.length == 3) hex = hex.map { "$it$it" }.joinToString("")
+ if (hex.length != 6 || hex.any { it.digitToIntOrNull(16) == null }) return null
+ return intArrayOf(hex.substring(0, 2).toInt(16), hex.substring(2, 4).toInt(16), hex.substring(4, 6).toInt(16))
+}
+
+/** WCAG relative luminance, 0 (black) to 1 (white). */
+private fun luminance(rgb: IntArray): Double {
+ fun channel(v: Int): Double {
+ val c = v / 255.0
+ return if (c <= 0.03928) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4)
+ }
+ return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2])
+}
+
+private fun rgbToHsl(rgb: IntArray): Triple<Double, Double, Double> {
+ val r = rgb[0] / 255.0
+ val g = rgb[1] / 255.0
+ val b = rgb[2] / 255.0
+ val mx = max(r, max(g, b))
+ val mn = min(r, min(g, b))
+ val l = (mx + mn) / 2
+ if (mx == mn) return Triple(0.0, 0.0, l)
+ val d = mx - mn
+ val s = if (l > 0.5) d / (2 - mx - mn) else d / (mx + mn)
+ val h = when (mx) {
+ r -> ((g - b) / d + if (g < b) 6 else 0) / 6
+ g -> ((b - r) / d + 2) / 6
+ else -> ((r - g) / d + 4) / 6
+ }
+ return Triple(h, s, l)
+}
+
+private fun hslToRgb(h: Double, s: Double, l: Double): IntArray {
+ if (s == 0.0) {
+ val v = (l * 255).roundToInt()
+ return intArrayOf(v, v, v)
+ }
+ fun hue(p: Double, q: Double, t0: Double): Double {
+ var t = t0
+ if (t < 0) t += 1
+ if (t > 1) t -= 1
+ return when {
+ t < 1.0 / 6 -> p + (q - p) * 6 * t
+ t < 1.0 / 2 -> q
+ t < 2.0 / 3 -> p + (q - p) * (2.0 / 3 - t) * 6
+ else -> p
+ }
+ }
+ val q = if (l < 0.5) l * (1 + s) else l + s - l * s
+ val p = 2 * l - q
+ return intArrayOf(
+ (hue(p, q, h + 1.0 / 3) * 255).roundToInt(),
+ (hue(p, q, h) * 255).roundToInt(),
+ (hue(p, q, h - 1.0 / 3) * 255).roundToInt(),
+ )
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Graph.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Graph.kt
new file mode 100644
index 0000000..77b4a79
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Graph.kt
@@ -0,0 +1,94 @@
+package gay.doughmination.plural.data
+
+import kotlin.math.PI
+import kotlin.math.cos
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+// The relationship map's 3D force layout, ported from system/src/lib/graph.ts
+// so the app's map settles into the same shape as the website's.
+// Deterministic: no randomness, so it looks the same every time.
+
+data class Point3(val x: Double, val y: Double, val z: Double)
+
+/** Where a point lands on screen: depth 0 is the back of the scene, 1 the front. */
+data class Projected(val x: Double, val y: Double, val depth: Double, val scale: Double)
+
+private const val ITERATIONS = 400
+private const val REST_LENGTH = 120.0
+private const val SPRING = 0.04
+private const val REPULSION = 60000.0
+private const val GRAVITY = 0.06
+private const val START_RADIUS = 220.0
+private const val CAMERA = 900.0
+
+/** Starting points spread evenly over a sphere (a Fibonacci lattice). */
+private fun sphere(count: Int): List<DoubleArray> {
+ val golden = PI * (3 - sqrt(5.0))
+ return List(count) { index ->
+ val y = if (count == 1) 0.0 else 1 - (index.toDouble() / (count - 1)) * 2
+ val ring = sqrt(1 - y * y)
+ val angle = golden * index
+ doubleArrayOf(cos(angle) * ring * START_RADIUS, y * START_RADIUS, sin(angle) * ring * START_RADIUS)
+ }
+}
+
+/**
+ * Lays out `count` nodes joined by `links`: they push apart, links pull like
+ * springs, a little gravity keeps them together. Then centred and scaled so
+ * the furthest node sits on `radius`.
+ */
+fun layout(count: Int, links: List<Pair<Int, Int>>, radius: Double): List<Point3> {
+ if (count == 0) return emptyList()
+ val points = sphere(count)
+
+ for (step in 0 until ITERATIONS) {
+ val cooling = 1 - step.toDouble() / ITERATIONS
+ val force = List(count) { DoubleArray(3) }
+
+ for (a in 0 until count) {
+ for (b in a + 1 until count) {
+ val dx = points[a][0] - points[b][0]
+ val dy = points[a][1] - points[b][1]
+ val dz = points[a][2] - points[b][2]
+ val distanceSq = max(dx * dx + dy * dy + dz * dz, 1.0)
+ val push = REPULSION / distanceSq / sqrt(distanceSq)
+ force[a][0] += dx * push; force[a][1] += dy * push; force[a][2] += dz * push
+ force[b][0] -= dx * push; force[b][1] -= dy * push; force[b][2] -= dz * push
+ }
+ }
+
+ for ((a, b) in links) {
+ val dx = points[b][0] - points[a][0]
+ val dy = points[b][1] - points[a][1]
+ val dz = points[b][2] - points[a][2]
+ val distance = max(sqrt(dx * dx + dy * dy + dz * dz), 1.0)
+ val pull = SPRING * (distance - REST_LENGTH) / distance
+ force[a][0] += dx * pull; force[a][1] += dy * pull; force[a][2] += dz * pull
+ force[b][0] -= dx * pull; force[b][1] -= dy * pull; force[b][2] -= dz * pull
+ }
+
+ for (i in 0 until count) {
+ for (axis in 0..2) {
+ points[i][axis] += (force[i][axis] - points[i][axis] * GRAVITY) * cooling
+ }
+ }
+ }
+
+ val centre = DoubleArray(3) { axis -> points.sumOf { it[axis] } / count }
+ val furthest = max(1.0, points.maxOf { hypot(hypot(it[0] - centre[0], it[1] - centre[1]), it[2] - centre[2]) })
+ val fit = radius / furthest
+ return points.map { Point3((it[0] - centre[0]) * fit, (it[1] - centre[1]) * fit, (it[2] - centre[2]) * fit) }
+}
+
+/** Rotates by yaw (round the vertical axis) then pitch, and projects with perspective. */
+fun project(point: Point3, yaw: Double, pitch: Double, radius: Double): Projected {
+ val x1 = point.x * cos(yaw) - point.z * sin(yaw)
+ val z1 = point.x * sin(yaw) + point.z * cos(yaw)
+ val y2 = point.y * cos(pitch) - z1 * sin(pitch)
+ val z2 = point.y * sin(pitch) + z1 * cos(pitch)
+ val scale = CAMERA / (CAMERA + z2)
+ return Projected(x1 * scale, y2 * scale, 1 - (z2 + radius) / (2 * radius), scale)
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Live.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Live.kt
new file mode 100644
index 0000000..97e139a
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Live.kt
@@ -0,0 +1,132 @@
+package gay.doughmination.plural.data
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.launch
+import okhttp3.Request
+import okhttp3.Response
+import okhttp3.WebSocket
+import okhttp3.WebSocketListener
+import kotlin.random.Random
+
+/**
+ * The API's realtime socket (/v2/ws), the website's live.svelte.ts in Kotlin:
+ * fronter and mental-state changes, and an admin's "refresh everyone". Open
+ * only while the app is on screen. Pings every 30s and gives up on a socket
+ * that doesn't answer within 10s; reconnects with jittered exponential backoff.
+ */
+class Live(private val api: Api, private val scope: CoroutineScope) {
+ enum class Status { Connecting, Open, Reconnecting, Closed }
+
+ enum class Event { FrontersChanged, MentalStateChanged, ForceRefresh, Reconnected }
+
+ private val _status = MutableStateFlow(Status.Closed)
+ val status: StateFlow<Status> = _status
+
+ private val _events = MutableSharedFlow<Event>(extraBufferCapacity = 16)
+ val events: SharedFlow<Event> = _events
+
+ private var socket: WebSocket? = null
+ private var pinger: Job? = null
+ private var pongTimeout: Job? = null
+ private var retry: Job? = null
+ private var running = false
+ private var attempts = 0
+
+ /** Whether a socket has opened before: every later open may have missed events. */
+ private var opened = false
+
+ fun start() {
+ if (running) return
+ running = true
+ connect()
+ }
+
+ fun stop() {
+ running = false
+ retry?.cancel()
+ pinger?.cancel()
+ pongTimeout?.cancel()
+ socket?.close(1000, null)
+ socket = null
+ _status.value = Status.Closed
+ }
+
+ private fun connect() {
+ if (!running || socket != null) return
+ _status.value = if (attempts > 0) Status.Reconnecting else Status.Connecting
+ val request = Request.Builder().url(api.socketUrl).build()
+ socket = api.http.newWebSocket(request, object : WebSocketListener() {
+ override fun onOpen(webSocket: WebSocket, response: Response) {
+ scope.launch {
+ if (socket !== webSocket) return@launch
+ // Anything that changed while we were away (backgrounded, or dropped) gets picked up.
+ if (opened) _events.tryEmit(Event.Reconnected)
+ opened = true
+ attempts = 0
+ _status.value = Status.Open
+ pinger?.cancel()
+ pinger = scope.launch {
+ while (true) {
+ delay(PING_MS)
+ webSocket.send("ping")
+ if (pongTimeout == null) {
+ pongTimeout = scope.launch {
+ delay(PONG_TIMEOUT_MS)
+ webSocket.cancel()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ override fun onMessage(webSocket: WebSocket, text: String) {
+ if (text == "pong") {
+ scope.launch {
+ pongTimeout?.cancel()
+ pongTimeout = null
+ }
+ return
+ }
+ when (api.eventType(text)) {
+ "fronters_update" -> _events.tryEmit(Event.FrontersChanged)
+ "mental_state_update" -> _events.tryEmit(Event.MentalStateChanged)
+ "force_refresh" -> _events.tryEmit(Event.ForceRefresh)
+ }
+ }
+
+ override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = lost(webSocket)
+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = lost(webSocket)
+ })
+ }
+
+ private fun lost(webSocket: WebSocket) {
+ scope.launch {
+ if (socket !== webSocket) return@launch
+ pinger?.cancel()
+ pongTimeout?.cancel()
+ pongTimeout = null
+ socket = null
+ if (!running) return@launch
+ _status.value = Status.Reconnecting
+ val ceiling = minOf(1000L shl attempts.coerceAtMost(5), MAX_BACKOFF_MS)
+ attempts += 1
+ retry = scope.launch {
+ delay((Random.nextDouble() * ceiling).toLong())
+ connect()
+ }
+ }
+ }
+
+ private companion object {
+ const val PING_MS = 30_000L
+ const val PONG_TIMEOUT_MS = 10_000L
+ const val MAX_BACKOFF_MS = 30_000L
+ }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Models.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Models.kt
new file mode 100644
index 0000000..c918bbe
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Models.kt
@@ -0,0 +1,157 @@
+package gay.doughmination.plural.data
+
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+
+// The shapes of /v2/plural/*, as the API returns them (mirrors
+// react-api/src/types/plural.ts). Members are PluralKit's member objects plus
+// the API's own tags, pride and status; PluralKit leaves out whatever a
+// member's privacy settings hide, so nearly everything is optional.
+
+@Serializable
+data class MemberStatus(
+ val text: String,
+ val emoji: String? = null,
+ @SerialName("updated_at") val updatedAt: String? = null,
+)
+
+@Serializable
+data class Member(
+ /** PluralKit's short id ("abcdef"). */
+ val id: String,
+ val name: String? = null,
+ @SerialName("display_name") val displayName: String? = null,
+ /** Hex without the "#", as PluralKit stores it. */
+ val color: String? = null,
+ val pronouns: String? = null,
+ @SerialName("avatar_url") val avatarUrl: String? = null,
+ val description: String? = null,
+ val tags: List<String> = emptyList(),
+ val pride: List<String> = emptyList(),
+ val status: MemberStatus? = null,
+) {
+ /** The name people see, as the website picks it. */
+ val shownName: String get() = displayName?.ifBlank { null } ?: name?.ifBlank { null } ?: id
+
+ /** What the API's tag, pride and status endpoints take: the member's name. */
+ val key: String get() = name ?: id
+
+ fun isSame(identifier: String) = identifier == id || identifier == name
+}
+
+@Serializable
+data class Fronters(
+ /** When the current switch happened. */
+ val timestamp: String? = null,
+ /** Absent when nobody is fronting. */
+ val members: List<Member> = emptyList(),
+)
+
+@Serializable
+data class MentalState(
+ val level: String,
+ @SerialName("updated_at") val updatedAt: String? = null,
+ val notes: String? = null,
+)
+
+@Serializable
+data class PluralSystem(
+ val name: String? = null,
+ val description: String? = null,
+ @SerialName("avatar_url") val avatarUrl: String? = null,
+ @SerialName("mental_state") val mentalState: MentalState? = null,
+)
+
+@Serializable
+data class Relationship(
+ val id: String,
+ /** Two member ids (or names). For a crush, the first has a crush on the second. */
+ val members: List<String>,
+ val type: String = "partner",
+ val since: String? = null,
+)
+
+@Serializable
+data class RelationshipsResponse(val relationships: List<Relationship> = emptyList())
+
+@Serializable
+data class MemberStatusResponse(val status: MemberStatus? = null)
+
+/** The windows the metrics endpoints report on, as the website labels them. */
+enum class Timeframe(val key: String, val label: String) {
+ Day("24h", "Last 24 Hours"),
+ TwoDays("48h", "Last 48 Hours"),
+ FiveDays("5d", "Last 5 Days"),
+ Week("7d", "Last 7 Days"),
+ Month("30d", "Last 30 Days"),
+}
+
+@Serializable
+data class MemberMetric(
+ val id: String,
+ val name: String? = null,
+ @SerialName("display_name") val displayName: String? = null,
+ @SerialName("avatar_url") val avatarUrl: String? = null,
+ @SerialName("total_seconds") val totalSeconds: Double = 0.0,
+ @SerialName("24h") val day: Double = 0.0,
+ @SerialName("48h") val twoDays: Double = 0.0,
+ @SerialName("5d") val fiveDays: Double = 0.0,
+ @SerialName("7d") val week: Double = 0.0,
+ @SerialName("30d") val month: Double = 0.0,
+) {
+ val shownName: String get() = displayName?.ifBlank { null } ?: name ?: id
+
+ /** Seconds fronted in a window. */
+ operator fun get(timeframe: Timeframe): Double = when (timeframe) {
+ Timeframe.Day -> day
+ Timeframe.TwoDays -> twoDays
+ Timeframe.FiveDays -> fiveDays
+ Timeframe.Week -> week
+ Timeframe.Month -> month
+ }
+}
+
+@Serializable
+data class FrontingMetrics(
+ @SerialName("total_time") val totalTime: Double = 0.0,
+ val members: Map<String, MemberMetric> = emptyMap(),
+)
+
+@Serializable
+data class SwitchMetrics(
+ @SerialName("total_switches") val totalSwitches: Int = 0,
+ @SerialName("avg_switches_per_day") val averagePerDay: Double = 0.0,
+ val timeframes: Map<String, Int> = emptyMap(),
+) {
+ operator fun get(timeframe: Timeframe): Int = timeframes[timeframe.key] ?: 0
+}
+
+@Serializable
+data class User(
+ val id: String,
+ val username: String,
+ @SerialName("display_name") val displayName: String? = null,
+ val email: String? = null,
+ @SerialName("is_admin") val isAdmin: Boolean = false,
+ @SerialName("is_owner") val isOwner: Boolean = false,
+ @SerialName("is_pet") val isPet: Boolean = false,
+ @SerialName("avatar_url") val avatarUrl: String? = null,
+) {
+ val shownName: String get() = displayName?.ifBlank { null } ?: username
+}
+
+/** The mental-state levels the website offers, in its order. */
+enum class MentalLevel(val value: String, val label: String, val severity: Int) {
+ Safe("safe", "Safe", 0),
+ Unstable("unstable", "Unstable", 1),
+ Idealizing("idealizing", "Idealizing", 1),
+ SelfHarming("self-harming", "Self-Harming", 2),
+ HighlyAtRisk("highly at risk", "Highly At Risk", 2);
+
+ companion object {
+ fun of(value: String): MentalLevel? = entries.firstOrNull { it.value == value }
+ }
+}
+
+/** The relationship types the website's admin page offers. */
+val RelationshipTypes = listOf("partner", "spouse", "queerplatonic", "datemate", "crush")
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Pride.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Pride.kt
new file mode 100644
index 0000000..e880798
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Pride.kt
@@ -0,0 +1,30 @@
+package gay.doughmination.plural.data
+
+import androidx.compose.ui.graphics.Color
+
+/** A pride flag: the label the API stores per member, and its stripes top to bottom. */
+class PrideFlag(val label: String, val stripes: List<Color>)
+
+private fun flag(label: String, vararg stripes: Long) = PrideFlag(label, stripes.map { Color(it) })
+
+/** The website's curated catalogue (system/src/lib/pride.ts), in its order. */
+val PrideFlags = listOf(
+ flag("Lesbian", 0xFFD52D00, 0xFFFF9A56, 0xFFFFFFFF, 0xFFD362A4, 0xFFA30262),
+ flag("Gay", 0xFF078D70, 0xFF98E8C1, 0xFFFFFFFF, 0xFF7BADE2, 0xFF3D1A78),
+ flag("Bisexual", 0xFFD60270, 0xFF9B4F96, 0xFF0038A8),
+ flag("Pansexual", 0xFFFF218C, 0xFFFFD800, 0xFF21B1FF),
+ flag("Asexual", 0xFF000000, 0xFFA3A3A3, 0xFFFFFFFF, 0xFF800080),
+ flag("Aromantic", 0xFF3DA542, 0xFFA7D379, 0xFFFFFFFF, 0xFFA9A9A9, 0xFF000000),
+ flag("Transgender", 0xFF5BCEFA, 0xFFF5A9B8, 0xFFFFFFFF, 0xFFF5A9B8, 0xFF5BCEFA),
+ flag("Nonbinary", 0xFFFCF434, 0xFFFFFFFF, 0xFF9C59D1, 0xFF2C2C2C),
+ flag("Genderfluid", 0xFFFF75A2, 0xFFFFFFFF, 0xFFBE18D6, 0xFF000000, 0xFF333EBD),
+ flag("Genderqueer", 0xFFB57EDC, 0xFFFFFFFF, 0xFF4A8123),
+ flag("Agender", 0xFF000000, 0xFFBCC4C7, 0xFFFFFFFF, 0xFFB7F684, 0xFFFFFFFF, 0xFFBCC4C7, 0xFF000000),
+ flag("Intersex", 0xFFFFD800, 0xFF7A00AC),
+ flag("Demisexual", 0xFF000000, 0xFFFFFFFF, 0xFF6E0070, 0xFFD3D3D3),
+ flag("Polyamory", 0xFF0000FF, 0xFFFF0000, 0xFF000000),
+ flag("Queer", 0xFFB57EDC, 0xFFFFFFFF, 0xFF4A8123),
+ flag("Rainbow", 0xFFE40303, 0xFFFF8C00, 0xFFFFED00, 0xFF008026, 0xFF004DFF, 0xFF750787),
+)
+
+fun findPrideFlag(label: String): PrideFlag? = PrideFlags.firstOrNull { it.label.equals(label, ignoreCase = true) }
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/Relations.kt b/plural/app/src/main/java/gay/doughmination/plural/data/Relations.kt
new file mode 100644
index 0000000..1328e9c
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/Relations.kt
@@ -0,0 +1,56 @@
+package gay.doughmination.plural.data
+
+// How the website reads the relationship list (system/src/routes/relationships
+// and [member_id]/+page.ts): crushes go one way (the first member has a crush
+// on the second), and two crushes on each other fold into one mutual crush.
+
+class Couple(val edge: Relationship, val a: Member, val b: Member, val mutual: Boolean) {
+ val label: String
+ get() = when {
+ edge.type != "crush" -> edge.type
+ mutual -> "mutual crush"
+ else -> "has a crush on"
+ }
+}
+
+fun List<Member>.find(identifier: String): Member? = firstOrNull { it.isSame(identifier) }
+
+/** Every relationship between two known members, mutual crushes folded together. */
+fun pairs(relationships: List<Relationship>, members: List<Member>): List<Couple> {
+ val list = mutableListOf<Couple>()
+ for (edge in relationships) {
+ val a = members.find(edge.members.getOrNull(0) ?: continue) ?: continue
+ val b = members.find(edge.members.getOrNull(1) ?: continue) ?: continue
+ if (a.id == b.id) continue
+ val reverse = list.indexOfFirst { it.edge.type == "crush" && edge.type == "crush" && it.a.id == b.id && it.b.id == a.id }
+ if (reverse >= 0) {
+ val old = list[reverse]
+ list[reverse] = Couple(old.edge, old.a, old.b, mutual = true)
+ } else {
+ list += Couple(edge, a, b, mutual = false)
+ }
+ }
+ return list
+}
+
+class Crush(val member: Member, val mutual: Boolean)
+
+/** A member's partners (any type but crush), the website's member page. */
+fun partnersOf(member: Member, relationships: List<Relationship>, members: List<Member>): List<Member> =
+ relationships.filter { it.type != "crush" }.mapNotNull { edge ->
+ when {
+ member.isSame(edge.members[0]) -> members.find(edge.members[1])
+ member.isSame(edge.members[1]) -> members.find(edge.members[0])
+ else -> null
+ }
+ }.distinctBy { it.id }
+
+/** Who a member has a crush on; mutual when the crush goes both ways. */
+fun crushesOf(member: Member, relationships: List<Relationship>, members: List<Member>): List<Crush> {
+ val crushes = relationships.filter { it.type == "crush" }
+ val crushedBy = crushes.filter { member.isSame(it.members[1]) }.mapNotNull { members.find(it.members[0]) }
+ return crushes.filter { member.isSame(it.members[0]) }
+ .mapNotNull { members.find(it.members[1]) }
+ .distinctBy { it.id }
+ .map { crush -> Crush(crush, mutual = crushedBy.any { it.id == crush.id }) }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/data/TokenStore.kt b/plural/app/src/main/java/gay/doughmination/plural/data/TokenStore.kt
new file mode 100644
index 0000000..9fe9ab1
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/data/TokenStore.kt
@@ -0,0 +1,74 @@
+package gay.doughmination.plural.data
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.util.Base64
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * Holds the API token, encrypted with a key that never leaves the Android
+ * Keystore, so a copy of the app's files alone doesn't sign anyone in (the
+ * same as Inbox). Also keeps the PKCE verifier of a sign-in in progress, which
+ * has to survive the app being killed while the browser tab is open.
+ */
+class TokenStore(context: Context) {
+ private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE)
+
+ @Volatile
+ private var cached: String? = null
+
+ var token: String?
+ get() = cached ?: prefs.getString(KEY_TOKEN, null)?.let(::decrypt)?.also { cached = it }
+ set(value) {
+ cached = value
+ prefs.edit().apply {
+ if (value == null) remove(KEY_TOKEN) else putString(KEY_TOKEN, encrypt(value))
+ }.apply()
+ }
+
+ var pendingVerifier: String?
+ get() = prefs.getString(KEY_VERIFIER, null)
+ set(value) = prefs.edit().apply {
+ if (value == null) remove(KEY_VERIFIER) else putString(KEY_VERIFIER, value)
+ }.apply()
+
+ private fun key(): SecretKey {
+ val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ (store.getKey(ALIAS, null) as SecretKey?)?.let { return it }
+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
+ generator.init(
+ KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .build(),
+ )
+ return generator.generateKey()
+ }
+
+ private fun encrypt(plain: String): String {
+ val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, key()) }
+ val sealed = cipher.iv + cipher.doFinal(plain.toByteArray())
+ return Base64.encodeToString(sealed, Base64.NO_WRAP)
+ }
+
+ /** Null when it can't be read (the key was wiped, say); that just means signed out. */
+ private fun decrypt(stored: String): String? = runCatching {
+ val sealed = Base64.decode(stored, Base64.NO_WRAP)
+ val cipher = Cipher.getInstance(TRANSFORM)
+ cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, sealed, 0, IV_BYTES))
+ String(cipher.doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES))
+ }.getOrNull()
+
+ private companion object {
+ const val ALIAS = "plural-session"
+ const val TRANSFORM = "AES/GCM/NoPadding"
+ const val IV_BYTES = 12
+ const val KEY_TOKEN = "token"
+ const val KEY_VERIFIER = "verifier"
+ }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/AccountScreen.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/AccountScreen.kt
new file mode 100644
index 0000000..0294c5a
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/AccountScreen.kt
@@ -0,0 +1,255 @@
+@file:OptIn(ExperimentalLayoutApi::class)
+
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.outlined.Login
+import androidx.compose.material.icons.automirrored.outlined.Logout
+import androidx.compose.material.icons.outlined.ChatBubbleOutline
+import androidx.compose.material.icons.outlined.Edit
+import androidx.compose.material.icons.outlined.FavoriteBorder
+import androidx.compose.material.icons.outlined.Flag
+import androidx.compose.material.icons.outlined.Group
+import androidx.compose.material.icons.outlined.LocalOffer
+import androidx.compose.material.icons.outlined.Psychology
+import androidx.compose.material.icons.outlined.Refresh
+import androidx.compose.material.icons.outlined.SwapHoriz
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+
+/** Sign-in, the profile, and the way into the admin and owner tools. */
+@Composable
+fun AccountScreen(vm: SystemViewModel) {
+ Column(
+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ if (!vm.signedIn) {
+ SignIn(vm)
+ return@Column
+ }
+ val user = vm.user
+ if (user == null) {
+ Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
+ return@Column
+ }
+
+ Panel {
+ Text("Account", style = Eyebrow)
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Avatar(user.avatarUrl, 96.dp, ring = Accent)
+ Text(user.shownName, style = MaterialTheme.typography.headlineSmall)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (user.isOwner) Badge("Owner")
+ if (user.isAdmin) Badge("Admin", accent = false)
+ if (user.isPet) Badge("Pet", accent = false)
+ }
+ Text("@${user.username}", color = Muted)
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(onClick = { vm.open(Screen.EditProfile) }) {
+ Icon(Icons.Outlined.Edit, null, Modifier.size(18.dp)); HGap(6); Text("Edit profile")
+ }
+ OutlinedButton(onClick = vm::signOut) {
+ Icon(Icons.AutoMirrored.Outlined.Logout, null, Modifier.size(18.dp)); HGap(6); Text("Sign out")
+ }
+ }
+ }
+
+ if (vm.isAdmin) AdminHub(vm)
+ }
+}
+
+@Composable
+private fun SignIn(vm: SystemViewModel) {
+ val context = LocalContext.current
+ Panel {
+ Text("Account", style = Eyebrow)
+ Text("Sign in", style = MaterialTheme.typography.headlineSmall)
+ Text("Use your SSO account to continue.", color = Muted)
+ Button(onClick = { vm.startLogin(context) }, enabled = !vm.signingIn) {
+ Icon(Icons.AutoMirrored.Outlined.Login, null, Modifier.size(18.dp))
+ HGap(6)
+ Text(if (vm.signingIn) "Signing in…" else "Sign in with SSO")
+ }
+ Text(
+ "You'll be taken to your SSO provider in a browser tab, then brought right back here.",
+ color = Muted,
+ style = MaterialTheme.typography.bodySmall,
+ )
+ }
+ Panel {
+ Text("Everything on the Members, Relationships and Metrics tabs is public and works without signing in. Signing in adds the admin tools.", color = Muted, style = MaterialTheme.typography.bodyMedium)
+ }
+}
+
+/** The website's /admin/dash and /owner/dash in one list. */
+@Composable
+private fun AdminHub(vm: SystemViewModel) {
+ var confirmRefresh by remember { mutableStateOf(false) }
+
+ PageHead("Admin", "Admin dashboard", "System management hub")
+ Tile(Icons.Outlined.SwapHoriz, "Switch manager", "Manage fronting members") { vm.open(Screen.Switch) }
+ Tile(Icons.Outlined.Psychology, "Mental health", "Update mental state") { vm.open(Screen.Mental) }
+ Tile(Icons.Outlined.ChatBubbleOutline, "Status manager", "Set member statuses") { vm.open(Screen.Status) }
+ Tile(Icons.Outlined.LocalOffer, "Tag manager", "Manage member tags") { vm.open(Screen.Tags) }
+ if (vm.isOwner) {
+ Tile(Icons.Outlined.Flag, "Pride manager", "Set member pride identities") { vm.open(Screen.Pride) }
+ Tile(Icons.Outlined.FavoriteBorder, "Relationships", "Map who is dating who") { vm.open(Screen.ManageRelationships) }
+ Tile(Icons.Outlined.Group, "User management", "Manage all users") { vm.open(Screen.Users) }
+ }
+
+ Panel(Modifier.border(1.dp, Bad.copy(alpha = 0.4f), RoundedCornerShape(16.dp))) {
+ Text("[ danger ] Force refresh all clients", style = MaterialTheme.typography.titleMedium)
+ Text(
+ "Send a refresh command to everyone viewing the website or this app. Their pages reload immediately.",
+ color = Muted,
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Button(
+ onClick = { confirmRefresh = true },
+ enabled = !vm.busy,
+ colors = ButtonDefaults.buttonColors(containerColor = Bad),
+ ) {
+ Icon(Icons.Outlined.Refresh, null, Modifier.size(18.dp)); HGap(6); Text("Refresh all")
+ }
+ }
+
+ if (confirmRefresh) {
+ Confirm(
+ title = "Refresh everyone?",
+ text = "This will reload the website for ALL connected users. Are you sure?",
+ action = "Refresh all",
+ onDismiss = { confirmRefresh = false },
+ ) {
+ confirmRefresh = false
+ vm.forceRefresh()
+ }
+ }
+}
+
+@Composable
+private fun Tile(icon: ImageVector, title: String, description: String, onClick: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(16.dp))
+ .background(Raised)
+ .border(1.dp, Line, RoundedCornerShape(16.dp))
+ .clickable(onClick = onClick)
+ .padding(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Box(Modifier.size(40.dp).clip(RoundedCornerShape(12.dp)).background(AccentDim), contentAlignment = Alignment.Center) {
+ Icon(icon, null, tint = Accent)
+ }
+ Column {
+ Text(title, style = MaterialTheme.typography.titleMedium)
+ Text(description, color = Muted, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+}
+
+/** A yes/no question before something that can't be undone. */
+@Composable
+fun Confirm(title: String, text: String, action: String, onDismiss: () -> Unit, onConfirm: () -> Unit) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(title) },
+ text = { Text(text) },
+ confirmButton = { TextButton(onClick = onConfirm) { Text(action, color = Bad) } },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
+ )
+}
+
+private val EmailPattern = Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")
+
+/** The website's /user/profile/edit. */
+@Composable
+fun EditProfileScreen(vm: SystemViewModel) {
+ val user = vm.user
+ var displayName by rememberSaveable { mutableStateOf(user?.displayName.orEmpty()) }
+ var avatarUrl by rememberSaveable { mutableStateOf(user?.avatarUrl.orEmpty()) }
+ var email by rememberSaveable { mutableStateOf(user?.email.orEmpty()) }
+ val emailOk = email.isBlank() || EmailPattern.matches(email.trim())
+
+ Column(Modifier.fillMaxSize()) {
+ BackBar("Edit profile", onBack = vm::back)
+ if (user == null) return@Column
+ Column(
+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ Notice("Sign-in is handled by SSO. Your username and password are managed by your SSO provider — this page only controls your display profile.")
+ Panel {
+ Field("Avatar", "Paste a direct link to an image (square recommended)") {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Avatar(avatarUrl.trim().ifBlank { null }, 56.dp, ring = Accent)
+ OutlinedTextField(
+ avatarUrl, { avatarUrl = it },
+ placeholder = { Text("https://example.com/avatar.png") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
+ modifier = Modifier.weight(1f),
+ )
+ }
+ }
+ Field("Display name", "Leave blank to use username: @${user.username}") {
+ OutlinedTextField(displayName, { displayName = it }, placeholder = { Text("Enter display name") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ }
+ Field("Contact email", "Optional contact address. Sign-in email lives with your SSO provider, not here.") {
+ OutlinedTextField(
+ email, { email = it },
+ placeholder = { Text("[email protected]") },
+ singleLine = true,
+ isError = !emailOk,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ Button(onClick = { vm.saveProfile(displayName, avatarUrl, email) }, enabled = !vm.busy && emailOk) {
+ Text(if (vm.busy) "Saving..." else "Save changes")
+ }
+ }
+ }
+ }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/AdminScreens.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/AdminScreens.kt
new file mode 100644
index 0000000..161bd04
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/AdminScreens.kt
@@ -0,0 +1,570 @@
+@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
+
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Close
+import androidx.compose.material.icons.outlined.Delete
+import androidx.compose.material3.Button
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExposedDropdownMenuBox
+import androidx.compose.material3.ExposedDropdownMenuDefaults
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.MenuAnchorType
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.RadioButton
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import gay.doughmination.plural.data.Api
+import gay.doughmination.plural.data.Member
+import gay.doughmination.plural.data.MentalLevel
+import gay.doughmination.plural.data.PrideFlags
+import gay.doughmination.plural.data.Relationship
+import gay.doughmination.plural.data.RelationshipTypes
+import gay.doughmination.plural.data.User
+import gay.doughmination.plural.data.find
+import gay.doughmination.plural.data.memberColour
+
+/** An admin page: a back bar over a scrolling column. */
+@Composable
+private fun AdminPage(vm: SystemViewModel, title: String, content: @Composable ColumnScope.() -> Unit) {
+ Column(Modifier.fillMaxSize()) {
+ BackBar(title, onBack = vm::back)
+ Column(
+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp).padding(bottom = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ content = content,
+ )
+ }
+}
+
+/** A member in a list to pick from, like the website's .pick rows. */
+@Composable
+private fun PickRow(member: Member, selected: Boolean, note: String? = null, trailing: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(if (selected) AccentDim else Raised)
+ .border(1.dp, if (selected) AccentLine else Line, RoundedCornerShape(12.dp))
+ .clickable(onClick = onClick)
+ .padding(horizontal = 10.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ Avatar(member.avatarUrl, 36.dp, ring = memberColour(member.color))
+ Column(Modifier.weight(1f)) {
+ Text(member.shownName, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ note?.let { Text(it, color = Muted, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) }
+ }
+ trailing?.invoke()
+ }
+}
+
+/** The website's MemberSelect: a dropdown of members. */
+@Composable
+private fun MemberSelect(label: String, members: List<Member>, selected: Member?, note: (Member) -> String = { "" }, onSelect: (Member) -> Unit) {
+ var open by remember { mutableStateOf(false) }
+ ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it }) {
+ OutlinedTextField(
+ value = selected?.shownName ?: "",
+ onValueChange = {},
+ readOnly = true,
+ label = { Text(label) },
+ placeholder = { Text("Choose a member...") },
+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = open) },
+ modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
+ )
+ ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
+ members.forEach { member ->
+ DropdownMenuItem(
+ text = { Text(member.shownName + note(member)) },
+ leadingIcon = { Avatar(member.avatarUrl, 24.dp) },
+ onClick = {
+ onSelect(member)
+ open = false
+ },
+ )
+ }
+ }
+ }
+}
+
+// ---- Switch manager -----------------------------------------------------------
+
+/** The website's /admin/switch: pick who's fronting now. */
+@Composable
+fun SwitchScreen(vm: SystemViewModel) {
+ val current = vm.fronters?.members.orEmpty().map { it.id }.toSet()
+ var selected by remember { mutableStateOf(current) }
+ var search by rememberSaveable { mutableStateOf("") }
+ // Starts from whoever is fronting; follows a switch made elsewhere until changed here.
+ LaunchedEffect(current) { selected = current }
+
+ val query = search.trim().lowercase()
+ val shown = vm.members.filter { m -> m.shownName.lowercase().contains(query) || m.tags.any { it.lowercase().contains(query) } }
+ val changed = selected != current
+
+ AdminPage(vm, "Switch manager") {
+ Text("Manage fronting members", color = Muted)
+ Panel {
+ SectionTitle("Currently fronting")
+ if (current.isEmpty()) Text("No one currently fronting", color = Muted)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ vm.fronters?.members.orEmpty().forEach { PersonChip(vm.member(it.id) ?: it) {} }
+ }
+ }
+
+ Panel {
+ SectionTitle("Selected")
+ Text("${selected.size} member${if (selected.size != 1) "s" else ""} selected", color = Muted, fontSize = 13.sp)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ vm.members.filter { it.id in selected }.forEach { member ->
+ PersonChip(member, badge = "✕") { selected = selected - member.id }
+ }
+ }
+ Button(
+ onClick = {
+ if (selected.isEmpty()) vm.show("Please select at least one member", error = true)
+ else vm.switchTo(vm.members.filter { it.id in selected }.map { it.id })
+ },
+ enabled = !vm.busy && selected.isNotEmpty() && changed,
+ modifier = Modifier.fillMaxWidth(),
+ ) { Text(if (vm.busy) "Switching..." else if (changed) "Apply switch" else "No changes") }
+ }
+
+ OutlinedTextField(search, { search = it }, placeholder = { Text("Search members...") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
+ OutlinedButton(onClick = { selected = selected + shown.map { it.id } }, enabled = shown.isNotEmpty()) { Text("Select all") }
+ OutlinedButton(onClick = { selected = emptySet() }, enabled = selected.isNotEmpty()) { Text("Clear all") }
+ }
+ if (shown.isEmpty()) Text(if (search.isNotBlank()) "No members found matching your search" else "No members available", color = Muted)
+ shown.forEach { member ->
+ PickRow(
+ member,
+ selected = member.id in selected,
+ note = member.pronouns,
+ trailing = {
+ if (member.id in current) Badge("fronting")
+ Checkbox(checked = member.id in selected, onCheckedChange = null)
+ },
+ ) { selected = if (member.id in selected) selected - member.id else selected + member.id }
+ }
+ }
+}
+
+// ---- Mental health --------------------------------------------------------------
+
+/** The website's /admin/mental. */
+@Composable
+fun MentalScreen(vm: SystemViewModel) {
+ val current = vm.mental
+ var level by rememberSaveable { mutableStateOf(current?.level ?: "") }
+ var notes by rememberSaveable { mutableStateOf(current?.notes ?: "") }
+
+ AdminPage(vm, "Mental health") {
+ Text("Update system mental state", color = Muted)
+ current?.let { MentalBanner(it) }
+ Panel {
+ Field("Mental state level") {
+ MentalLevel.entries.forEach { option ->
+ Row(
+ Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).clickable { level = option.value }.padding(vertical = 2.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ RadioButton(selected = level == option.value, onClick = { level = option.value })
+ Icon(mentalIcon(option.value), null, tint = mentalColour(option.value), modifier = Modifier.size(20.dp))
+ HGap()
+ Text(option.label)
+ }
+ }
+ }
+ Field("Notes (optional)") {
+ OutlinedTextField(
+ notes, { notes = it },
+ placeholder = { Text("Add any additional notes about the current mental state...") },
+ minLines = 3,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ Button(onClick = { vm.setMental(level, notes) }, enabled = !vm.busy && level.isNotBlank()) {
+ Text(if (vm.busy) "Updating..." else "Update mental state")
+ }
+ }
+ }
+}
+
+// ---- Status manager -------------------------------------------------------------
+
+private val EmojiSuggestions = listOf("💤", "🎮", "📚", "🎨", "🎵", "💻", "🌙", "☀️", "🍕", "☕", "🎬", "✨", "💭", "😴", "🏃", "🧘")
+
+/** The website's /admin/status. */
+@Composable
+fun StatusScreen(vm: SystemViewModel) {
+ var chosenId by rememberSaveable { mutableStateOf<String?>(null) }
+ val chosen = chosenId?.let(vm::member)
+ var text by rememberSaveable { mutableStateOf("") }
+ var emoji by rememberSaveable { mutableStateOf("") }
+ var confirmClear by remember { mutableStateOf(false) }
+ // Picking a member fills the form with their current status.
+ LaunchedEffect(chosenId) {
+ text = chosen?.status?.text.orEmpty()
+ emoji = chosen?.status?.emoji.orEmpty()
+ }
+ val withStatus = vm.members.filter { it.status != null }
+
+ AdminPage(vm, "Status manager") {
+ Text("Update member status messages", color = Muted)
+ Panel {
+ MemberSelect("Select member", vm.members, chosen, note = { if (it.status != null) " (has status)" else "" }) { chosenId = it.id }
+ if (chosen != null) {
+ Field("Emoji (optional)") {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedTextField(emoji, { if (it.length <= 4) emoji = it }, placeholder = { Text("😊") }, singleLine = true, modifier = Modifier.size(width = 80.dp, height = 56.dp))
+ if (emoji.isNotEmpty()) IconButton(onClick = { emoji = "" }) { Icon(Icons.Outlined.Close, "Clear emoji") }
+ }
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ EmojiSuggestions.forEach { suggestion -> Chip(suggestion, active = emoji == suggestion) { emoji = suggestion } }
+ }
+ }
+ Field("Status text", "${text.length}/100 characters") {
+ OutlinedTextField(text, { if (it.length <= 100) text = it }, placeholder = { Text("What's happening?") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(onClick = { vm.setStatus(chosen, text, emoji) }, enabled = !vm.busy && text.isNotBlank()) {
+ Text(if (vm.busy) "Updating..." else "Update status")
+ }
+ if (chosen.status != null) {
+ OutlinedButton(onClick = { confirmClear = true }, enabled = !vm.busy) { Text("Clear", color = Bad) }
+ }
+ }
+ chosen.status?.let { status ->
+ Notice("Current: ${status.emoji.orEmpty()} ${status.text}".trim() + (formatTime(status.updatedAt)?.let { "\nUpdated $it" } ?: ""))
+ }
+ }
+ }
+
+ Panel {
+ SectionTitle("Members with a status")
+ Text("${withStatus.size} member(s) have status set", color = Muted, fontSize = 13.sp)
+ if (withStatus.isEmpty()) Text("No members have status set", color = Muted)
+ withStatus.forEach { member ->
+ PickRow(member, selected = member.id == chosenId, note = "${member.status?.emoji.orEmpty()} ${member.status?.text.orEmpty()}".trim()) {
+ chosenId = member.id
+ }
+ }
+ }
+ }
+
+ if (confirmClear && chosen != null) {
+ Confirm("Clear status?", "Clear status for ${chosen.shownName}?", "Clear", onDismiss = { confirmClear = false }) {
+ confirmClear = false
+ vm.clearStatus(chosen)
+ }
+ }
+}
+
+// ---- Tag manager ------------------------------------------------------------------
+
+/** The website's /admin/tags. */
+@Composable
+fun TagsScreen(vm: SystemViewModel) {
+ var chosenId by rememberSaveable { mutableStateOf<String?>(null) }
+ val chosen = chosenId?.let(vm::member)
+ var newTag by rememberSaveable { mutableStateOf("") }
+ var search by rememberSaveable { mutableStateOf("") }
+ var removing by remember { mutableStateOf<Pair<Member, String>?>(null) }
+ val allTags = vm.members.flatMap { it.tags }.distinct().sortedBy { it.lowercase() }
+ val query = search.trim().lowercase()
+ val shown = vm.members.filter { m -> m.shownName.lowercase().contains(query) || m.tags.any { it.lowercase().contains(query) } }
+
+ AdminPage(vm, "Tag manager") {
+ Text("Manage member tags", color = Muted)
+ Panel {
+ MemberSelect("Select member", vm.members, chosen) { chosenId = it.id }
+ if (chosen != null) {
+ Field("Tags") {
+ if (chosen.tags.isEmpty()) Text("No tags yet", color = Muted)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ chosen.tags.forEach { tag -> Chip("$tag ✕", tint = memberColour(chosen.color)) { removing = chosen to tag } }
+ }
+ }
+ Field("Add a tag") {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
+ OutlinedTextField(newTag, { newTag = it }, placeholder = { Text("New tag") }, singleLine = true, modifier = Modifier.weight(1f))
+ Button(onClick = { vm.addTag(chosen, newTag); newTag = "" }, enabled = !vm.busy && newTag.isNotBlank()) { Text("Add") }
+ }
+ val suggestions = allTags.filter { it !in chosen.tags && it.contains(newTag.trim(), ignoreCase = true) }
+ if (suggestions.isNotEmpty()) {
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ suggestions.take(12).forEach { tag -> Chip(tag) { newTag = tag } }
+ }
+ }
+ }
+ }
+ }
+
+ OutlinedTextField(search, { search = it }, placeholder = { Text("Search members or tags...") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ shown.forEach { member ->
+ PickRow(member, selected = member.id == chosenId, note = member.tags.joinToString(", ").ifBlank { "No tags" }) { chosenId = member.id }
+ }
+ }
+
+ removing?.let { (member, tag) ->
+ Confirm("Remove tag?", "Remove tag \"$tag\" from ${member.shownName}?", "Remove", onDismiss = { removing = null }) {
+ removing = null
+ vm.removeTag(member, tag)
+ }
+ }
+}
+
+// ---- Pride manager (owner) ----------------------------------------------------------
+
+/** The website's /admin/pride: tap a flag to give or take it. */
+@Composable
+fun PrideScreen(vm: SystemViewModel) {
+ var chosenId by rememberSaveable { mutableStateOf<String?>(null) }
+ val chosen = chosenId?.let(vm::member)
+
+ AdminPage(vm, "Pride manager") {
+ Text("Set member pride identities", color = Muted)
+ Panel {
+ MemberSelect("Select member", vm.members, chosen) { chosenId = it.id }
+ if (chosen != null) {
+ Field("Identities", "Tap a flag to add it; tap a highlighted one to remove it.") {
+ // The catalogue, plus anything already set that isn't in it.
+ val labels = PrideFlags.map { it.label } + chosen.pride.filter { label -> PrideFlags.none { it.label.equals(label, true) } }
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ labels.forEach { label ->
+ val has = chosen.pride.any { it.equals(label, ignoreCase = true) }
+ Chip(label, active = has, leading = { PrideSwatch(label) }) {
+ if (vm.busy) return@Chip
+ if (has) vm.removePride(chosen, chosen.pride.first { it.equals(label, true) }) else vm.addPride(chosen, label)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+// ---- Relationships (owner) --------------------------------------------------------
+
+/** The website's /admin/relationships. */
+@Composable
+fun ManageRelationshipsScreen(vm: SystemViewModel) {
+ var aId by rememberSaveable { mutableStateOf<String?>(null) }
+ var bId by rememberSaveable { mutableStateOf<String?>(null) }
+ var type by rememberSaveable { mutableStateOf("partner") }
+ var since by rememberSaveable { mutableStateOf("") }
+ var removing by remember { mutableStateOf<Relationship?>(null) }
+ val a = aId?.let(vm::member)
+ val b = bId?.let(vm::member)
+
+ fun label(identifier: String) = vm.members.find(identifier)?.shownName ?: identifier
+
+ AdminPage(vm, "Relationships") {
+ Text("Map who is dating who. A crush goes one way: the first member has a crush on the second.", color = Muted)
+ Panel {
+ MemberSelect("First member", vm.members, a) { aId = it.id }
+ Field("Type") {
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ RelationshipTypes.forEach { option -> Chip(option, active = type == option) { type = option } }
+ }
+ }
+ MemberSelect("Second member", vm.members, b) { bId = it.id }
+ Field("Since (optional)", "Free text, e.g. 2026-02-14") {
+ OutlinedTextField(since, { since = it }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ }
+ Button(
+ onClick = {
+ when {
+ a == null || b == null -> vm.show("Pick two members", error = true)
+ a.id == b.id -> vm.show("Pick two different members", error = true)
+ else -> vm.addRelationship(a, b, type, since) { aId = null; bId = null; since = ""; type = "partner" }
+ }
+ },
+ enabled = !vm.busy,
+ ) { Text(if (vm.busy) "Saving..." else "Add relationship") }
+ }
+
+ Panel {
+ SectionTitle("Current relationships")
+ if (vm.relationships.isEmpty()) Text("None yet", color = Muted)
+ vm.relationships.forEach { edge ->
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Column(Modifier.weight(1f)) {
+ Text("${label(edge.members[0])} ${if (edge.type == "crush") "→" else "&"} ${label(edge.members[1])}")
+ Text(edge.type + (edge.since?.let { " · since $it" } ?: ""), color = Muted, fontSize = 12.sp)
+ }
+ IconButton(onClick = { removing = edge }, enabled = !vm.busy) { Icon(Icons.Outlined.Delete, "Remove", tint = Bad) }
+ }
+ }
+ }
+ }
+
+ removing?.let { edge ->
+ val pair = "${label(edge.members[0])} ${if (edge.type == "crush") "→" else "&"} ${label(edge.members[1])}"
+ Confirm("Remove relationship?", "Remove the relationship between $pair?", "Remove", onDismiss = { removing = null }) {
+ removing = null
+ vm.removeRelationship(edge)
+ }
+ }
+}
+
+// ---- User management (owner) ------------------------------------------------------
+
+/** The website's /owner/users. */
+@Composable
+fun UsersScreen(vm: SystemViewModel) {
+ var creating by rememberSaveable { mutableStateOf(false) }
+ var editingId by rememberSaveable { mutableStateOf<String?>(null) }
+ var deleting by remember { mutableStateOf<User?>(null) }
+
+ AdminPage(vm, "User management") {
+ Text("Accounts sign in with SSO; this controls their profile and roles here.", color = Muted)
+ if (creating) {
+ CreateUser(vm, onDone = { creating = false })
+ } else {
+ Button(onClick = { creating = true }) { Text("Add user") }
+ }
+ vm.users.forEach { user ->
+ if (editingId == user.id) {
+ EditUser(vm, user, onDone = { editingId = null })
+ } else {
+ Panel {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Avatar(user.avatarUrl, 44.dp)
+ Column(Modifier.weight(1f)) {
+ Text(user.shownName)
+ Text("@${user.username}" + (user.email?.let { " · $it" } ?: ""), color = Muted, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (user.isOwner) Badge("Owner")
+ if (user.isAdmin) Badge("Admin", accent = false)
+ if (user.isPet) Badge("Pet", accent = false)
+ }
+ }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedButton(onClick = { editingId = user.id }) { Text("Edit") }
+ if (user.id != vm.user?.id) {
+ OutlinedButton(onClick = { deleting = user }, enabled = !vm.busy) { Text("Delete", color = Bad) }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ deleting?.let { user ->
+ Confirm("Delete user?", "Delete user \"${user.username}\"? This action cannot be undone.", "Delete", onDismiss = { deleting = null }) {
+ deleting = null
+ vm.deleteUser(user)
+ }
+ }
+}
+
+@Composable
+private fun CreateUser(vm: SystemViewModel, onDone: () -> Unit) {
+ var username by rememberSaveable { mutableStateOf("") }
+ var displayName by rememberSaveable { mutableStateOf("") }
+ var email by rememberSaveable { mutableStateOf("") }
+ var admin by rememberSaveable { mutableStateOf(false) }
+ var pet by rememberSaveable { mutableStateOf(false) }
+ Panel {
+ SectionTitle("New user")
+ OutlinedTextField(username, { username = it }, label = { Text("Username") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ OutlinedTextField(displayName, { displayName = it }, label = { Text("Display name (optional)") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ OutlinedTextField(email, { email = it }, label = { Text("Email (optional)") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ Toggle("Admin", admin) { admin = it }
+ Toggle("Pet", pet) { pet = it }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(
+ onClick = {
+ if (username.isBlank()) {
+ vm.show("Username is required", error = true)
+ } else {
+ vm.createUser(
+ Api.UserCreate(username.trim(), displayName.trim().ifBlank { null }, email.trim().ifBlank { null }, admin, pet),
+ then = onDone,
+ )
+ }
+ },
+ enabled = !vm.busy,
+ ) { Text("Create") }
+ OutlinedButton(onClick = onDone) { Text("Cancel") }
+ }
+ }
+}
+
+@Composable
+private fun EditUser(vm: SystemViewModel, user: User, onDone: () -> Unit) {
+ var displayName by rememberSaveable(user.id) { mutableStateOf(user.displayName.orEmpty()) }
+ var email by rememberSaveable(user.id) { mutableStateOf(user.email.orEmpty()) }
+ var avatarUrl by rememberSaveable(user.id) { mutableStateOf(user.avatarUrl.orEmpty()) }
+ var admin by rememberSaveable(user.id) { mutableStateOf(user.isAdmin) }
+ var pet by rememberSaveable(user.id) { mutableStateOf(user.isPet) }
+ Panel(Modifier.border(1.dp, AccentLine, RoundedCornerShape(16.dp))) {
+ SectionTitle("Editing @${user.username}")
+ OutlinedTextField(displayName, { displayName = it }, label = { Text("Display name") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ OutlinedTextField(
+ email, { email = it },
+ label = { Text("Email") },
+ singleLine = true,
+ // Only the owner may change someone's email, as on the website.
+ enabled = vm.isOwner,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ OutlinedTextField(avatarUrl, { avatarUrl = it }, label = { Text("Avatar URL") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ Toggle("Admin", admin) { admin = it }
+ Toggle("Pet", pet) { pet = it }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(onClick = { vm.updateUser(user, displayName, email, avatarUrl, admin, pet, then = onDone) }, enabled = !vm.busy) { Text("Save") }
+ OutlinedButton(onClick = onDone) { Text("Cancel") }
+ }
+ }
+}
+
+@Composable
+private fun Toggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
+ Row(Modifier.fillMaxWidth().clickable { onChange(!checked) }, verticalAlignment = Alignment.CenterVertically) {
+ Text(label, modifier = Modifier.weight(1f))
+ Switch(checked = checked, onCheckedChange = onChange)
+ }
+}
+
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/AppRoot.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/AppRoot.kt
new file mode 100644
index 0000000..4638d3d
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/AppRoot.kt
@@ -0,0 +1,104 @@
+package gay.doughmination.plural.ui
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.asPaddingValues
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.AccountCircle
+import androidx.compose.material.icons.outlined.BarChart
+import androidx.compose.material.icons.outlined.FavoriteBorder
+import androidx.compose.material.icons.outlined.Groups
+import androidx.compose.material3.Icon
+import androidx.compose.material3.NavigationBar
+import androidx.compose.material3.NavigationBarItem
+import androidx.compose.material3.NavigationBarItemDefaults
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Snackbar
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+
+private class Tab(val screen: Screen, val label: String, val icon: ImageVector)
+
+private val Tabs = listOf(
+ Tab(Screen.Members, "Members", Icons.Outlined.Groups),
+ Tab(Screen.Relationships, "Relationships", Icons.Outlined.FavoriteBorder),
+ Tab(Screen.Metrics, "Metrics", Icons.Outlined.BarChart),
+ Tab(Screen.Account, "Account", Icons.Outlined.AccountCircle),
+)
+
+@Composable
+fun AppRoot(vm: SystemViewModel) {
+ val snackbar = remember { SnackbarHostState() }
+ LaunchedEffect(vm.flash) {
+ vm.flash?.let { snackbar.showSnackbar(it.text) }
+ }
+
+ // Back pops a page off the current tab, then returns to Members, then leaves.
+ BackHandler(enabled = vm.stack.size > 1 || vm.tab != Screen.Members) {
+ if (vm.stack.size > 1) vm.back() else vm.selectTab(Screen.Members)
+ }
+
+ Box(Modifier.fillMaxSize()) {
+ Backdrop()
+ Scaffold(
+ containerColor = Color.Transparent,
+ snackbarHost = {
+ SnackbarHost(snackbar) { data ->
+ val error = vm.flash?.error == true
+ Snackbar(
+ data,
+ containerColor = if (error) Bad else androidx.compose.material3.MaterialTheme.colorScheme.surfaceContainerHighest,
+ contentColor = if (error) Color(0xFF1A0611) else TextColour,
+ )
+ }
+ },
+ bottomBar = {
+ NavigationBar(containerColor = Bg.copy(alpha = 0.92f)) {
+ Tabs.forEach { tab ->
+ NavigationBarItem(
+ selected = vm.tab == tab.screen,
+ onClick = { vm.selectTab(tab.screen) },
+ icon = { Icon(tab.icon, contentDescription = null) },
+ label = { Text(tab.label) },
+ colors = NavigationBarItemDefaults.colors(indicatorColor = AccentDim, selectedIconColor = Accent, selectedTextColor = Accent),
+ )
+ }
+ }
+ },
+ contentWindowInsets = WindowInsets(0),
+ ) { padding ->
+ Box(Modifier.padding(padding).fillMaxSize().padding(top = statusBarPadding())) {
+ when (val screen = vm.screen) {
+ Screen.Members -> HomeScreen(vm)
+ Screen.Relationships -> RelationshipsScreen(vm)
+ Screen.Metrics -> MetricsScreen(vm)
+ Screen.Account -> AccountScreen(vm)
+ is Screen.MemberPage -> MemberScreen(vm, screen.id)
+ Screen.EditProfile -> EditProfileScreen(vm)
+ Screen.Switch -> SwitchScreen(vm)
+ Screen.Mental -> MentalScreen(vm)
+ Screen.Status -> StatusScreen(vm)
+ Screen.Tags -> TagsScreen(vm)
+ Screen.Pride -> PrideScreen(vm)
+ Screen.ManageRelationships -> ManageRelationshipsScreen(vm)
+ Screen.Users -> UsersScreen(vm)
+ }
+ }
+ }
+ }
+}
+
+/** Content starts below the status bar; the app draws edge to edge. */
+@Composable
+private fun statusBarPadding() = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/Avatar.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/Avatar.kt
new file mode 100644
index 0000000..9bfc27a
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/Avatar.kt
@@ -0,0 +1,92 @@
+package gay.doughmination.plural.ui
+
+import android.graphics.BitmapFactory
+import android.util.LruCache
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.border
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.produceState
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.imageResource
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import gay.doughmination.plural.R
+import gay.doughmination.plural.SystemApp
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.util.concurrent.ConcurrentHashMap
+
+/**
+ * A member's (or user's) avatar, round, with a ring in their colour. Shows the
+ * System mascot while it loads and when it can't be, as the website falls
+ * back to the site icon.
+ */
+@Composable
+fun Avatar(url: String?, size: Dp, modifier: Modifier = Modifier, ring: Color? = null) {
+ val picture by rememberPicture(url)
+ val shape = modifier
+ .size(size)
+ .clip(CircleShape)
+ .let { if (ring != null) it.border(2.dp, ring, CircleShape) else it }
+ Image(
+ bitmap = picture ?: ImageBitmap.imageResource(R.drawable.mascot),
+ contentDescription = null,
+ modifier = shape,
+ contentScale = ContentScale.Crop,
+ )
+}
+
+/** An avatar as a bitmap (null until loaded, or if it can't be), for drawing on a canvas. */
+@Composable
+fun rememberPicture(url: String?): State<ImageBitmap?> {
+ val http = (LocalContext.current.applicationContext as SystemApp).api.http
+ return produceState(url?.let { cache.get(it) }, url) {
+ if (url != null && value == null) value = load(http, url)
+ }
+}
+
+/** Avatars fetched this run, scaled down; about 25 MB at most. */
+private val cache = object : LruCache<String, ImageBitmap>(24 * 1024 * 1024) {
+ override fun sizeOf(key: String, value: ImageBitmap) = value.width * value.height * 4
+}
+
+/** Requests in flight, so a grid of the same avatar fetches it once. */
+private val pending = ConcurrentHashMap<String, CompletableDeferred<ImageBitmap?>>()
+
+private suspend fun load(http: OkHttpClient, url: String): ImageBitmap? {
+ cache.get(url)?.let { return it }
+ val mine = CompletableDeferred<ImageBitmap?>()
+ val existing = pending.putIfAbsent(url, mine)
+ if (existing != null) return existing.await()
+ val result = withContext(Dispatchers.IO) {
+ runCatching {
+ http.newCall(Request.Builder().url(url).build()).execute().use { res ->
+ if (!res.isSuccessful) return@use null
+ val bytes = res.body?.bytes() ?: return@use null
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
+ var sample = 1
+ while (minOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= 256) sample *= 2
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
+ ?.asImageBitmap()
+ }
+ }.getOrNull()
+ }
+ result?.let { cache.put(url, it) }
+ mine.complete(result)
+ pending.remove(url)
+ return result
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/Components.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/Components.kt
new file mode 100644
index 0000000..3bd0a84
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/Components.kt
@@ -0,0 +1,289 @@
+@file:OptIn(ExperimentalMaterial3Api::class)
+
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.outlined.CheckCircle
+import androidx.compose.material.icons.outlined.Info
+import androidx.compose.material.icons.outlined.Report
+import androidx.compose.material.icons.outlined.Shield
+import androidx.compose.material.icons.outlined.WarningAmber
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.material3.TopAppBar
+import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import gay.doughmination.plural.data.MemberStatus
+import gay.doughmination.plural.data.MentalLevel
+import gay.doughmination.plural.data.MentalState
+import gay.doughmination.plural.data.findPrideFlag
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.time.format.FormatStyle
+
+/** The website's .panel: a raised card with a hairline border. */
+@Composable
+fun Panel(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
+ Column(
+ modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(16.dp))
+ .background(Raised)
+ .border(1.dp, Line, RoundedCornerShape(16.dp))
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ content = content,
+ )
+}
+
+/** A page's heading, as the website writes them: "// system.members" over a title. */
+@Composable
+fun PageHead(eyebrow: String, title: String, subtitle: String? = null) {
+ Column(Modifier.padding(bottom = 4.dp)) {
+ Text(eyebrow, style = Eyebrow)
+ Text(title, style = MaterialTheme.typography.headlineMedium)
+ subtitle?.let { Text(it, color = Muted, style = MaterialTheme.typography.bodyMedium) }
+ }
+}
+
+@Composable
+fun SectionTitle(text: String, colour: Color = TextColour) {
+ Text(text, style = MaterialTheme.typography.titleMedium, color = colour)
+}
+
+/** A pill, like the website's .chip; `active` fills it with the accent. */
+@Composable
+fun Chip(
+ text: String,
+ modifier: Modifier = Modifier,
+ active: Boolean = false,
+ tint: Color? = null,
+ leading: (@Composable () -> Unit)? = null,
+ onClick: (() -> Unit)? = null,
+) {
+ val shape = RoundedCornerShape(50)
+ val border = when {
+ active -> AccentLine
+ tint != null -> tint.copy(alpha = 0.5f)
+ else -> Line
+ }
+ Row(
+ modifier
+ .clip(shape)
+ .background(if (active) AccentDim else (tint?.copy(alpha = 0.12f) ?: Raised))
+ .border(1.dp, border, shape)
+ .let { if (onClick != null) it.clickable(onClick = onClick) else it }
+ .padding(horizontal = 10.dp, vertical = 5.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ leading?.invoke()
+ Text(
+ text,
+ fontSize = 13.sp,
+ color = if (active) Accent else TextColour,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+}
+
+/** A small accent badge ("fronting", "mutual", "Owner"). */
+@Composable
+fun Badge(text: String, accent: Boolean = true) {
+ Text(
+ text,
+ fontSize = 11.sp,
+ fontWeight = FontWeight.SemiBold,
+ color = if (accent) Accent else Muted,
+ modifier = Modifier
+ .clip(RoundedCornerShape(50))
+ .background(if (accent) AccentDim else Raised)
+ .border(1.dp, if (accent) AccentLine else Line, RoundedCornerShape(50))
+ .padding(horizontal = 8.dp, vertical = 2.dp),
+ )
+}
+
+/** A member's status note: emoji and text. */
+@Composable
+fun StatusTag(status: MemberStatus, modifier: Modifier = Modifier) {
+ Row(
+ modifier
+ .clip(RoundedCornerShape(8.dp))
+ .background(Raised)
+ .border(1.dp, Line, RoundedCornerShape(8.dp))
+ .padding(horizontal = 8.dp, vertical = 4.dp),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ status.emoji?.ifBlank { null }?.let { Text(it, fontSize = 13.sp) }
+ Text(status.text, fontSize = 13.sp, color = TextColour, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+/** A pride flag as a small striped swatch; the accent when the label isn't a known flag. */
+@Composable
+fun PrideSwatch(label: String, modifier: Modifier = Modifier) {
+ val stripes = findPrideFlag(label)?.stripes
+ val shape = RoundedCornerShape(3.dp)
+ Box(
+ modifier
+ .size(width = 18.dp, height = 12.dp)
+ .clip(shape)
+ .border(1.dp, Line, shape)
+ .background(
+ if (stripes == null) {
+ Brush.verticalGradient(listOf(Accent, Accent))
+ } else {
+ // Hard bands, top to bottom, like the website's gradient.
+ val stops = stripes.flatMapIndexed { index, colour ->
+ listOf(index.toFloat() / stripes.size to colour, (index + 1f) / stripes.size to colour)
+ }
+ Brush.verticalGradient(*stops.toTypedArray())
+ },
+ ),
+ )
+}
+
+/** The colour the website gives a mental-state level: ok, warn or bad. */
+fun mentalColour(level: String): Color = when (MentalLevel.of(level)?.severity) {
+ 1 -> Warn
+ 2 -> Bad
+ else -> Ok
+}
+
+fun mentalIcon(level: String): ImageVector = when (MentalLevel.of(level)) {
+ MentalLevel.Safe -> Icons.Outlined.CheckCircle
+ MentalLevel.Unstable -> Icons.Outlined.WarningAmber
+ MentalLevel.Idealizing -> Icons.Outlined.Info
+ MentalLevel.SelfHarming -> Icons.Outlined.Report
+ MentalLevel.HighlyAtRisk -> Icons.Outlined.Shield
+ null -> Icons.Outlined.Info
+}
+
+/** The home page's mental-state banner. */
+@Composable
+fun MentalBanner(state: MentalState, modifier: Modifier = Modifier) {
+ val colour = mentalColour(state.level)
+ val label = MentalLevel.of(state.level)?.label ?: state.level
+ val shape = RoundedCornerShape(16.dp)
+ Row(
+ modifier
+ .fillMaxWidth()
+ .clip(shape)
+ .background(colour.copy(alpha = 0.08f))
+ .border(1.dp, colour.copy(alpha = 0.45f), shape)
+ .padding(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ ) {
+ Icon(mentalIcon(state.level), contentDescription = null, tint = colour, modifier = Modifier.size(30.dp))
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Row {
+ Text("status: ", color = Muted, fontFamily = Eyebrow.fontFamily, fontSize = 14.sp)
+ Text("[ $label ]", color = colour, fontWeight = FontWeight.SemiBold, fontFamily = Eyebrow.fontFamily, fontSize = 14.sp)
+ }
+ state.notes?.ifBlank { null }?.let { Text(it, style = MaterialTheme.typography.bodyMedium) }
+ formatTime(state.updatedAt)?.let {
+ Text("last_updated: $it", color = Muted, fontSize = 12.sp, fontFamily = Eyebrow.fontFamily)
+ }
+ }
+ }
+}
+
+/** A plain notice line, like the website's .notice. */
+@Composable
+fun Notice(text: String, error: Boolean = false, modifier: Modifier = Modifier) {
+ val colour = if (error) Bad else Muted
+ Text(
+ text,
+ color = if (error) Bad else TextColour,
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(colour.copy(alpha = 0.08f))
+ .border(1.dp, colour.copy(alpha = 0.35f), RoundedCornerShape(12.dp))
+ .padding(12.dp),
+ )
+}
+
+/** The top bar for screens opened on top of a tab. */
+@Composable
+fun BackBar(title: String, onBack: () -> Unit, actions: @Composable () -> Unit = {}) {
+ TopAppBar(
+ title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ navigationIcon = {
+ IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") }
+ },
+ actions = { actions() },
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
+ )
+}
+
+/** A labelled row of content in a form. */
+@Composable
+fun Field(label: String, hint: String? = null, content: @Composable () -> Unit) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(label, style = MaterialTheme.typography.labelLarge, color = Muted)
+ content()
+ hint?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = Muted) }
+ }
+}
+
+@Composable
+fun Gap(height: Int = 8) = Spacer(Modifier.height(height.dp))
+
+@Composable
+fun HGap(width: Int = 8) = Spacer(Modifier.width(width.dp))
+
+private val timeFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT)
+
+/** An ISO timestamp from the API in the phone's time zone and locale. */
+fun formatTime(iso: String?): String? = iso?.let {
+ runCatching { timeFormat.format(Instant.parse(it).atZone(ZoneId.systemDefault())) }.getOrNull()
+}
+
+/** "for 3h 12m", from an ISO timestamp to now. */
+fun sinceText(iso: String?): String? = iso?.let {
+ runCatching {
+ val seconds = (System.currentTimeMillis() - Instant.parse(it).toEpochMilli()) / 1000
+ duration(seconds.toDouble())
+ }.getOrNull()
+}
+
+/** The website's duration format: "3h 12m", or "2d 4h" past a day. */
+fun duration(seconds: Double): String {
+ val hours = (seconds / 3600).toLong()
+ val minutes = ((seconds % 3600) / 60).toLong()
+ return if (hours > 24) "${hours / 24}d ${hours % 24}h" else "${hours}h ${minutes}m"
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/HomeScreen.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/HomeScreen.kt
new file mode 100644
index 0000000..a4ba904
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/HomeScreen.kt
@@ -0,0 +1,321 @@
+@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
+
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.GridItemSpan
+import androidx.compose.foundation.lazy.grid.LazyGridItemSpanScope
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Close
+import androidx.compose.material.icons.outlined.FilterList
+import androidx.compose.material.icons.outlined.Search
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.OutlinedTextFieldDefaults
+import androidx.compose.material3.Text
+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import gay.doughmination.plural.data.Live
+import gay.doughmination.plural.data.Member
+import gay.doughmination.plural.data.memberColour
+import gay.doughmination.plural.data.readableOnDark
+
+/** "Untagged", the website's tag filter for members with no tags. */
+const val UNTAGGED = "untagged"
+
+/** The members page: mental state, who's fronting, then everyone, searchable and filterable. */
+@Composable
+fun HomeScreen(vm: SystemViewModel) {
+ var filtersOpen by rememberSaveable { mutableStateOf(false) }
+
+ val tags = remember(vm.members) { vm.members.flatMap { it.tags }.distinct().sortedBy { it.lowercase() } }
+ val identities = remember(vm.members) { vm.members.flatMap { it.pride }.distinct().sortedBy { it.lowercase() } }
+ val shown = remember(vm.members, vm.search, vm.tagFilter, vm.identityFilter) {
+ val query = vm.search.trim().lowercase()
+ vm.members.filter { member ->
+ if (query.isNotEmpty()) {
+ val named = member.shownName.lowercase().contains(query)
+ val tagged = member.tags.any { it.lowercase().contains(query) }
+ if (!named && !tagged) return@filter false
+ }
+ when (val tag = vm.tagFilter) {
+ null -> {}
+ UNTAGGED -> if (member.tags.isNotEmpty()) return@filter false
+ else -> if (tag !in member.tags) return@filter false
+ }
+ vm.identityFilter?.let { if (it !in member.pride) return@filter false }
+ true
+ }
+ }
+ val fronting = vm.fronters?.members.orEmpty()
+ val activeFilters = (if (vm.tagFilter != null) 1 else 0) + (if (vm.identityFilter != null) 1 else 0)
+
+ if (vm.loading && vm.members.isEmpty()) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
+ return
+ }
+
+ PullToRefreshBox(isRefreshing = vm.refreshing, onRefresh = { vm.refresh() }, modifier = Modifier.fillMaxSize()) {
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(minSize = 150.dp),
+ contentPadding = PaddingValues(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ val full: LazyGridItemSpanScope.() -> GridItemSpan = { GridItemSpan(maxLineSpan) }
+
+ if (vm.liveStatus == Live.Status.Reconnecting) {
+ item(span = full) { Notice("Live updates disconnected. Reconnecting…", error = true) }
+ }
+ vm.loadError?.let { error ->
+ item(span = full) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Notice(error, error = true)
+ OutlinedButton(onClick = { vm.refresh() }) { Text("Try again") }
+ }
+ }
+ }
+
+ item(span = full) { PageHead("// system.members", "System Members") }
+
+ vm.mental?.let { state -> item(span = full) { MentalBanner(state) } }
+
+ if (fronting.isNotEmpty()) {
+ item(span = full) { FrontingPanel(vm, fronting) }
+ }
+
+ item(span = full) {
+ Controls(vm, activeFilters) { filtersOpen = true }
+ }
+
+ if (shown.isEmpty() && vm.members.isNotEmpty()) {
+ item(span = full) {
+ Panel {
+ Text(
+ if (vm.search.isNotBlank() || activeFilters > 0) "No members found matching your criteria." else "No members available.",
+ color = Muted,
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (vm.search.isNotBlank()) OutlinedButton(onClick = { vm.search = "" }) { Text("Clear search") }
+ if (activeFilters > 0) OutlinedButton(onClick = vm::clearFilters) { Text("Clear filters") }
+ }
+ }
+ }
+ }
+
+ items(shown, key = { it.id }) { member ->
+ MemberCard(member, fronting = vm.isFronting(member), activeTag = vm.tagFilter, onTag = { tag ->
+ vm.tagFilter = if (vm.tagFilter == tag) null else tag
+ }) { vm.open(Screen.MemberPage(member.id)) }
+ }
+ }
+ }
+
+ if (filtersOpen) {
+ ModalBottomSheet(onDismissRequest = { filtersOpen = false }) {
+ Column(Modifier.padding(horizontal = 20.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text("Filters", style = MaterialTheme.typography.titleLarge)
+ Text("Tag", color = Muted, style = MaterialTheme.typography.labelLarge)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Chip("All", active = vm.tagFilter == null) { vm.tagFilter = null }
+ tags.forEach { tag -> Chip(tag, active = vm.tagFilter == tag) { vm.tagFilter = if (vm.tagFilter == tag) null else tag } }
+ Chip("Untagged", active = vm.tagFilter == UNTAGGED) {
+ vm.tagFilter = if (vm.tagFilter == UNTAGGED) null else UNTAGGED
+ }
+ }
+ if (identities.isNotEmpty()) {
+ Text("Identity", color = Muted, style = MaterialTheme.typography.labelLarge)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Chip("All", active = vm.identityFilter == null) { vm.identityFilter = null }
+ identities.forEach { identity ->
+ Chip(identity, active = vm.identityFilter == identity, leading = { PrideSwatch(identity) }) {
+ vm.identityFilter = if (vm.identityFilter == identity) null else identity
+ }
+ }
+ }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (activeFilters > 0) OutlinedButton(onClick = vm::clearFilters) { Text("Clear filters") }
+ Button(onClick = { filtersOpen = false }) { Text("Done") }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun FrontingPanel(vm: SystemViewModel, fronting: List<Member>) {
+ Panel {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ SectionTitle(if (fronting.size > 1) "Currently Co-fronting" else "Currently Fronting")
+ sinceText(vm.fronters?.timestamp)?.let {
+ HGap()
+ Text("for $it", color = Muted, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+ fronting.forEach { member ->
+ // The socket's members lack tags and status; the full list has them.
+ val full = vm.member(member.id) ?: member
+ val colour = memberColour(full.color) ?: Accent
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .clickable { vm.open(Screen.MemberPage(full.id)) }
+ .padding(vertical = 4.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Avatar(full.avatarUrl, 56.dp, ring = colour)
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.weight(1f)) {
+ Text(
+ full.shownName,
+ color = readableOnDark(full.color, Accent),
+ style = MaterialTheme.typography.titleMedium,
+ )
+ full.pronouns?.ifBlank { null }?.let { Text(it, color = Muted, fontSize = 13.sp) }
+ if (full.tags.isNotEmpty()) {
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ full.tags.sortedBy { it.lowercase() }.forEach { tag ->
+ Chip(tag, active = vm.tagFilter == tag) { vm.tagFilter = if (vm.tagFilter == tag) null else tag }
+ }
+ }
+ }
+ full.status?.let { StatusTag(it) }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun Controls(vm: SystemViewModel, activeFilters: Int, openFilters: () -> Unit) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedTextField(
+ value = vm.search,
+ onValueChange = { vm.search = it },
+ placeholder = { Text("Search members...") },
+ leadingIcon = { Icon(Icons.Outlined.Search, contentDescription = null) },
+ trailingIcon = {
+ if (vm.search.isNotEmpty()) {
+ IconButton(onClick = { vm.search = "" }) { Icon(Icons.Outlined.Close, contentDescription = "Clear search") }
+ }
+ },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
+ shape = RoundedCornerShape(14.dp),
+ colors = OutlinedTextFieldDefaults.colors(unfocusedBorderColor = Line),
+ modifier = Modifier.weight(1f),
+ )
+ FilledTonalButton(onClick = openFilters, contentPadding = PaddingValues(horizontal = 14.dp, vertical = 12.dp)) {
+ Icon(Icons.Outlined.FilterList, contentDescription = null, modifier = Modifier.size(18.dp))
+ HGap(6)
+ Text(if (activeFilters > 0) "Filters · $activeFilters" else "Filters")
+ }
+ }
+ if (activeFilters > 0) {
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ vm.tagFilter?.let { tag ->
+ Chip("tag: ${if (tag == UNTAGGED) "untagged" else tag} ✕", active = true) { vm.tagFilter = null }
+ }
+ vm.identityFilter?.let { identity ->
+ Chip("identity: $identity ✕", active = true, leading = { PrideSwatch(identity) }) { vm.identityFilter = null }
+ }
+ }
+ }
+ }
+}
+
+/** A member in the grid: avatar, name in their colour, pronouns, two tags, status. */
+@Composable
+private fun MemberCard(member: Member, fronting: Boolean, activeTag: String?, onTag: (String) -> Unit, onClick: () -> Unit) {
+ val colour = memberColour(member.color) ?: Accent
+ val shape = RoundedCornerShape(16.dp)
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .clip(shape)
+ .background(if (fronting) colour.copy(alpha = 0.10f) else Raised)
+ .border(if (fronting) 2.dp else 1.dp, if (fronting) colour.copy(alpha = 0.8f) else Line, shape)
+ .clickable(onClick = onClick)
+ .padding(14.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ Box {
+ Avatar(member.avatarUrl, 84.dp, ring = colour.copy(alpha = 0.9f))
+ if (fronting) {
+ Box(Modifier.align(Alignment.BottomEnd)) { Badge("fronting") }
+ }
+ }
+ Text(
+ member.shownName,
+ color = readableOnDark(member.color, TextColour),
+ fontWeight = FontWeight.SemiBold,
+ fontSize = 16.sp,
+ textAlign = TextAlign.Center,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ member.pronouns?.ifBlank { null }?.let {
+ Text(it, color = Muted, fontSize = 12.sp, textAlign = TextAlign.Center, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ if (member.tags.isNotEmpty()) {
+ FlowRow(
+ horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ member.tags.sortedBy { it.lowercase() }.take(2).forEach { tag ->
+ Chip(tag, active = activeTag == tag) { onTag(tag) }
+ }
+ if (member.tags.size > 2) {
+ Text("+${member.tags.size - 2}", color = Muted, fontSize = 12.sp, modifier = Modifier.align(Alignment.CenterVertically))
+ }
+ }
+ }
+ member.status?.let { StatusTag(it) }
+ }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/MemberScreen.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/MemberScreen.kt
new file mode 100644
index 0000000..aa035ee
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/MemberScreen.kt
@@ -0,0 +1,144 @@
+@file:OptIn(ExperimentalLayoutApi::class)
+
+package gay.doughmination.plural.ui
+
+import android.content.Intent
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Share
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import gay.doughmination.plural.BuildConfig
+import gay.doughmination.plural.data.Member
+import gay.doughmination.plural.data.crushesOf
+import gay.doughmination.plural.data.memberColour
+import gay.doughmination.plural.data.partnersOf
+import gay.doughmination.plural.data.readableOnDark
+import java.net.URLEncoder
+
+/** One member's page, as the website's /[member_id]. */
+@Composable
+fun MemberScreen(vm: SystemViewModel, id: String) {
+ val member = vm.member(id)
+ val context = LocalContext.current
+
+ Column(Modifier.fillMaxSize()) {
+ BackBar(member?.shownName ?: "Member", onBack = vm::back) {
+ if (member != null) {
+ IconButton(onClick = {
+ val url = "${BuildConfig.SITE_URL}/${URLEncoder.encode(member.key, "UTF-8").replace("+", "%20")}"
+ val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, url)
+ context.startActivity(Intent.createChooser(send, null))
+ }) { Icon(Icons.Outlined.Share, contentDescription = "Share") }
+ }
+ }
+ if (member == null) {
+ Box(Modifier.fillMaxSize().padding(16.dp)) {
+ Panel {
+ Text("Error 404", style = Eyebrow)
+ Text("Member not found", style = MaterialTheme.typography.headlineSmall)
+ Text("This member could not be found in the Doughmination System.", color = Muted)
+ }
+ }
+ return
+ }
+ MemberDetails(vm, member)
+ }
+}
+
+@Composable
+private fun MemberDetails(vm: SystemViewModel, member: Member) {
+ val colour = memberColour(member.color) ?: Accent
+ val nameColour = readableOnDark(member.color, TextColour)
+ val partners = remember(member, vm.relationships, vm.members) { partnersOf(member, vm.relationships, vm.members) }
+ val crushes = remember(member, vm.relationships, vm.members) { crushesOf(member, vm.relationships, vm.members) }
+
+ Column(
+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ Panel(Modifier) {
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Avatar(member.avatarUrl, 132.dp, ring = colour)
+ Text(member.shownName, color = nameColour, style = MaterialTheme.typography.headlineMedium, textAlign = TextAlign.Center)
+ member.pronouns?.ifBlank { null }?.let { Text(it, color = Muted) }
+ if (vm.isFronting(member)) Badge("fronting now")
+ member.status?.let { StatusTag(it) }
+ }
+
+ member.description?.ifBlank { null }?.let { about ->
+ Gap(4)
+ SectionTitle("About", nameColour)
+ SelectionContainer { Text(about, style = MaterialTheme.typography.bodyLarge) }
+ }
+
+ if (member.tags.isNotEmpty()) {
+ Gap(4)
+ SectionTitle("Tags", nameColour)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ member.tags.forEach { tag -> Chip(tag, tint = colour) { vm.filterBy(tag = tag) } }
+ }
+ }
+
+ if (member.pride.isNotEmpty()) {
+ Gap(4)
+ SectionTitle("Pride", nameColour)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ member.pride.forEach { identity ->
+ Chip(identity, leading = { PrideSwatch(identity) }) { vm.filterBy(identity = identity) }
+ }
+ }
+ }
+
+ if (partners.isNotEmpty()) {
+ Gap(4)
+ SectionTitle("Partners", nameColour)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ partners.forEach { partner -> PersonChip(partner) { vm.open(Screen.MemberPage(partner.id)) } }
+ }
+ }
+
+ if (crushes.isNotEmpty()) {
+ Gap(4)
+ SectionTitle("Crushes", nameColour)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ crushes.forEach { crush ->
+ PersonChip(crush.member, badge = if (crush.mutual) "mutual" else null) {
+ vm.open(Screen.MemberPage(crush.member.id))
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** Another member as a chip with their avatar, like the website's partner chips. */
+@Composable
+fun PersonChip(member: Member, badge: String? = null, onClick: () -> Unit) {
+ Chip(
+ if (badge != null) "${member.shownName} · $badge" else member.shownName,
+ leading = { Avatar(member.avatarUrl, 22.dp) },
+ tint = memberColour(member.color),
+ onClick = onClick,
+ )
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/MetricsScreen.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/MetricsScreen.kt
new file mode 100644
index 0000000..ad8311b
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/MetricsScreen.kt
@@ -0,0 +1,212 @@
+@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
+
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Text
+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import gay.doughmination.plural.data.MemberMetric
+import gay.doughmination.plural.data.Timeframe
+
+/** The website's chart colours, in order. */
+private val Palette = listOf(
+ 0xFF8B5CF6, 0xFFEC4899, 0xFFF59E0B, 0xFF10B981, 0xFF3B82F6,
+ 0xFFEF4444, 0xFF14B8A6, 0xFFF97316, 0xFF6366F1, 0xFF84CC16,
+).map { Color(it) }
+
+/** The website's /user/metrics: switching and fronting over the last 30 days. */
+@Composable
+fun MetricsScreen(vm: SystemViewModel) {
+ var timeframeName by rememberSaveable { mutableStateOf(Timeframe.Week.name) }
+ val timeframe = Timeframe.valueOf(timeframeName)
+
+ val fronting = vm.frontingMetrics
+ val switches = vm.switchMetrics
+ // The ten members who fronted most in the chosen window.
+ val top = remember(fronting, timeframe) {
+ fronting?.members?.values.orEmpty().filter { it[timeframe] > 0 }.sortedByDescending { it[timeframe] }.take(10)
+ }
+ val topTotal = top.sumOf { it[timeframe] }
+
+ PullToRefreshBox(isRefreshing = vm.metricsLoading && fronting != null, onRefresh = vm::loadMetrics, modifier = Modifier.fillMaxSize()) {
+ Column(
+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ PageHead("// system.metrics", "Metrics", "System fronting and switching statistics")
+
+ vm.metricsError?.let {
+ Notice(it, error = true)
+ OutlinedButton(onClick = vm::loadMetrics) { Text("Try again") }
+ }
+
+ if (fronting == null && switches == null) {
+ if (vm.metricsLoading) {
+ Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
+ }
+ return@Column
+ }
+
+ Text("Timeframe", color = Muted, style = MaterialTheme.typography.labelLarge)
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Timeframe.entries.forEach { option ->
+ Chip(option.label, active = option == timeframe) { timeframeName = option.name }
+ }
+ }
+
+ switches?.let { s ->
+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Stat("Total switches", "${s.totalSwitches}", "Last 30 days", Modifier.weight(1f))
+ Stat("Avg per day", "%.1f".format(s.averagePerDay), "Switches per day", Modifier.weight(1f))
+ Stat("Selected", "${s[timeframe]}", timeframe.label, Modifier.weight(1f))
+ }
+ }
+
+ if (fronting != null && top.isNotEmpty()) {
+ Panel {
+ SectionTitle("Fronting time distribution")
+ Text("Top fronters for ${timeframe.label.lowercase()}", color = Muted, style = MaterialTheme.typography.bodySmall)
+ Donut(top.map { it[timeframe] / topTotal }, Modifier.align(Alignment.CenterHorizontally).size(200.dp))
+ top.forEachIndexed { index, member ->
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Box(Modifier.size(12.dp).clip(CircleShape).background(Palette[index % Palette.size]))
+ Text(member.shownName, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text("%.0f%%".format(member[timeframe] / topTotal * 100), color = Muted)
+ }
+ }
+ }
+ }
+
+ switches?.let { s ->
+ Panel {
+ SectionTitle("Switch frequency over time")
+ Text("Number of switches across different timeframes", color = Muted, style = MaterialTheme.typography.bodySmall)
+ val peak = maxOf(1, Timeframe.entries.maxOf { s[it] })
+ Row(
+ Modifier.fillMaxWidth().height(180.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.Bottom,
+ ) {
+ Timeframe.entries.forEach { option ->
+ Column(Modifier.weight(1f).fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Bottom) {
+ Text("${s[option]}", fontSize = 12.sp)
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .fillMaxHeight((s[option].toFloat() / peak * 0.8f).coerceAtLeast(0.01f))
+ .clip(RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp))
+ .background(if (option == timeframe) Accent else AccentLine),
+ )
+ Text(option.key, color = Muted, fontSize = 12.sp)
+ }
+ }
+ }
+ }
+ }
+
+ if (fronting != null && top.isNotEmpty()) {
+ Panel {
+ SectionTitle("Top fronters")
+ Text("Most active members for ${timeframe.label.lowercase()}", color = Muted, style = MaterialTheme.typography.bodySmall)
+ top.forEachIndexed { index, member -> Ranked(index + 1, member, member[timeframe], top.first()[timeframe]) }
+ }
+ } else if (fronting != null) {
+ Panel { Text("No fronting data available for the selected timeframe", color = Muted) }
+ }
+ }
+ }
+}
+
+@Composable
+private fun Stat(label: String, value: String, note: String, modifier: Modifier) {
+ Panel(modifier) {
+ Text(label.uppercase(), style = Eyebrow.copy(fontSize = 10.sp), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(value, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.SemiBold)
+ Text(note, color = Muted, fontSize = 11.sp, maxLines = 2)
+ }
+}
+
+/** Slices as arcs round one ring, like the website's stroke-dasharray donut. */
+@Composable
+private fun Donut(fractions: List<Double>, modifier: Modifier) {
+ Canvas(modifier.padding(8.dp)) {
+ val stroke = size.minDimension * 0.16f
+ val inset = stroke / 2
+ var start = -90f
+ fractions.forEachIndexed { index, fraction ->
+ val sweep = (fraction * 360).toFloat()
+ drawArc(
+ Palette[index % Palette.size],
+ startAngle = start,
+ sweepAngle = sweep,
+ useCenter = false,
+ topLeft = Offset(inset, inset),
+ size = Size(size.width - stroke, size.height - stroke),
+ style = Stroke(width = stroke),
+ )
+ start += sweep
+ }
+ }
+}
+
+@Composable
+private fun Ranked(rank: Int, member: MemberMetric, seconds: Double, best: Double) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("$rank", color = Accent, fontWeight = FontWeight.SemiBold, modifier = Modifier.size(width = 20.dp, height = 20.dp))
+ Avatar(member.avatarUrl, 34.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row {
+ Text(member.shownName, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
+ HGap(6)
+ Text(duration(seconds), color = Muted, fontSize = 12.sp)
+ }
+ Box(Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)).background(Line)) {
+ Box(
+ Modifier
+ .fillMaxWidth(if (best > 0) (seconds / best).toFloat().coerceIn(0f, 1f) else 0f)
+ .fillMaxHeight()
+ .clip(RoundedCornerShape(3.dp))
+ .background(Accent),
+ )
+ }
+ }
+ }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/RelationshipsScreen.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/RelationshipsScreen.kt
new file mode 100644
index 0000000..a9f5d56
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/RelationshipsScreen.kt
@@ -0,0 +1,300 @@
+@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
+
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableDoubleStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.PathEffect
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.drawscope.clipPath
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.res.imageResource
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.drawText
+import androidx.compose.ui.text.rememberTextMeasurer
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.IntSize
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import gay.doughmination.plural.R
+import gay.doughmination.plural.data.Couple
+import gay.doughmination.plural.data.Member
+import gay.doughmination.plural.data.Relationship
+import gay.doughmination.plural.data.find
+import gay.doughmination.plural.data.layout
+import gay.doughmination.plural.data.memberColour
+import gay.doughmination.plural.data.pairs
+import gay.doughmination.plural.data.project
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.sin
+
+/** The website's /relationships: the map, then everyone in pairs. */
+@Composable
+fun RelationshipsScreen(vm: SystemViewModel) {
+ val couples = remember(vm.relationships, vm.members) { pairs(vm.relationships, vm.members) }
+
+ PullToRefreshBox(isRefreshing = vm.refreshing, onRefresh = { vm.refresh() }, modifier = Modifier.fillMaxSize()) {
+ Column(
+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ PageHead("// system.relationships", "Relationship Map", "Who is dating who across the system")
+
+ if (couples.isEmpty()) {
+ Panel { Text(if (vm.loading) "Loading…" else "No relationships to show yet", color = Muted) }
+ return@Column
+ }
+
+ Panel {
+ RelationshipMap(vm.members, vm.relationships) { vm.open(Screen.MemberPage(it.id)) }
+ Text("Drag to turn it; tap someone to open their page.", color = Muted, style = MaterialTheme.typography.bodySmall)
+ }
+
+ Panel {
+ SectionTitle("Everyone, in pairs")
+ couples.forEach { couple -> CoupleRow(couple) { vm.open(Screen.MemberPage(it.id)) } }
+ }
+ }
+ }
+}
+
+@Composable
+private fun CoupleRow(couple: Couple, open: (Member) -> Unit) {
+ Column(Modifier.fillMaxWidth().padding(vertical = 4.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Who(couple.a, Modifier.weight(1f), open)
+ Badge(couple.label, accent = couple.edge.type != "crush")
+ Who(couple.b, Modifier.weight(1f), open, end = true)
+ }
+ couple.edge.since?.ifBlank { null }?.let {
+ Text("since $it", color = Muted, style = MaterialTheme.typography.bodySmall, modifier = Modifier.align(Alignment.CenterHorizontally))
+ }
+ }
+}
+
+@Composable
+private fun Who(member: Member, modifier: Modifier, open: (Member) -> Unit, end: Boolean = false) {
+ Row(
+ modifier.clip(RoundedCornerShape(10.dp)).clickable { open(member) }.padding(4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp, if (end) Alignment.End else Alignment.Start),
+ ) {
+ if (!end) Avatar(member.avatarUrl, 32.dp, ring = memberColour(member.color))
+ Text(member.shownName, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f, fill = false))
+ if (end) Avatar(member.avatarUrl, 32.dp, ring = memberColour(member.color))
+ }
+}
+
+// The website's RelationshipGraph.svelte, in its 720-unit square.
+private const val SIZE = 720f
+private const val RADIUS = 285.0
+private const val NODE_RADIUS = 26f
+private const val SPIN_PER_FRAME = 0.0025
+private const val DRAG_SPEED = 0.008
+
+private class Link(val edge: Relationship, val a: Int, val b: Int, val mutual: Boolean)
+
+/** The rotating 3D map: nodes are avatars, links lines; crushes dashed, with arrows. */
+@Composable
+fun RelationshipMap(members: List<Member>, relationships: List<Relationship>, open: (Member) -> Unit) {
+ val graph = remember(members, relationships) {
+ val nodes = mutableListOf<Member>()
+ fun indexOf(identifier: String): Int? {
+ val member = members.find(identifier) ?: return null
+ val index = nodes.indexOfFirst { it.id == member.id }
+ return if (index >= 0) index else { nodes += member; nodes.size - 1 }
+ }
+ val links = mutableListOf<Link>()
+ for (edge in relationships) {
+ val a = indexOf(edge.members.getOrNull(0) ?: continue) ?: continue
+ val b = indexOf(edge.members.getOrNull(1) ?: continue) ?: continue
+ if (a == b) continue
+ val reverse = links.indexOfFirst { edge.type == "crush" && it.edge.type == "crush" && it.a == b && it.b == a }
+ if (reverse >= 0) links[reverse] = Link(links[reverse].edge, links[reverse].a, links[reverse].b, true)
+ else links += Link(edge, a, b, false)
+ }
+ Triple(nodes.toList(), links.toList(), layout(nodes.size, links.map { it.a to it.b }, RADIUS))
+ }
+ val (nodes, links, points) = graph
+
+ var yaw by remember { mutableDoubleStateOf(0.6) }
+ var pitch by remember { mutableDoubleStateOf(-0.35) }
+ var dragging by remember { mutableStateOf(false) }
+
+ // A slow spin, paused while someone turns it by hand.
+ LaunchedEffect(Unit) {
+ while (true) withFrameNanos { if (!dragging) yaw += SPIN_PER_FRAME }
+ }
+
+ val fallback = ImageBitmap.imageResource(R.drawable.mascot)
+ val pictures = nodes.map { node -> key(node.id) { rememberPicture(node.avatarUrl) } }
+ val measurer = rememberTextMeasurer()
+ val density = LocalDensity.current
+ val labelStyle = TextStyle(fontSize = 11.sp, fontFamily = PlexSans, color = TextColour)
+
+ fun screen(index: Int, scale: Float): Placed {
+ val p = project(points[index], yaw, pitch, RADIUS)
+ return Placed(
+ x = (SIZE / 2 + p.x.toFloat()) * scale,
+ y = (SIZE / 2 + p.y.toFloat()) * scale,
+ r = NODE_RADIUS * p.scale.toFloat() * scale,
+ fade = 0.45f + 0.55f * p.depth.toFloat().coerceIn(0f, 1f),
+ depth = p.depth,
+ )
+ }
+
+ Canvas(
+ Modifier
+ .fillMaxWidth()
+ .aspectRatio(1f)
+ .pointerInput(nodes) {
+ detectDragGestures(
+ onDragStart = { dragging = true },
+ onDragEnd = { dragging = false },
+ onDragCancel = { dragging = false },
+ ) { change, amount ->
+ change.consume()
+ val dx = amount.x / density.density
+ val dy = amount.y / density.density
+ yaw += dx * DRAG_SPEED
+ pitch = (pitch - dy * DRAG_SPEED).coerceIn(-1.3, 1.3)
+ }
+ }
+ .pointerInput(nodes) {
+ detectTapGestures { tap ->
+ val scale = size.width / SIZE
+ // The front-most node under the finger.
+ nodes.indices
+ .map { it to screen(it, scale) }
+ .filter { (_, at) -> hypot(tap.x - at.x, tap.y - at.y) <= at.r + 8.dp.toPx() }
+ .maxByOrNull { (_, at) -> at.depth }
+ ?.let { (index, _) -> open(nodes[index]) }
+ }
+ },
+ ) {
+ val scale = size.width / SIZE
+ val placed = nodes.indices.map { screen(it, scale) }
+
+ drawCircle(
+ Brush.radialGradient(listOf(Accent.copy(alpha = 0.12f), Color.Transparent), center = center, radius = (RADIUS.toFloat() + 60) * scale),
+ radius = (RADIUS.toFloat() + 60) * scale,
+ )
+
+ // Back to front, so nearer lines and avatars cover further ones.
+ links.sortedBy { placed[it.a].depth + placed[it.b].depth }.forEach { link ->
+ drawLink(link, placed[link.a], placed[link.b], scale)
+ }
+ nodes.indices.sortedBy { placed[it].depth }.forEach { index ->
+ val at = placed[index]
+ val node = nodes[index]
+ drawAvatar(pictures[index].value ?: fallback, at, memberColour(node.color) ?: Accent)
+ // Names for the nearer half, so the back doesn't turn to noise.
+ if (at.depth > 0.35) {
+ val text = measurer.measure(node.shownName, labelStyle, maxLines = 1, overflow = TextOverflow.Ellipsis, constraints = androidx.compose.ui.unit.Constraints(maxWidth = (120 * scale).toInt().coerceAtLeast(1)))
+ drawText(
+ text,
+ topLeft = Offset(at.x - text.size.width / 2f, at.y + at.r + 3.dp.toPx()),
+ alpha = at.fade,
+ )
+ }
+ }
+ }
+}
+
+private class Placed(val x: Float, val y: Float, val r: Float, val fade: Float, val depth: Double)
+
+private fun DrawScope.drawLink(link: Link, from: Placed, to: Placed, scale: Float) {
+ val crush = link.edge.type == "crush"
+ val colour = if (crush) Warn else Accent
+ val alpha = (from.fade + to.fade) / 2
+ val length = max(hypot(to.x - from.x, to.y - from.y), 1f)
+ // Stop a crush short of the avatar, so its arrow isn't hidden under it.
+ val endGap = if (crush) (to.r + 5 * scale) / length else 0f
+ val startGap = if (link.mutual) (from.r + 5 * scale) / length else 0f
+ val start = Offset(from.x + (to.x - from.x) * startGap, from.y + (to.y - from.y) * startGap)
+ val end = Offset(to.x - (to.x - from.x) * endGap, to.y - (to.y - from.y) * endGap)
+
+ drawLine(
+ colour.copy(alpha = alpha),
+ start,
+ end,
+ strokeWidth = 2.2f * scale * 1.6f,
+ cap = StrokeCap.Round,
+ pathEffect = if (crush) PathEffect.dashPathEffect(floatArrayOf(5f * scale * 1.6f, 6f * scale * 1.6f)) else null,
+ )
+ if (crush) {
+ arrow(end, atan2(end.y - start.y, end.x - start.x), colour.copy(alpha = alpha), scale)
+ if (link.mutual) arrow(start, atan2(start.y - end.y, start.x - end.x), colour.copy(alpha = alpha), scale)
+ }
+}
+
+private fun DrawScope.arrow(tip: Offset, angle: Float, colour: Color, scale: Float) {
+ val size = 9f * scale * 1.6f
+ val path = Path().apply {
+ moveTo(tip.x, tip.y)
+ lineTo(tip.x - size * cos(angle - 0.45f), tip.y - size * sin(angle - 0.45f))
+ lineTo(tip.x - size * cos(angle + 0.45f), tip.y - size * sin(angle + 0.45f))
+ close()
+ }
+ drawPath(path, colour)
+}
+
+private fun DrawScope.drawAvatar(image: ImageBitmap, at: Placed, ring: Color) {
+ val clip = Path().apply { addOval(Rect(Offset(at.x, at.y), at.r)) }
+ // Centre-crop to a square, as object-fit: cover would.
+ val side = min(image.width, image.height)
+ val src = IntOffset((image.width - side) / 2, (image.height - side) / 2)
+ clipPath(clip) {
+ drawRect(Bg, topLeft = Offset(at.x - at.r, at.y - at.r), size = androidx.compose.ui.geometry.Size(at.r * 2, at.r * 2))
+ drawImage(
+ image,
+ srcOffset = src,
+ srcSize = IntSize(side, side),
+ dstOffset = IntOffset((at.x - at.r).toInt(), (at.y - at.r).toInt()),
+ dstSize = IntSize((at.r * 2).toInt().coerceAtLeast(1), (at.r * 2).toInt().coerceAtLeast(1)),
+ alpha = at.fade,
+ )
+ }
+ drawCircle(ring.copy(alpha = at.fade), radius = at.r, center = Offset(at.x, at.y), style = Stroke(width = 2.dp.toPx()))
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/SystemViewModel.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/SystemViewModel.kt
new file mode 100644
index 0000000..b22a882
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/SystemViewModel.kt
@@ -0,0 +1,393 @@
+package gay.doughmination.plural.ui
+
+import android.app.Application
+import android.content.Context
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import gay.doughmination.plural.SystemApp
+import gay.doughmination.plural.data.Api
+import gay.doughmination.plural.data.ApiException
+import gay.doughmination.plural.data.FrontingMetrics
+import gay.doughmination.plural.data.Fronters
+import gay.doughmination.plural.data.Live
+import gay.doughmination.plural.data.Member
+import gay.doughmination.plural.data.MentalState
+import gay.doughmination.plural.data.Relationship
+import gay.doughmination.plural.data.SwitchMetrics
+import gay.doughmination.plural.data.User
+import kotlinx.coroutines.async
+import kotlinx.coroutines.launch
+
+/** Where the app is. The first four are the tabs; the rest open on top of one. */
+sealed interface Screen {
+ data object Members : Screen
+ data object Relationships : Screen
+ data object Metrics : Screen
+ data object Account : Screen
+
+ data class MemberPage(val id: String) : Screen
+ data object EditProfile : Screen
+ data object Switch : Screen
+ data object Mental : Screen
+ data object Status : Screen
+ data object Tags : Screen
+ data object Pride : Screen
+ data object ManageRelationships : Screen
+ data object Users : Screen
+
+ val isTab: Boolean get() = this == Members || this == Relationships || this == Metrics || this == Account
+}
+
+/** A short note for the snackbar. */
+data class Flash(val text: String, val error: Boolean, val id: Long = System.nanoTime())
+
+/** Everything the screens show and do; one per activity. */
+class SystemViewModel(application: Application) : AndroidViewModel(application) {
+ private val app = application as SystemApp
+ private val api: Api get() = app.api
+
+ // ---- Public data, kept live by the socket ---------------------------------
+
+ /** A–Z by the name people see, as the website sorts them. */
+ var members by mutableStateOf<List<Member>>(emptyList())
+ private set
+ var fronters by mutableStateOf<Fronters?>(null)
+ private set
+ var mental by mutableStateOf<MentalState?>(null)
+ private set
+ var relationships by mutableStateOf<List<Relationship>>(emptyList())
+ private set
+ var frontingMetrics by mutableStateOf<FrontingMetrics?>(null)
+ private set
+ var switchMetrics by mutableStateOf<SwitchMetrics?>(null)
+ private set
+ var metricsError by mutableStateOf<String?>(null)
+ private set
+ var metricsLoading by mutableStateOf(false)
+ private set
+
+ /** True until the first load finishes, either way. */
+ var loading by mutableStateOf(true)
+ private set
+ var refreshing by mutableStateOf(false)
+ private set
+ /** Set when nothing could be loaded at all. */
+ var loadError by mutableStateOf<String?>(null)
+ private set
+
+ var liveStatus by mutableStateOf(Live.Status.Connecting)
+ private set
+
+ // ---- The home screen's search and filters (the website keeps these in the URL) ----
+
+ var search by mutableStateOf("")
+ var tagFilter by mutableStateOf<String?>(null)
+ var identityFilter by mutableStateOf<String?>(null)
+
+ // ---- Who's signed in ------------------------------------------------------
+
+ var signedIn by mutableStateOf(app.tokens.token != null)
+ private set
+ var user by mutableStateOf<User?>(null)
+ private set
+ var signingIn by mutableStateOf(false)
+ private set
+
+ val isAdmin: Boolean get() = user?.let { it.isAdmin || it.isOwner } == true
+ val isOwner: Boolean get() = user?.isOwner == true
+
+ // ---- Admin pages ------------------------------------------------------------
+
+ /** A change is being sent; buttons wait for it. */
+ var busy by mutableStateOf(false)
+ private set
+ var users by mutableStateOf<List<User>>(emptyList())
+ private set
+
+ // ---- Navigation and messages ------------------------------------------------
+
+ var stack by mutableStateOf<List<Screen>>(listOf(Screen.Members))
+ private set
+ val screen: Screen get() = stack.last()
+ val tab: Screen get() = stack.first()
+
+ var flash by mutableStateOf<Flash?>(null)
+ private set
+
+ init {
+ viewModelScope.launch { app.live.status.collect { liveStatus = it } }
+ viewModelScope.launch {
+ app.live.events.collect { event ->
+ when (event) {
+ Live.Event.FrontersChanged, Live.Event.MentalStateChanged -> refresh(quiet = true)
+ Live.Event.Reconnected -> refresh(quiet = true)
+ Live.Event.ForceRefresh -> {
+ refresh(quiet = true)
+ if (frontingMetrics != null) loadMetrics()
+ if (signedIn) loadUser()
+ }
+ }
+ }
+ }
+ viewModelScope.launch {
+ app.signedIn.collect { value ->
+ if (!value && signedIn) {
+ signedIn = false
+ user = null
+ }
+ }
+ }
+ refresh(quiet = true)
+ if (signedIn) loadUser()
+ }
+
+ // ---- Loading --------------------------------------------------------------
+
+ /**
+ * Reloads what the home, member and relationship pages show. Each part
+ * stands alone: one failing keeps what was there, as the website does.
+ */
+ fun refresh(quiet: Boolean = false) {
+ if (!quiet) refreshing = true
+ viewModelScope.launch {
+ val newMembers = async { runCatching { api.members() } }
+ val newFronters = async { runCatching { api.fronters() } }
+ val newSystem = async { runCatching { api.system() } }
+ val newRelationships = async { runCatching { api.relationships() } }
+
+ newMembers.await().onSuccess { list -> members = list.sortedBy { it.shownName.lowercase() } }
+ newFronters.await().onSuccess { fronters = it }
+ newSystem.await().onSuccess { mental = it.mentalState }
+ newRelationships.await().onSuccess { relationships = it }
+
+ val failure = newMembers.await().exceptionOrNull()
+ loadError = if (failure != null && members.isEmpty()) failure.message ?: "Couldn't load the system." else null
+ if (failure != null && members.isNotEmpty() && !quiet) show(failure.message ?: "Couldn't refresh.", error = true)
+ loading = false
+ refreshing = false
+ }
+ }
+
+ fun loadMetrics() {
+ metricsLoading = true
+ viewModelScope.launch {
+ val fronting = async { runCatching { api.frontingMetrics(30) } }
+ val switches = async { runCatching { api.switchMetrics(30) } }
+ fronting.await().onSuccess { frontingMetrics = it }
+ switches.await().onSuccess { switchMetrics = it }
+ val failure = fronting.await().exceptionOrNull() ?: switches.await().exceptionOrNull()
+ metricsError = when {
+ failure == null -> null
+ (failure as? ApiException)?.status == 401 -> "Metrics are not available publicly yet"
+ else -> failure.message ?: "Failed to fetch metrics"
+ }
+ metricsLoading = false
+ }
+ }
+
+ fun member(id: String): Member? = members.firstOrNull { it.id == id }
+
+ fun isFronting(member: Member): Boolean =
+ fronters?.members.orEmpty().any { it.id == member.id || (it.name != null && it.name == member.name) }
+
+ // ---- Navigation -------------------------------------------------------------
+
+ fun selectTab(tab: Screen) {
+ stack = listOf(tab)
+ if (tab == Screen.Metrics && frontingMetrics == null && !metricsLoading) loadMetrics()
+ }
+
+ fun open(screen: Screen) {
+ if (screen == Screen.Users) loadUsers()
+ stack = stack + screen
+ }
+
+ fun back() {
+ if (stack.size > 1) stack = stack.dropLast(1)
+ }
+
+ /** From a member page's tag or pride chip: the home screen, filtered by it. */
+ fun filterBy(tag: String? = null, identity: String? = null) {
+ tagFilter = tag
+ identityFilter = identity
+ search = ""
+ stack = listOf(Screen.Members)
+ }
+
+ fun clearFilters() {
+ tagFilter = null
+ identityFilter = null
+ }
+
+ fun show(text: String, error: Boolean = false) {
+ flash = Flash(text, error)
+ }
+
+ // ---- Sign-in ------------------------------------------------------------------
+
+ fun startLogin(context: Context) {
+ signingIn = true
+ app.auth.start(context)
+ }
+
+ /** The browser tab came back with gay.doughmination.plural://auth?code=… */
+ fun finishLogin(code: String) {
+ signingIn = true
+ viewModelScope.launch {
+ try {
+ app.auth.finish(code)
+ signedIn = true
+ app.setSignedIn(true)
+ loadUser()
+ selectTab(Screen.Account)
+ } catch (e: Exception) {
+ show(e.message ?: "Sign-in failed. Please try again.", error = true)
+ } finally {
+ signingIn = false
+ }
+ }
+ }
+
+ /** …or with ?error=… */
+ fun loginFailed(message: String) {
+ signingIn = false
+ app.tokens.pendingVerifier = null
+ show(message, error = true)
+ }
+
+ /** The browser tab was closed without finishing. */
+ fun loginAbandoned() {
+ signingIn = false
+ }
+
+ private fun loadUser() {
+ viewModelScope.launch {
+ try {
+ user = api.userInfo()
+ } catch (e: ApiException) {
+ if (e.status == 401) {
+ signedIn = false
+ user = null
+ }
+ }
+ }
+ }
+
+ fun signOut() {
+ viewModelScope.launch {
+ app.auth.signOut()
+ app.setSignedIn(false)
+ signedIn = false
+ user = null
+ users = emptyList()
+ stack = listOf(Screen.Account)
+ show("Signed out")
+ }
+ }
+
+ // ---- Changes ----------------------------------------------------------------
+
+ /** Runs a change, says how it went, then reloads. Returns whether it worked. */
+ private fun change(done: String, after: suspend () -> Unit = { refresh(quiet = true) }, then: () -> Unit = {}, action: suspend () -> Unit) {
+ if (busy) return
+ busy = true
+ viewModelScope.launch {
+ try {
+ action()
+ show(done)
+ after()
+ then()
+ } catch (e: Exception) {
+ show(e.message ?: "Something went wrong", error = true)
+ } finally {
+ busy = false
+ }
+ }
+ }
+
+ fun switchTo(memberIds: List<String>) {
+ val count = memberIds.size
+ change("Switched to $count member${if (count != 1) "s" else ""}") { api.multiSwitch(memberIds) }
+ }
+
+ fun setMental(level: String, notes: String) =
+ change("Mental state updated") { api.setMentalState(level, notes.trim().ifBlank { null }) }
+
+ fun setStatus(member: Member, text: String, emoji: String) =
+ change("Status updated") { api.setStatus(member.key, text.trim(), emoji.ifBlank { null }) }
+
+ fun clearStatus(member: Member) = change("Status cleared") { api.clearStatus(member.key) }
+
+ fun addTag(member: Member, tag: String) = change("Tag added") { api.addTag(member.key, tag.trim()) }
+
+ fun removeTag(member: Member, tag: String) = change("Tag removed") { api.removeTag(member.key, tag) }
+
+ fun addPride(member: Member, identity: String) = change("Pride identity added") { api.addPride(member.key, identity) }
+
+ fun removePride(member: Member, identity: String) =
+ change("Pride identity removed") { api.removePride(member.key, identity) }
+
+ fun addRelationship(a: Member, b: Member, type: String, since: String, then: () -> Unit) =
+ change("Relationship added", then = then) { api.addRelationship(a.key, b.key, type, since.trim().ifBlank { null }) }
+
+ fun removeRelationship(edge: Relationship) = change("Relationship removed") { api.removeRelationship(edge.id) }
+
+ fun forceRefresh() = change("Refresh sent to everyone connected", after = {}) { api.forceRefresh() }
+
+ fun saveProfile(displayName: String, avatarUrl: String, email: String) {
+ val me = user ?: return
+ change("Profile updated", after = { loadUser() }) {
+ api.updateUser(
+ me.id,
+ Api.UserUpdate(
+ displayName = displayName.trim().ifBlank { null },
+ avatarUrl = avatarUrl.trim().ifBlank { null },
+ email = Api.Optional.Set(email.trim().ifBlank { null }),
+ ),
+ )
+ }
+ }
+
+ // ---- Users (owner) ------------------------------------------------------------
+
+ fun loadUsers() {
+ viewModelScope.launch {
+ try {
+ users = api.users().sortedBy { it.username.lowercase() }
+ } catch (e: Exception) {
+ show(e.message ?: "Failed to fetch users", error = true)
+ }
+ }
+ }
+
+ fun createUser(input: Api.UserCreate, then: () -> Unit) =
+ change("User created. They can sign in once they authenticate with SSO under this username.", after = { loadUsers() }, then = then) {
+ api.createUser(input)
+ }
+
+ fun updateUser(target: User, displayName: String, email: String, avatarUrl: String, admin: Boolean, pet: Boolean, then: () -> Unit) {
+ // Only the owner may change someone's email, and only when it changed (as on the website).
+ val emailChange = if (isOwner && email.trim() != (target.email ?: "")) {
+ Api.Optional.Set(email.trim().ifBlank { null })
+ } else {
+ Api.Optional.Unset
+ }
+ change("Updated @${target.username}", after = { loadUsers(); if (target.id == user?.id) loadUser() }, then = then) {
+ api.updateUser(
+ target.id,
+ Api.UserUpdate(
+ displayName = displayName.trim().ifBlank { null },
+ avatarUrl = avatarUrl.trim().ifBlank { null },
+ email = emailChange,
+ isAdmin = admin,
+ isPet = pet,
+ ),
+ )
+ }
+ }
+
+ fun deleteUser(target: User) = change("User deleted", after = { loadUsers() }) { api.deleteUser(target.id) }
+}
diff --git a/plural/app/src/main/java/gay/doughmination/plural/ui/Theme.kt b/plural/app/src/main/java/gay/doughmination/plural/ui/Theme.kt
new file mode 100644
index 0000000..e808bff
--- /dev/null
+++ b/plural/app/src/main/java/gay/doughmination/plural/ui/Theme.kt
@@ -0,0 +1,136 @@
+package gay.doughmination.plural.ui
+
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Typography
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.Font
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.sp
+import gay.doughmination.plural.R
+
+// The website's tokens (system/src/lib/styles/theme.css), which are
+// doughmination.gay's.
+val Bg = Color(0xFF0B0A0D)
+val TextColour = Color(0xFFECE9EF)
+val Muted = Color(0xFFA49EAB)
+val Accent = Color(0xFFEB459E)
+val AccentDim = Color(0xFFEB459E).copy(alpha = 0.14f)
+val AccentLine = Color(0xFFEB459E).copy(alpha = 0.4f)
+val Ok = Color(0xFF7FD98B)
+val Warn = Color(0xFFF2C46D)
+val Bad = Color(0xFFFF8A9A)
+/** A card on the backdrop, like --raised. */
+val Raised = Color.White.copy(alpha = 0.035f)
+/** Hairline borders, like --line. */
+val Line = Color.White.copy(alpha = 0.09f)
+
+/** IBM Plex Sans, as on the website (the same files as TTF, shared with Inbox). */
+val PlexSans = FontFamily(
+ Font(R.font.ibm_plex_sans_regular, FontWeight.Normal),
+ Font(R.font.ibm_plex_sans_medium, FontWeight.Medium),
+ Font(R.font.ibm_plex_sans_semibold, FontWeight.SemiBold),
+ Font(R.font.ibm_plex_sans_bold, FontWeight.Bold),
+)
+
+private fun TextStyle.plex() = copy(fontFamily = PlexSans)
+
+private val typography = Typography().run {
+ Typography(
+ displayLarge = displayLarge.plex(),
+ displayMedium = displayMedium.plex(),
+ displaySmall = displaySmall.plex(),
+ headlineLarge = headlineLarge.plex(),
+ headlineMedium = headlineMedium.plex().copy(fontWeight = FontWeight.SemiBold),
+ headlineSmall = headlineSmall.plex().copy(fontWeight = FontWeight.SemiBold),
+ titleLarge = titleLarge.plex().copy(fontWeight = FontWeight.SemiBold),
+ titleMedium = titleMedium.plex().copy(fontWeight = FontWeight.SemiBold),
+ titleSmall = titleSmall.plex(),
+ bodyLarge = bodyLarge.plex(),
+ bodyMedium = bodyMedium.plex(),
+ bodySmall = bodySmall.plex(),
+ labelLarge = labelLarge.plex(),
+ labelMedium = labelMedium.plex(),
+ labelSmall = labelSmall.plex(),
+ )
+}
+
+/** The website's mono eyebrows ("// system.members"). */
+val Eyebrow = TextStyle(
+ fontFamily = FontFamily.Monospace,
+ fontSize = 12.sp,
+ letterSpacing = 0.5.sp,
+ color = Accent,
+)
+
+private val colours = darkColorScheme(
+ primary = Accent,
+ onPrimary = Color(0xFF1A0611),
+ primaryContainer = Color(0xFF3A1A2C),
+ onPrimaryContainer = Color(0xFFFFD8EA),
+ secondaryContainer = Color(0xFF2A1A24),
+ onSecondaryContainer = Color(0xFFFFD8EA),
+ // Screens sit on the Backdrop, so these are see-through. Sheets, menus and
+ // dialogs use the surfaceContainer colours and stay opaque.
+ background = Color.Transparent,
+ onBackground = TextColour,
+ surface = Color.Transparent,
+ onSurface = TextColour,
+ surfaceVariant = Color(0xFF1C1A20),
+ onSurfaceVariant = Muted,
+ surfaceContainerLowest = Bg,
+ surfaceContainerLow = Color(0xFF131116),
+ surfaceContainer = Color(0xFF17151B),
+ surfaceContainerHigh = Color(0xFF1E1B22),
+ surfaceContainerHighest = Color(0xFF26222B),
+ outline = Color(0xFF3A3640),
+ outlineVariant = Color(0xFF26222B),
+ error = Bad,
+)
+
+/** The site's wallpaper behind every screen, dimmed the way the web does it. */
+@Composable
+fun Backdrop(modifier: Modifier = Modifier) {
+ Box(modifier.fillMaxSize().background(Bg)) {
+ Image(
+ painterResource(R.drawable.background),
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ alpha = 0.45f,
+ modifier = Modifier.fillMaxSize(),
+ )
+ Box(
+ Modifier.fillMaxSize().background(
+ Brush.verticalGradient(0f to Bg.copy(alpha = 0.55f), 0.5f to Bg.copy(alpha = 0.85f), 1f to Bg),
+ ),
+ )
+ Box(
+ Modifier.fillMaxSize().drawBehind {
+ drawRect(
+ Brush.radialGradient(
+ listOf(Accent.copy(alpha = 0.12f), Color.Transparent),
+ center = Offset(size.width * 0.2f, size.height * 0.15f),
+ radius = size.maxDimension * 0.6f,
+ ),
+ )
+ },
+ )
+ }
+}
+
+@Composable
+fun SystemTheme(content: @Composable () -> Unit) =
+ MaterialTheme(colorScheme = colours, typography = typography, content = content)
diff --git a/plural/app/src/main/res/drawable-nodpi/background.webp b/plural/app/src/main/res/drawable-nodpi/background.webp
new file mode 100644
index 0000000..1f56761
Binary files /dev/null and b/plural/app/src/main/res/drawable-nodpi/background.webp differ
diff --git a/plural/app/src/main/res/drawable-nodpi/mascot.png b/plural/app/src/main/res/drawable-nodpi/mascot.png
new file mode 100644
index 0000000..dd98cea
Binary files /dev/null and b/plural/app/src/main/res/drawable-nodpi/mascot.png differ
diff --git a/plural/app/src/main/res/drawable/ic_launcher_foreground.xml b/plural/app/src/main/res/drawable/ic_launcher_foreground.xml
index 03e59e5..cfdd344 100644
--- a/plural/app/src/main/res/drawable/ic_launcher_foreground.xml
+++ b/plural/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -1,12 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Placeholder doughnut until the app gets its real icon. -->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="108dp"
- android:height="108dp"
- android:viewportWidth="108"
- android:viewportHeight="108">
- <path
- android:fillColor="#F5A9C8"
- android:fillType="evenOdd"
- android:pathData="M54,32a22,22 0,1 1,0 44a22,22 0,1 1,0 -44zM54,46a8,8 0,1 0,0 16a8,8 0,1 0,0 -16z" />
-</vector>
+<!-- The Doughmination System mascot (system/static/favicon.png), inset to sit
+ inside the ~66dp circle every launcher mask shows. -->
+<inset xmlns:android="http://schemas.android.com/apk/res/android"
+ android:drawable="@drawable/mascot"
+ android:inset="18%" />
diff --git a/plural/app/src/main/res/font/ibm_plex_sans_bold.ttf b/plural/app/src/main/res/font/ibm_plex_sans_bold.ttf
new file mode 100644
index 0000000..c864a80
Binary files /dev/null and b/plural/app/src/main/res/font/ibm_plex_sans_bold.ttf differ
diff --git a/plural/app/src/main/res/font/ibm_plex_sans_medium.ttf b/plural/app/src/main/res/font/ibm_plex_sans_medium.ttf
new file mode 100644
index 0000000..94738b8
Binary files /dev/null and b/plural/app/src/main/res/font/ibm_plex_sans_medium.ttf differ
diff --git a/plural/app/src/main/res/font/ibm_plex_sans_regular.ttf b/plural/app/src/main/res/font/ibm_plex_sans_regular.ttf
new file mode 100644
index 0000000..a4f4148
Binary files /dev/null and b/plural/app/src/main/res/font/ibm_plex_sans_regular.ttf differ
diff --git a/plural/app/src/main/res/font/ibm_plex_sans_semibold.ttf b/plural/app/src/main/res/font/ibm_plex_sans_semibold.ttf
new file mode 100644
index 0000000..454f3d4
Binary files /dev/null and b/plural/app/src/main/res/font/ibm_plex_sans_semibold.ttf differ
diff --git a/plural/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/plural/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
index 5c84730..a8a8fa5 100644
--- a/plural/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+++ b/plural/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -2,5 +2,4 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
- <monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
diff --git a/plural/app/src/main/res/values/strings.xml b/plural/app/src/main/res/values/strings.xml
index 500c9df..3d9b606 100644
--- a/plural/app/src/main/res/values/strings.xml
+++ b/plural/app/src/main/res/values/strings.xml
@@ -1,3 +1,3 @@
<resources>
- <string name="app_name">Plural</string>
+ <string name="app_name">System</string>
</resources>
diff --git a/plural/app/src/main/res/values/themes.xml b/plural/app/src/main/res/values/themes.xml
index c2f0dd7..a411fb3 100644
--- a/plural/app/src/main/res/values/themes.xml
+++ b/plural/app/src/main/res/values/themes.xml
@@ -1,5 +1,11 @@
<resources>
- <!-- Compose draws everything; this only covers the window before it does. -->
- <style name="Theme.App" parent="android:Theme.Material.Light.NoActionBar" />
- <color name="ic_launcher_background">#1E1B2E</color>
+ <!-- Compose draws everything; this only covers the window before it does,
+ in the site's dark background so launching doesn't flash white. -->
+ <style name="Theme.App" parent="android:Theme.Material.NoActionBar">
+ <item name="android:windowBackground">@color/bg</item>
+ <item name="android:statusBarColor">@android:color/transparent</item>
+ <item name="android:navigationBarColor">@android:color/transparent</item>
+ </style>
+ <color name="bg">#0B0A0D</color>
+ <color name="ic_launcher_background">#0B0A0D</color>
</resources>