Merge branch 'ios-google-signin'

This commit is contained in:
Olof Hedman
2025-09-20 16:41:41 +02:00
25 changed files with 1054 additions and 35 deletions

View File

@@ -9,6 +9,7 @@ import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import app.klottr.util.AuthShared
object Auth {
@@ -50,6 +51,8 @@ object Auth {
email = sp.getString(KEY_EMAIL, null)
_loggedIn.value = idToken != null
_email.value = email
// Keep shared KMP state in sync (for iOS/Compose common UI)
AuthShared.applyLogin(idToken, userId, email)
}
/** Spara kontoinfo efter lyckad inloggning och uppdatera flöden. */
@@ -68,6 +71,8 @@ object Auth {
}
_loggedIn.value = token != null
_email.value = mail
// Sync shared KMP state
AuthShared.applyLogin(token, sub, mail)
if (token == null) {
Log.w("Klottr/Auth", "ID‑token är null efter sign‑in. Kontrollera WEB_CLIENT_ID i Auth.kt och på servern.")
}
@@ -82,6 +87,8 @@ object Auth {
signInClient(ctx).signOut()
_loggedIn.value = false
_email.value = null
// Clear shared KMP state too
AuthShared.clearAll()
}
/**

View File

@@ -6,7 +6,7 @@
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects

View File

@@ -6,6 +6,11 @@
objectVersion = 77;
objects = {
/* Begin PBXBuildFile section */
412CF4A32E719E7D00EADB15 /* shared.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = 412CF4A22E719E7D00EADB15 /* shared.xcframework */; };
412CF4B12E71B7C300EADB15 /* GoogleSignIn in Frameworks */ = {isa = PBXBuildFile; productRef = 412CF4B02E71B7C300EADB15 /* GoogleSignIn */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
412CF4592E7037D800EADB15 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
@@ -27,11 +32,25 @@
412CF4482E7037D700EADB15 /* Klottr.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Klottr.app; sourceTree = BUILT_PRODUCTS_DIR; };
412CF4582E7037D800EADB15 /* KlottrTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = KlottrTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
412CF4622E7037D800EADB15 /* KlottrUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = KlottrUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
412CF4A22E719E7D00EADB15 /* shared.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = shared.xcframework; path = "/Users/olle/Documents/git-personal/klottr/shared/build/XCFrameworks/release/shared.xcframework"; sourceTree = "<absolute>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
412CF4B42E71C14D00EADB15 /* Exceptions for "Klottr" folder in "Klottr" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
);
target = 412CF4472E7037D700EADB15 /* Klottr */;
};
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
412CF44A2E7037D700EADB15 /* Klottr */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
412CF4B42E71C14D00EADB15 /* Exceptions for "Klottr" folder in "Klottr" target */,
);
path = Klottr;
sourceTree = "<group>";
};
@@ -52,6 +71,8 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
412CF4A32E719E7D00EADB15 /* shared.xcframework in Frameworks */,
412CF4B12E71B7C300EADB15 /* GoogleSignIn in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -75,9 +96,11 @@
412CF43F2E7037D600EADB15 = {
isa = PBXGroup;
children = (
412CF4A22E719E7D00EADB15 /* shared.xcframework */,
412CF44A2E7037D700EADB15 /* Klottr */,
412CF45B2E7037D800EADB15 /* KlottrTests */,
412CF4652E7037D800EADB15 /* KlottrUITests */,
412CF4AF2E71B7C300EADB15 /* Frameworks */,
412CF4492E7037D700EADB15 /* Products */,
);
sourceTree = "<group>";
@@ -92,6 +115,13 @@
name = Products;
sourceTree = "<group>";
};
412CF4AF2E71B7C300EADB15 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -112,6 +142,7 @@
);
name = Klottr;
packageProductDependencies = (
412CF4B02E71B7C300EADB15 /* GoogleSignIn */,
);
productName = Klottr;
productReference = 412CF4482E7037D700EADB15 /* Klottr.app */;
@@ -195,6 +226,9 @@
);
mainGroup = 412CF43F2E7037D600EADB15;
minimizedProjectReferenceProxies = 1;
packageReferences = (
412CF4A62E71AF4C00EADB15 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */,
);
preferredProjectObjectVersion = 77;
productRefGroup = 412CF4492E7037D700EADB15 /* Products */;
projectDirPath = "";
@@ -398,8 +432,10 @@
DEVELOPMENT_ASSET_PATHS = "\"Klottr/Preview Content\"";
DEVELOPMENT_TEAM = 9LY47TPGT7;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
FRAMEWORK_SEARCH_PATHS = "";
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = Klottr/Info.plist;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = NO;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
@@ -409,7 +445,7 @@
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = se.ointressant.Klottr;
PRODUCT_BUNDLE_IDENTIFIER = app.klottr;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
@@ -427,8 +463,10 @@
DEVELOPMENT_ASSET_PATHS = "\"Klottr/Preview Content\"";
DEVELOPMENT_TEAM = 9LY47TPGT7;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
FRAMEWORK_SEARCH_PATHS = "";
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = Klottr/Info.plist;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = NO;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
@@ -438,7 +476,7 @@
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = se.ointressant.Klottr;
PRODUCT_BUNDLE_IDENTIFIER = app.klottr;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
@@ -558,6 +596,25 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
412CF4A62E71AF4C00EADB15 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/google/GoogleSignIn-iOS";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 9.0.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
412CF4B02E71B7C300EADB15 /* GoogleSignIn */ = {
isa = XCSwiftPackageProductDependency;
package = 412CF4A62E71AF4C00EADB15 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */;
productName = GoogleSignIn;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 412CF4402E7037D600EADB15 /* Project object */;
}

View File

@@ -0,0 +1,69 @@
{
"originHash" : "68aa00e3cba36db2e0a76f54dbc84d1f079d8aa9a19bfa9fce02d6286bd620b7",
"pins" : [
{
"identity" : "app-check",
"kind" : "remoteSourceControl",
"location" : "https://github.com/google/app-check.git",
"state" : {
"revision" : "61b85103a1aeed8218f17c794687781505fbbef5",
"version" : "11.2.0"
}
},
{
"identity" : "appauth-ios",
"kind" : "remoteSourceControl",
"location" : "https://github.com/openid/AppAuth-iOS.git",
"state" : {
"revision" : "145104f5ea9d58ae21b60add007c33c1cc0c948e",
"version" : "2.0.0"
}
},
{
"identity" : "googlesignin-ios",
"kind" : "remoteSourceControl",
"location" : "https://github.com/google/GoogleSignIn-iOS",
"state" : {
"revision" : "3996d908c7b3ce8a87d39c808f9a6b2a08fbe043",
"version" : "9.0.0"
}
},
{
"identity" : "googleutilities",
"kind" : "remoteSourceControl",
"location" : "https://github.com/google/GoogleUtilities.git",
"state" : {
"revision" : "60da361632d0de02786f709bdc0c4df340f7613e",
"version" : "8.1.0"
}
},
{
"identity" : "gtm-session-fetcher",
"kind" : "remoteSourceControl",
"location" : "https://github.com/google/gtm-session-fetcher.git",
"state" : {
"revision" : "a2ab612cb980066ee56d90d60d8462992c07f24b",
"version" : "3.5.0"
}
},
{
"identity" : "gtmappauth",
"kind" : "remoteSourceControl",
"location" : "https://github.com/google/GTMAppAuth.git",
"state" : {
"revision" : "56e0ccf09a6dd29dc7e68bdf729598240ca8aa16",
"version" : "5.0.0"
}
},
{
"identity" : "promises",
"kind" : "remoteSourceControl",
"location" : "https://github.com/google/promises.git",
"state" : {
"revision" : "540318ecedd63d883069ae7f1ed811a2df00b6ac",
"version" : "2.4.0"
}
}
],
"version" : 3
}

View File

@@ -0,0 +1,31 @@
//
// AppDelegate.swift
// Klottr
//
// Created by Olof Hedman on 2025-09-10.
//
// iosApp/AppDelegate.swift
import UIKit
import GoogleSignIn
import shared
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
PlatformAuthStorage.shared.install(delegate: KeychainStorage())
return true
}
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if GIDSignIn.sharedInstance.handle(url) { return true }
return false
}
}

View File

@@ -0,0 +1,38 @@
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "1.000",
"green" : "1.000",
"red" : "1.000"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0.000",
"green" : "0.000",
"red" : "0.000"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -5,20 +5,30 @@
//Created by Olof Hedman on 2025-09-09.
//
import shared
import SwiftUI
struct ContentView: View {
var sharedPing = SharedPing()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
Text(sharedPing.ping())
Button("Tap me") {
var result = sharedPing.ping()
NSLog("Ping result: \(result)")
}
}
.padding()
}
}
#Preview {
ContentView()
}

View File

@@ -0,0 +1,63 @@
//
// GoogleAutIOS.swift
// Klottr
//
// Created by Olof Hedman on 2025-09-10.
//
// iosApp/GoogleAuthIOS.swift
import UIKit
import GoogleSignIn
import shared // Kotlin framework from :shared
enum GoogleAuthError: Error { case noPresenter }
enum GoogleAuthIOS {
/// Optional: reads client IDs from Info.plist and sets configuration.
static func configureFromPlist() {
if let clientID = Bundle.main.object(forInfoDictionaryKey: "GIDClientID") as? String {
let serverID = Bundle.main.object(forInfoDictionaryKey: "GIDServerClientID") as? String
GIDSignIn.sharedInstance.configuration = GIDConfiguration(
clientID: clientID,
serverClientID: serverID
)
}
}
/// Interactive sign-in. Call from a button handler.
@MainActor
static func signIn(presenting: UIViewController) async throws {
let result = try await GIDSignIn.sharedInstance.signIn(withPresenting: presenting) // iOS
let user = try await result.user.refreshTokensIfNeeded()
let idToken = user.idToken?.tokenString
let sub = user.userID
let email = user.profile?.email
AuthShared.shared.applyLogin(token: idToken, sub: sub, mail: email)
}
/// Silent restore. Call on app start.
@MainActor
static func restorePreviousSignIn() async {
do {
if GIDSignIn.sharedInstance.hasPreviousSignIn() {
let user = try await GIDSignIn.sharedInstance.restorePreviousSignIn()
let refreshed = try await user.refreshTokensIfNeeded()
AuthShared.shared.applyLogin(
token: refreshed.idToken?.tokenString,
sub: refreshed.userID,
mail: refreshed.profile?.email
)
} else {
AuthShared.shared.loadFromStorage() // falls back to saved ID token/email
}
} catch {
AuthShared.shared.loadFromStorage()
}
}
static func signOut() {
GIDSignIn.sharedInstance.signOut()
AuthShared.shared.clearAll()
}
}

View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.508890452239-66lqrsbphlmqltb6aoe3c0d6dlgtjse8</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>UILaunchScreen</key>
<dict>
<!-- Optional image in your asset catalog -->
<!-- <key>UIImageName</key><string>LaunchScreenLogo</string> -->
<!-- Solid background from a Color Set named LaunchScreenBackground -->
<key>UIColorName</key><string>LaunchScreenBackground</string>
<!-- Safe default -->
<key>UIImageRespectsSafeAreaInsets</key><true/>
</dict>
<key>GIDClientID</key>
<string>508890452239-66lqrsbphlmqltb6aoe3c0d6dlgtjse8.apps.googleusercontent.com</string>
<key>GIDServerClientID</key>
<string>508890452239-5hdoedc9b4rk3k5mmru176lj7f04135r.apps.googleusercontent.com</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
</dict>
</array>
</dict>
</dict>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,57 @@
//
// KeychainStorage.swift
// Klottr
//
// Created by Olof Hedman on 2025-09-10.
//
// iosApp/KeychainStorage.swift
import Foundation
import Security
import shared // your XCFramework module name
final class KeychainStorage: NSObject, AuthStorageDelegate {
private let service = "app.klottr.auth"
func get(key: String) -> String? {
let q: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne
]
var out: AnyObject?
let status = SecItemCopyMatching(q as CFDictionary, &out)
guard status == errSecSuccess, let data = out as? Data else { return nil }
return String(data: data, encoding: .utf8)
}
func set(key: String, value: String?) {
let base: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key
]
if value == nil {
SecItemDelete(base as CFDictionary)
return
}
let attrs = [kSecValueData as String: value!.data(using: .utf8)!]
let status = SecItemUpdate(base as CFDictionary, attrs as CFDictionary)
if status == errSecItemNotFound {
var add = base
add[kSecValueData as String] = value!.data(using: .utf8)!
SecItemAdd(add as CFDictionary, nil)
}
}
func clear() {
let q: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service
]
SecItemDelete(q as CFDictionary)
}
}

View File

@@ -7,11 +7,14 @@
import SwiftUI
@main
struct KlottrApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
//@main
//struct KlottrApp: App {
// // Make AppDelegate participate in the SwiftUI lifecycle
// @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
//
// var body: some Scene {
// WindowGroup {
// ContentView()
// }
// }
//}

View File

@@ -0,0 +1,38 @@
//
// SceneDelegate.swift
// Klottr
//
// Created by Olof Hedman on 2025-09-17.
//
import UIKit
import shared
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
let root = MainKt.MainViewController() // Compose VC
let window = UIWindow(windowScene: windowScene)
window.rootViewController = root
self.window = window
window.makeKeyAndVisible()
// If you need to kick off sign-in at launch, do it here:
DispatchQueue.main.async {
Task {
do {
try await GoogleAuthIOS.signIn(presenting: root)
} catch {
NSLog("Sign In Error: \(error)")
}
}
}
}
}

View File

@@ -50,6 +50,7 @@ kotlin {
iosX64 {
binaries.framework {
baseName = xcfName
isStatic = true
xcf.add(this)
}
}
@@ -57,6 +58,7 @@ kotlin {
iosArm64 {
binaries.framework {
baseName = xcfName
isStatic = true
xcf.add(this)
}
}
@@ -64,6 +66,7 @@ kotlin {
iosSimulatorArm64 {
binaries.framework {
baseName = xcfName
isStatic = true
xcf.add(this)
}
}
@@ -91,6 +94,10 @@ kotlin {
// Lämna AndroidX Compose BOM/runtimes utanför :shared.
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material)
implementation(compose.material3)
// Material Icons (Icons.Filled.*, Icons.Outlined.*)
implementation(compose.materialIconsExtended)
// för Compose i :shared (Android-del)
// OBS: Dessa AndroidX Compose-rader ska förbli utkommenterade i :shared.

View File

@@ -0,0 +1,14 @@
// shared/src/androidMain/kotlin/app/klottr/util/PlatformAuthStorage.android.kt
package app.klottr.util
/** In-memory stub; Android keeps its own SharedPreferences today. */
actual object PlatformAuthStorage {
private val mem = mutableMapOf<String, String>()
actual fun get(key: String) = mem[key]
actual fun set(key: String, value: String?) {
if (value == null) mem.remove(key) else mem[key] = value
}
actual fun clear() = mem.clear()
actual fun install(delegate: AuthStorageDelegate) { /* no-op on Android */ }
}

View File

@@ -1,30 +1,56 @@
package app.klottr.util
import android.text.format.DateFormat
import android.os.Build
import java.text.DateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
// Android-actual: samma beteende som tidigare.
actual fun formatRelativeOrTime(ms: Long): String {
val calNow = Calendar.getInstance()
val calTime = Calendar.getInstance().apply { timeInMillis = ms }
val locale: Locale = Locale.getDefault()
val date = Date(ms)
val sameYear = calNow.get(Calendar.YEAR) == calTime.get(Calendar.YEAR)
val sameDay = sameYear &&
calNow.get(Calendar.DAY_OF_YEAR) == calTime.get(Calendar.DAY_OF_YEAR)
// Detect same day / yesterday once.
val nowCal = Calendar.getInstance()
val thatCal = Calendar.getInstance().apply { timeInMillis = ms }
val yesterday = sameYear &&
calNow.get(Calendar.DAY_OF_YEAR) - calTime.get(Calendar.DAY_OF_YEAR) == 1
val sameDay =
nowCal.get(Calendar.YEAR) == thatCal.get(Calendar.YEAR) &&
nowCal.get(Calendar.DAY_OF_YEAR) == thatCal.get(Calendar.DAY_OF_YEAR)
val yestCal = Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -1) }
val yesterday =
yestCal.get(Calendar.YEAR) == thatCal.get(Calendar.YEAR) &&
yestCal.get(Calendar.DAY_OF_YEAR) == thatCal.get(Calendar.DAY_OF_YEAR)
if (Build.VERSION.SDK_INT >= 24) {
// API 24+: Use ICU for truly localized "Today/Yesterday" + locale-correct joining.
val timeStr = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(date)
val rfmt = android.icu.text.RelativeDateTimeFormatter.getInstance(locale)
return when {
sameDay -> {
"idag " + DateFormat.format("HH:mm", ms).toString()
val day = rfmt.format(
android.icu.text.RelativeDateTimeFormatter.Direction.THIS,
android.icu.text.RelativeDateTimeFormatter.AbsoluteUnit.DAY
)
rfmt.combineDateAndTime(day, timeStr)
}
yesterday -> {
"igår " + DateFormat.format("HH:mm", ms).toString()
val day = rfmt.format(
android.icu.text.RelativeDateTimeFormatter.Direction.LAST,
android.icu.text.RelativeDateTimeFormatter.AbsoluteUnit.DAY
)
rfmt.combineDateAndTime(day, timeStr)
}
else -> {
val pattern = if (sameYear) "d MMM HH:mm" else "yyyy-MM-dd HH:mm"
DateFormat.format(pattern, ms).toString()
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, locale)
.format(date)
}
}
} else {
// < API 24: Fallback to localized date+time (no ICU-relative words available without Context).
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, locale)
.format(date)
}
}

View File

@@ -0,0 +1,363 @@
// :shared/src/commonMain/kotlin/app/klottr/KlottrRoot.kt
package app.klottr
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Map
import androidx.compose.material.icons.filled.NearMe
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun KlottrRoot(
onRequestPerms: () -> Unit = {},
onLogin: () -> Unit = {},
onLogout: () -> Unit = {}
) {
val scope = rememberCoroutineScope()
// --- Settings/state (kept local; wire to SettingsStore later) ----------------------
var night by remember { mutableStateOf(false) }
var showCoords by remember { mutableStateOf(false) }
var showKlotter by remember { mutableStateOf(true) }
var showWiki by remember { mutableStateOf(true) }
var showDm by remember { mutableStateOf(true) }
var showFornsok by remember { mutableStateOf(true) }
var wikiRadius by remember { mutableStateOf(500) }
var dmRadius by remember { mutableStateOf(500) }
var fornsokRadius by remember { mutableStateOf(500) }
var satellite by remember { mutableStateOf(false) }
var onlyNew by remember { mutableStateOf(false) }
// --- Top-level UI mode flags (dialogs/sheets) -------------------------------------
var showWrite by remember { mutableStateOf(false) }
var showNearby by remember { mutableStateOf(false) }
var showMap by remember { mutableStateOf(false) }
var showSettings by remember { mutableStateOf(false) }
var showLoginRequired by remember { mutableStateOf(false) }
var showAbout by remember { mutableStateOf(false) }
// --- Auth (local stub; replace with shared Auth later) ----------------------------
var loggedIn by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
// TODO(shared Auth): collect Auth.loggedIn and refresh silently.
// val logged by Auth.loggedIn.collectAsState(false)
// Auth.refreshSilently(<platformCtx>) { }
}
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text("") },
actions = {
IconButton(onClick = { showAbout = true }) {
Icon(imageVector = Icons.Filled.Info, contentDescription = "Om")
}
IconButton(onClick = { showSettings = true }) {
Icon(imageVector = Icons.Filled.Settings, contentDescription = "Inställningar")
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
// --- Quick actions (Write / Nearby / Map) ---------------------------------
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = {
if (!loggedIn) {
showLoginRequired = true
} else {
showWrite = true
}
}
) {
Icon(Icons.Filled.Edit, contentDescription = null)
Spacer(Modifier.padding(2.dp))
Text("Klottra")
}
Button(
onClick = {
// TODO(location): fetch current/last known location via expect/actual.
// val gp = LocationProvider.currentOrLastKnown()
showNearby = true
}
) {
Icon(Icons.Filled.NearMe, contentDescription = null)
Spacer(Modifier.padding(2.dp))
Text("Närliggande")
}
Button(
onClick = {
// TODO(map): present map dialog (UIKitView on iOS; GoogleMap on Android).
showMap = true
}
) {
Icon(Icons.Filled.Map, contentDescription = null)
Spacer(Modifier.padding(2.dp))
Text("Karta")
}
}
Spacer(Modifier.height(8.dp))
// --- Filters row -----------------------------------------------------------
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
FilterChip(
selected = showKlotter,
onClick = { showKlotter = !showKlotter },
label = { Text("Klotter") }
)
FilterChip(
selected = showWiki,
onClick = { showWiki = !showWiki },
label = { Text("Wikipedia") }
)
FilterChip(
selected = showDm,
onClick = { showDm = !showDm },
label = { Text("Digitalt Museum") }
)
FilterChip(
selected = showFornsok,
onClick = { showFornsok = !showFornsok },
label = { Text("Fornsök") }
)
}
Spacer(Modifier.height(12.dp))
// --- Latest / Found list ---------------------------------------------------
// NOTE: Hook the real data once shared store + use-cases are wired on iOS.
// val entries = remember(foundRefresh, showKlotter, showWiki, showDm, showFornsok) {
// FoundStore.getAllFiltered(onlyNew, showKlotter, showWiki, showDm, showFornsok)
// }
// FoundContent(
// entries = entries,
// currentLat = /* last known lat */ null,
// currentLon = /* last known lon */ null,
// showCoords = showCoords,
// labelOverrides = emptyMap(),
// isClickable = { it.layer != FoundStore.LAYER_UNKNOWN },
// onEntryClick = { /* TODO(open wiki/fornsök/dm/klotter) */ },
// isBold = { f -> /* !FoundStore.isAway(<platform>, f.layer, f.id) */ false },
// distanceFormatter = ::formatDistance,
// coordsFormatter = ::formatCoords,
// rowTextStyle = MaterialTheme.typography.bodyMedium
// )
PlaceholderFoundList()
}
}
// --- About ------------------------------------------------------------------------
if (showAbout) {
AlertDialog(
onDismissRequest = { showAbout = false },
title = { Text("Om") },
text = {
Text("Klottr – Compose Multiplatform. (Denna dialog är delad mellan Android & iOS.)")
},
confirmButton = {
TextButton(onClick = { showAbout = false }) { Text("OK") }
}
)
}
// --- Settings ---------------------------------------------------------------------
if (showSettings) {
// If you already have SettingsDialog in :shared, you can uncomment and use it.
// SettingsDialog(
// onlyNew = onlyNew,
// satellite = satellite,
// night = night,
// showCoords = showCoords,
// onShowCoordsChanged = { /* SettingsStore.setShowCoordinates(it); */ showCoords = it },
// showKlotter = showKlotter,
// showWiki = showWiki,
// wikiRadius = wikiRadius,
// showDm = showDm,
// dmRadius = dmRadius,
// showFornsok = showFornsok,
// fornsokRadius = fornsokRadius,
// onOnlyNewChanged = { /* SettingsStore.setOnlyNew(it); */ onlyNew = it },
// onSatelliteChanged = { /* SettingsStore.setSatellite(it); */ satellite = it },
// onNightChanged = { /* SettingsStore.setNightMode(it); */ night = it },
// onShowKlotterChanged = { /* SettingsStore.setShowKlotter(it); */ showKlotter = it },
// onShowWikiChanged = { /* SettingsStore.setShowWikipedia(it); */ showWiki = it },
// onWikiRadiusChanged = { /* SettingsStore.setWikiRadiusMeters(it); */ wikiRadius = it },
// onShowDmChanged = { /* SettingsStore.setShowDigitaltMuseum(it); */ showDm = it },
// onDmRadiusChanged = { /* SettingsStore.setDigitaltMuseumRadiusMeters(it); */ dmRadius = it },
// onShowFornsokChanged = { /* SettingsStore.setShowFornsok(it); */ showFornsok = it },
// onFornsokRadiusChanged = { /* SettingsStore.setFornsokRadiusMeters(it); */ fornsokRadius = it },
// onClearFinds = {
// // TODO(shared): FoundStore.clearAll()
// },
// onClose = { showSettings = false }
// )
// SimpleSettingsDialog(
// onlyNew = onlyNew,
// satellite = satellite,
// night = night,
// showCoords = showCoords,
// onOnlyNewChanged = { onlyNew = it },
// onSatelliteChanged = { satellite = it },
// onNightChanged = { night = it },
// onShowCoordsChanged = { showCoords = it },
// onClose = { showSettings = false }
// )
}
// --- Write / Nearby / Map (left commented-out so iOS builds immediately) ----------
if (showWrite) {
// WriteDocDialog(
// onClose = { showWrite = false },
// onDone = { /* TODO(upload note + refresh */ showWrite = false }
// )
// Placeholder:
AlertDialog(
onDismissRequest = { showWrite = false },
title = { Text("Klottra") },
text = { Text("TODO: Implementera skriv-notering för iOS (kamera/foto/position).") },
confirmButton = { TextButton({ showWrite = false }) { Text("Stäng") } }
)
}
if (showNearby) {
// NearbyDialog(
// /* inputs incl. last-known location & filters */,
// onMarkedFound = { /* refresh found list */ },
// onClose = { showNearby = false }
// )
AlertDialog(
onDismissRequest = { showNearby = false },
title = { Text("Närliggande") },
text = { Text("TODO: Visa närliggande fynd (kräver platsbehörighet).") },
confirmButton = { TextButton({ showNearby = false }) { Text("Stäng") } }
)
}
if (showMap) {
// MapDialog(
// onClose = { showMap = false },
// onKlotterClick = { id, la, lo -> /* TODO(open) */ },
// onWikiClick = { pageId -> /* TODO(open) */ },
// onDmClick = { item -> /* TODO(open) */ },
// onFornsokClick = { item -> /* TODO(open) */ }
// )
AlertDialog(
onDismissRequest = { showMap = false },
title = { Text("Karta") },
text = { Text("TODO: Karta via expect/actual (UIKitView på iOS).") },
confirmButton = { TextButton({ showMap = false }) { Text("Stäng") } }
)
}
// --- Login required ---------------------------------------------------------------
if (showLoginRequired) {
AlertDialog(
onDismissRequest = { showLoginRequired = false },
title = { Text("Inloggning krävs") },
text = { Text("Du måste logga in för att kunna klottra.") },
confirmButton = {
TextButton(onClick = {
showLoginRequired = false
onLogin()
// TODO(shared Auth): set loggedIn=true when Auth completes.
}) { Text("Logga in") }
},
dismissButton = {
TextButton(onClick = { showLoginRequired = false }) { Text("Stäng") }
}
)
}
}
// --- Helpers --------------------------------------------------------------------------
@Composable
private fun PlaceholderFoundList() {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
"Inga fynd ännu.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
// TIP: Replace with FoundContent(...) once wired on iOS.
}
}
// Keep these signatures handy if you want to pass formatters into FoundContent later.
private fun formatDistance(meters: Double?): String =
meters?.let { if (it >= 1000.0) "${(it / 1000.0).toStringAsFixed(1)} km" else "${it.toInt()} m" } ?: ""
private fun formatCoords(lat: Double?, lon: Double?): String =
if (lat == null || lon == null) "" else "${lat.toStringAsFixed(5)}, ${lon.toStringAsFixed(5)}"
// Small utility (MPP-friendly) for 1 decimal formatting without Locale issues
private fun Double.toStringAsFixed(decimals: Int): String {
val pow = pow10(decimals)
val v = kotlin.math.round(this * pow) / pow
var s = v.toString()
if (!s.contains('.')) s += "."
val idx = s.indexOf('.')
val need = decimals - (s.length - idx - 1)
if (need > 0) s += "0".repeat(need)
return s
}
private fun pow10(exp: Int): Double {
var p = 1.0
repeat(exp) { p *= 10.0 }
return p
}

View File

@@ -8,6 +8,8 @@ import app.klottr.util.distanceMeters
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlin.math.roundToInt
import kotlin.time.Clock
import kotlin.time.ExperimentalTime
/** Konfiguration för autoscan (toggles + radier). */
data class ScanConfig(
@@ -36,7 +38,8 @@ suspend fun scanAndMarkFound(
): Boolean = coroutineScope {
updateAwayFlags(lat, lon)
val now = System.currentTimeMillis()
@OptIn(ExperimentalTime::class)
val now: Long = Clock.System.now().toEpochMilliseconds()
val wikiDef = async {
if (!config.showWiki) emptyList()

View File

@@ -0,0 +1,54 @@
// shared/src/commonMain/kotlin/app/klottr/util/AuthShared.kt
package app.klottr.util
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlin.concurrent.Volatile
object AuthShared {
private const val KEY_IDTOKEN = "id_token"
private const val KEY_SUB = "sub"
private const val KEY_EMAIL = "email"
@Volatile var idToken: String? = null; private set
@Volatile var userId: String? = null; private set
@Volatile
var email: String? = null; private set
private val _loggedIn = MutableStateFlow(false)
val loggedIn: StateFlow<Boolean> = _loggedIn
private val _email = MutableStateFlow<String?>(null)
val emailFlow: StateFlow<String?> = _email
/** Called by platform code after a successful sign-in (or silent restore). */
fun applyLogin(token: String?, sub: String?, mail: String?) {
idToken = token
userId = sub
email = mail
_loggedIn.value = token != null
_email.value = mail
if (token != null) {
PlatformAuthStorage.set(KEY_IDTOKEN, token)
PlatformAuthStorage.set(KEY_SUB, sub)
PlatformAuthStorage.set(KEY_EMAIL, mail)
}
}
/** Load last known auth state from platform storage (Keychain on iOS). */
fun loadFromStorage() {
idToken = PlatformAuthStorage.get(KEY_IDTOKEN)
userId = PlatformAuthStorage.get(KEY_SUB)
email = PlatformAuthStorage.get(KEY_EMAIL)
_loggedIn.value = idToken != null
_email.value = email
}
/** Clear both in-memory state and platform storage. */
fun clearAll() {
idToken = null; userId = null; email = null
_loggedIn.value = false
_email.value = null
PlatformAuthStorage.clear()
}
}

View File

@@ -0,0 +1,8 @@
// shared/src/commonMain/kotlin/app/klottr/util/AuthStorageDelegate.kt
package app.klottr.util
interface AuthStorageDelegate {
fun get(key: String): String?
fun set(key: String, value: String?)
fun clear()
}

View File

@@ -0,0 +1,13 @@
// shared/src/commonMain/kotlin/app/klottr/util/PlatformAuthStorage.kt
package app.klottr.util
/** Minimal key-value used only by AuthShared. iOS uses Keychain. */
expect object PlatformAuthStorage {
fun get(key: String): String?
fun set(key: String, value: String?)
fun clear()
/** iOS will use this; Android can be a no-op */
fun install(delegate: AuthStorageDelegate)
}

View File

@@ -0,0 +1,7 @@
package app.klottr
import androidx.compose.ui.window.ComposeUIViewController
import platform.UIKit.UIViewController
fun MainViewController(): UIViewController =
ComposeUIViewController { KlottrRoot() }

View File

@@ -0,0 +1,6 @@
package app.klottr.location
/** iOS implementation keeps the last known point in memory. */
actual object LastLocationStore {
actual var lastKnown: GeoPoint? = null
}

View File

@@ -0,0 +1,38 @@
package app.klottr.util
import platform.Foundation.NSLog
import kotlin.concurrent.Volatile
// iOS-implementation av KLog: loggar till Xcode/Console via NSLog.
// Default-tag "Klottr" om ingen tag anges. Loggning kan stängas av.
actual object KLog {
@Volatile
private var enabled: Boolean = true // På som default; kan stängas via setEnabled
actual fun setEnabled(enabled: Boolean) {
this.enabled = enabled // Uppdatera flagga
}
private fun tagOrDefault(tag: String?): String = tag ?: "Klottr" // Standardtag
private fun log(level: String, tag: String?, text: () -> String) {
if (!enabled) return
val tg = tagOrDefault(tag)
// %@ konverterar Kotlin String -> NSString
NSLog("[$level][%@] %@", tg, text())
}
actual fun d(tag: String?, msg: () -> String) = log("D", tag, msg)
actual fun w(tag: String?, msg: () -> String) = log("W", tag, msg)
actual fun e(tag: String?, t: Throwable?, msg: () -> String) {
if (!enabled) return
val tg = tagOrDefault(tag)
if (t != null) {
NSLog("[E][%@] %@ — %@", tg, msg(), t.stackTraceToString())
} else {
NSLog("[E][%@] %@", tg, msg())
}
}
}

View File

@@ -0,0 +1,14 @@
// shared/src/iosMain/kotlin/app/klottr/util/PlatformAuthStorage.ios.kt
package app.klottr.util
actual object PlatformAuthStorage {
private var delegate: AuthStorageDelegate? = null
actual fun install(delegate: AuthStorageDelegate) {
this.delegate = delegate
}
actual fun get(key: String): String? = delegate?.get(key)
actual fun set(key: String, value: String?) { delegate?.set(key, value) }
actual fun clear() { delegate?.clear() }
}

View File

@@ -0,0 +1,24 @@
package app.klottr.util
import platform.Foundation.NSDate
import platform.Foundation.NSDateFormatter
import platform.Foundation.NSDateFormatterMediumStyle
import platform.Foundation.NSDateFormatterShortStyle
import platform.Foundation.NSTimeZone
import platform.Foundation.localTimeZone
import platform.Foundation.dateWithTimeIntervalSince1970
actual fun formatRelativeOrTime(ms: Long): String {
val date = NSDate.dateWithTimeIntervalSince1970(ms.toDouble() / 1000.0)
// Fully localized output like:
// - "Today, 14:32" / "Yesterday, 2:32 PM" (language + punctuation vary by locale)
// - "Sep 20, 2025 at 14:32" or locale-equivalent for older dates
return NSDateFormatter().apply {
dateStyle = NSDateFormatterMediumStyle
timeStyle = NSDateFormatterShortStyle
doesRelativeDateFormatting = true // enables "Today"/"Yesterday" in the user’s language
timeZone = NSTimeZone.localTimeZone // device zone
// locale defaults to user's current; no override here on purpose.
}.stringFromDate(date)
}