<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by TonyGnk on Medium]]></title>
        <description><![CDATA[Stories by TonyGnk on Medium]]></description>
        <link>https://medium.com/@TonyGnk?source=rss-fc66e55e776c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KfgsyhIUqyF8RfUpoi16og.png</url>
            <title>Stories by TonyGnk on Medium</title>
            <link>https://medium.com/@TonyGnk?source=rss-fc66e55e776c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:41:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TonyGnk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Making libs.versions Clickable: Building the CatalogLens IntelliJ Plugin]]></title>
            <link>https://medium.com/@TonyGnk/making-libs-versions-clickable-building-the-cataloglens-intellij-plugin-84d882656d28?source=rss-fc66e55e776c------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d882656d28</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[android-libraries]]></category>
            <dc:creator><![CDATA[TonyGnk]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 14:26:02 GMT</pubDate>
            <atom:updated>2026-06-09T14:28:34.847Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If you’ve worked on a modern Gradle project, you’ve met the version catalog: a single `gradle/libs.versions.toml` file that holds every dependency coordinate and version in one place. It’s a genuinely great convention — one source of truth, type-safe accessors, no more magic strings scattered across `build.gradle` files.</p><p>But the file itself is inert. It’s a wall of text. When I see a line like this:</p><pre>coil = { module = &quot;io.coil-kt:coil-compose&quot;, version.ref = &quot;coil&quot; }</pre><p>…there’s no way to Ctrl/Cmd-click <em>io.coil-kt:coil-compose</em> and land on its Maven Central page to check the latest version. When I bump a version, there’s no quick path to the library’s changelog to see what actually changed.</p><p>Neither of these is a hard problem — they’re just friction, small and repeated, every single day. So I built a plugin to remove them. It also does one thing that isn’t a problem at all: on demand, it can sort the entries inside a table alphabetically. An unsorted catalog is perfectly fine; some people (me included) just like to keep it tidy, and doing it by hand is tedious.</p><p><strong>CatalogLens</strong> is an IntelliJ / Android Studio plugin that makes version catalogs navigable. In this article I’ll cover what it does, then dig into how it works under the hood — the TOML PSI, web references, gutter line markers, the group sorter — and finally how the bundled artifact map turns it into something the community can extend with a single-line pull request.</p><p>&gt; Get CatalogLens on the <a href="https://plugins.jetbrains.com/plugin/32144-cataloglens/">JetBrains Marketplace</a>. Source is on <a href="https://github.com/tonygnk/CatalogLens">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJ0ZKQAMbx5awFO3Lg_P6w.png" /><figcaption>CatalogLens in a libs.versions.toml file — artifact links and gutter icons</figcaption></figure><h3>What It Does</h3><p>CatalogLens adds three things to any `libs.versions.toml` file.</p><h4>1. Artifact links</h4><p>Every entry in the <em>[libraries]</em> table becomes Ctrl/Cmd-clickable. Click the coordinate and the artifact’s page opens in your browser — Maven Central by default, MvnRepository if you prefer. Google-Maven-only artifacts (AndroidX, Firebase, Play Services) route to <em>maven.google.com</em> instead, because they don’t exist on Central.</p><p>It understands every shape a catalog entry can take:</p><pre># string notation<br>retrofit = &quot;com.squareup.retrofit2:retrofit:2.11.0&quot;<br># module shorthand<br>coil = { module = &quot;io.coil-kt:coil-compose&quot;, version.ref = &quot;coil&quot; }<br># group / name<br>core = { group = &quot;androidx.core&quot;, name = &quot;core-ktx&quot;, version.ref = &quot;core&quot; }<br># long-form dotted keys<br>ktor.client.core = &quot;io.ktor:ktor-client-core&quot;</pre><h4>2. Upstream changelog links</h4><p>Each `[versions]` entry gets a gutter icon. Click it and you jump straight to the release notes or changelog for every library and plugin that references that version. This is the one I reach for most when bumping dependencies — no more Googling “okhttp changelog” to find out what a patch bump fixed.</p><p>The links come from a bundled map of popular artifacts (AndroidX, Kotlin(x), Square, Koin, Ktor, Coil, Dagger/Hilt, and more) with a group-prefix fallback. If a single version is shared by several libraries, the icon opens a small popup so you can pick which changelog to open.</p><h4>3. Sort groups A→Z</h4><p>A floating editor icon (and a context-menu action) sorts entries alphabetically within each group. A “group” here is a contiguous run of entry lines — blank lines, comments, and table headers act as delimiters and stay exactly where they are. Before anything is written, a diff preview appears with a checkbox per unsorted group, so you sort exactly the groups you want and leave the rest alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuDg_9rS953RLcPZo7Lz7w.png" /><figcaption>The sort preview dialog, with a checkbox per group</figcaption></figure><p>One thing I want to call out up front: <strong>all of these links are built locally from the file’s contents. </strong>The plugin makes zero network calls while you edit. A browser opens only when you explicitly click a link. Nothing about your dependency graph ever leaves your machine.</p><h3>Installation</h3><p>Open `Settings → Plugins → Marketplace`, search for <strong>CatalogLens</strong>, install, restart. It requires an IntelliJ-based IDE on `2025.1` or newer (Android Studio Narwhal and up).</p><h3>How It Works</h3><p>The interesting part isn’t the feature list — it’s how little code each feature takes once you build on the right foundation.</p><h4><strong>Standing on the TOML PSI</strong></h4><p>The decision that saved the most work was not parsing the file myself. IntelliJ ships a bundled TOML plugin (`org.toml.lang`) that exposes a full PSI tree — `TomlTable`, `TomlKeyValue`, `TomlLiteral`, and friends. By declaring a dependency on it in `plugin.xml`, every catalog file arrives already parsed into typed elements I can walk.</p><pre>&lt;depends&gt;com.intellij.modules.platform&lt;/depends&gt;<br>&lt;depends&gt;org.toml.lang&lt;/depends&gt;</pre><p>Before doing anything, the plugin needs to know whether a given TOML file is actually a version catalog. That check runs constantly, so it’s cached against the file’s modification count:</p><pre>object VersionCatalogDetector {<br><br>    private val CATALOG_TABLES = setOf(&quot;libraries&quot;, &quot;versions&quot;, &quot;plugins&quot;, &quot;bundles&quot;)<br><br>    fun isVersionCatalog(file: PsiFile?): Boolean {<br>        if (file !is TomlFile) return false<br>        if (file.name.endsWith(&quot;.versions.toml&quot;)) return true<br>        val vf = file.virtualFile ?: return false<br>        if (vf.parent?.name != &quot;gradle&quot;) return false<br>        return hasCatalogTables(file)<br>    }<br><br>    private fun hasCatalogTables(file: TomlFile): Boolean =<br>        CachedValuesManager.getCachedValue(file) {<br>            val has = file.children<br>                .filterIsInstance&lt;TomlTable&gt;()<br>                .any { it.header.key?.segments?.singleOrNull()?.name in CATALOG_TABLES }<br>            CachedValueProvider.Result.create(has, file)<br>        }<br>}</pre><h4><strong>Behavior 1: artifact links</strong></h4><p>A clickable web link inside the editor is exactly what the platform’s `WebReference` is for. I register a `PsiReferenceContributor` that, for any string literal in a catalog file, extracts the coordinate and attaches a `WebReference` pointing at the artifact page.</p><pre>private class LibrariesWebReferenceProvider : PsiReferenceProvider() {<br><br>    override fun getReferencesByElement(<br>        element: PsiElement,<br>        context: ProcessingContext,<br>    ): Array&lt;PsiReference&gt; {<br>        val literal = element as? TomlLiteral ?: return PsiReference.EMPTY_ARRAY<br>        if (!VersionCatalogDetector.isVersionCatalog(literal.containingFile)) {<br>            return PsiReference.EMPTY_ARRAY<br>        }<br>        val coord = CatalogCoordinateExtractor.coordinateForLinkLiteral(literal)<br>            ?: return PsiReference.EMPTY_ARRAY<br>        val style = CatalogLensGlobalSettings.getInstance().state.artifactUrlStyle<br>        val url = ArtifactUrlBuilder.url(https://medium.com/coord,%20style)<br>        val range = ElementManipulators.getValueTextRange(literal)<br>        return arrayOf(WebReference(literal, range, url))<br>    }<br>}</pre><p>This gives you the native hyperlink UX — underline on hover, click to open — for free, and it’s daemon-safe and read-only.</p><p>All the messy work lives in the coordinate extractor, which normalizes those four catalog syntaxes into one small data class:</p><pre>data class Coord(val group: String, val name: String, val version: String?) {<br>    val key: String get() = &quot;$group:$name&quot;<br>}</pre><p>The URL builder is then pure string templating — no I/O, no surprises:</p><pre>fun url(/service/coord: Coord, style: ArtifactUrlStyle): String =<br>    when (style) {<br>        ArtifactUrlStyle.MAVEN_CENTRAL -&gt;<br>            if (isGoogleMavenHosted(coord.group)) {<br>                &quot;https://maven.google.com/web/index.html#${coord.group}:${coord.name}&quot;<br>            } else {<br>                withVersion(&quot;https://central.sonatype.com/artifact/${coord.group}/${coord.name}&quot;, coord) + &quot;/versions&quot;<br>            }<br>        ArtifactUrlStyle.MVNREPOSITORY -&gt;<br>            withVersion(&quot;https://mvnrepository.com/artifact/${coord.group}/${coord.name}&quot;, coord)<br>    }</pre><p>Note the small product decisions baked in: Central links land on the <em>Versions</em> tab rather than the overview, and Google Maven links carry no version at all — a stale version would just render an empty pane.</p><h4>Behavior 2: changelog gutter icons</h4><p>The gutter icon is a `LineMarkerProviderDescriptor`. The one sharp edge here is well documented in the platform: line markers must be registered on <strong>leaf</strong> PSI elements, never on composite ones, or you get flicker as the daemon re-runs. So the provider bails immediately unless the element is the exact leaf identifier inside a `[versions]` entry:</p><pre>override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo&lt;*&gt;? {<br>    if (element !is LeafPsiElement) return null<br>    val segment = element.parent as? TomlKeySegment ?: return null<br>    val key = segment.parent as? TomlKey ?: return null<br>    val keyValue = key.parent as? TomlKeyValue ?: return null<br>    val table = keyValue.parent as? TomlTable ?: return null<br>    if (headerName(table) != &quot;versions&quot;) return null<br><br>    val file = element.containingFile as? TomlFile ?: return null<br>    if (!VersionCatalogDetector.isVersionCatalog(file)) return null<br><br>    val refName = segment.name ?: return null<br>    val urls = resolveUrls(file, refName)<br>    if (urls.isEmpty()) return null<br>    // ... build LineMarkerInfo: one URL opens directly, several show a popup<br>}</pre><p>To resolve a version key into changelog URLs, it walks the file once to build an index — which libraries and plugins reference each version ref — then feeds each coordinate through the resolver. That index is cached the same way the detector is, so scrolling a large catalog stays cheap.</p><h4><strong>The bundled map and a three-layer resolver</strong></h4><p>The changelog URLs come from a JSON file shipped inside the plugin:</p><pre>{<br>  &quot;artifacts&quot;: {<br>    &quot;com.squareup.okhttp3:okhttp&quot;: [<br>      &quot;https://square.github.io/okhttp/changelogs/changelog/&quot;,<br>      &quot;https://github.com/square/okhttp/releases&quot;<br>    ]<br>  },<br>  &quot;groupPrefixes&quot;: {<br>    &quot;androidx&quot;: [&quot;https://developer.android.com/jetpack/androidx/versions&quot;]<br>  }<br>}</pre><p>`artifacts` holds exact `group:artifact` (or plugin-ID) keys; `groupPrefixes` is a fallback matched on dot boundaries, longest prefix wins — so `androidx.compose.ui` falls back to the `androidx` entry if it has no exact match.</p><p>User mappings layer on top of the bundle. The resolver checks them in priority order: project-scoped mappings first (stored in `.idea/cataloglens.xml`, so a team can share them), then your global mappings, then the bundled map. Each layer shadows the ones below it:</p><pre>private fun resolve(project: Project, exactKey: String, prefixSource: String): List&lt;String&gt; {<br>    val global = CatalogLensGlobalSettings.getInstance().state<br><br>    lookupUserMappings(<br>        CatalogLensProjectSettings.getInstance(project).state.mappings, exactKey, prefixSource,<br>    )?.let { return it }<br><br>    lookupUserMappings(global.mappings, exactKey, prefixSource)?.let { return it }<br><br>    if (!global.useBundledMap) return emptyList()<br>    BundledArtifactMap.exact(exactKey)?.let { return it }<br>    ret</pre><h4><strong>The sorter</strong></h4><p>The sort feature is the one piece that deliberately <em>doesn’t</em> use the PSI. Reformatting through the AST would lose comment placement and blank lines, which is exactly what people care about in a hand-curated catalog. So the sorter works on raw text.</p><p>It splits the file into segments: a <em>group</em> is a contiguous run of entry lines, and anything else (blank line, comment, table header) is a <em>delimiter</em> that stays put. Multi-line entries — like a `[bundles]` array spread across several lines — are tracked with a small bracket-depth counter so they move as a single unit, and any line it can’t parse cleanly marks its group as unsortable rather than risking a mangle.</p><p>The result is a non-destructive transform: delimiters never move, only the entries inside each group get reordered, and you preview the diff before a single character is written.</p><h3>Extending It: Add a Library in One PR</h3><p>This is the part I’m most interested in growing, and where contributions are genuinely easy.</p><p>If you use a library that has no changelog icon, it’s almost certainly missing from the bundled map. Adding it is a one-file change — `src/main/resources/cataloglens/artifact-map.json` — and a pull request:</p><pre>&quot;com.squareup.okhttp3:okhttp&quot;: [<br>  &quot;https://square.github.io/okhttp/changelogs/changelog/&quot;,<br>  &quot;https://github.com/square/okhttp/releases&quot;<br>]</pre><p>That’s the whole contribution. Exact `group:artifact` key, a list of URLs, prefer the official release-notes page over a generic repo root. There’s no code to touch, no API to learn — and the map already ships with 50-odd of the most common JVM and Android libraries, so it’s mostly a matter of filling gaps. The one rule for any PR: keep the zero-network-while-editing guarantee intact.</p><p>If you’d rather not open a PR, the same mappings are available in `Settings → Tools → CatalogLens`, either globally or scoped to a single project.</p><h3>Publishing to the Marketplace</h3><p>I expected plugin publishing to be a slog. It mostly wasn’t.</p><p>The build uses the IntelliJ Platform Gradle Plugin 2.x, which handles the entire lifecycle — compiling against a target IDE, running a sandbox instance, verifying compatibility, and publishing. Running the plugin in a real Android Studio sandbox during development is one task:</p><pre>./gradlew runIde</pre><p>Publishing to the Marketplace is one command with your signing credentials in the environment:</p><pre>PUBLISH_TOKEN=… CERTIFICATE_CHAIN=… PRIVATE_KEY=… PRIVATE_KEY_PASSWORD=… ./gradlew publishPlugin</pre><p>The signing keys are a one-time `openssl` step. The only real gotchas were Marketplace’s rules rather than anything technical: the plugin name can’t contain “Plugin”, “IntelliJ”, or “Support”, and the default template icon gets rejected — you need a custom one. Both are quick fixes, and neither cost me more than the listing itself did.</p><h3>Conclusion</h3><p>CatalogLens is a small plugin that scratches a daily itch: the version catalog is the right place to manage dependencies, but the file shouldn’t be a dead end. Now the coordinates are clickable, the changelogs are one gutter-click away, and the file stays tidy on demand — all without a single network call while you type.</p><p>If any of that friction sounds familiar, [it’s on the Marketplace](https://plugins.jetbrains.com/plugin/32144-cataloglens/). And if a library you rely on is missing its changelog link, the bundled map takes a one-file pull request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d882656d28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Precision Overlays in Jetpack Compose: From onGloballyPositioned to onLayoutRectChanged]]></title>
            <link>https://medium.com/@TonyGnk/mastering-precision-overlays-in-jetpack-compose-from-ongloballypositioned-to-onlayoutrectchanged-1c2febc476dd?source=rss-fc66e55e776c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2febc476dd</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[TonyGnk]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 21:47:42 GMT</pubDate>
            <atom:updated>2025-11-22T21:47:42.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*MfTjBHGF3dS9ZNCrolr-EA.gif" /><figcaption>The final result</figcaption></figure><h3>Introduction</h3><p>In modern Android and Multiplatform development, striking the balance between delightful animations and raw rendering performance is often a tightrope walk. We often need to create immersive effects — like a confetti explosion — that originate from a specific element but render <em>above</em> the rest of the UI hierarchy.</p><p>However, placing these animations precisely is difficult. The standard approach is to wrap elements in a Box. But what if you need an animation to render <strong>above</strong> a Card, but center itself exactly over a specific Text element deeply nested <strong>inside</strong> that Card?</p><p>In this guide, we will build a high-performance system to render a <strong>Lottie animation overlay</strong> that tracks a specific text element. We will compare two approaches: the legacy OnGloballyPositioned modifier and the modern, efficient OnLayoutRectChanged.</p><p>This guide uses standard libraries compatible with <strong>Compose Multiplatform</strong></p><h3>Dependencies &amp; Assets</h3><p>Ensure you are using a version of Compose UI that supports the new layout modifiers (Compose BOM 2025.04.01 or later).</p><pre>// build.gradle.kts<br>dependencies {<br>    // Jetpack Compose BOM (April 2025 release or newer for onLayoutRectChanged)<br>    implementation(platform(&quot;androidx.compose:compose-bom:2025.04.01&quot;))<br>    <br>    // A lightweight Compose Multiplatform library for Lottie<br>    implementation(&quot;io.github.alexzhirkevich:compottie-lite:2.0.0&quot;) <br>}</pre><p>You will also need a Lottie JSON file (e.g., confetti.json) placed in your src/main/assets or composeResources/files directory.</p><h3>The Spatial Challenge</h3><p>When we visualize our UI, we typically think in stacks. If we want an animation to appear “on top” of a text element, the naive approach is to wrap both in a Box and align them.</p><pre>// The &quot;Easy&quot; Way - often insufficient<br>Box(contentAlignment = Alignment.Center) {<br>    Text(&quot;100%&quot;)<br>    if (showAnim) LottieAnimation()<br>}</pre><p>However, real-world constraints often break this simple model:</p><ol><li><strong>Clipping:</strong> The parent container (like a Card) might clip its content, cutting off an explosion animation that should spill outside the card bounds.</li><li><strong>Complex Nesting:</strong> The target element (the Text) might be buried deep inside nested Columns and Rows, making it difficult to position a floating overlay relative to it from a higher UI layer.</li></ol><p>Let’s look at our scenario. We have a BookProgressList. Inside it, we have cards displaying reading progress. When the user finishes a book (100%), we want a celebratory animation to explode <em>over</em> the progress text.</p><p>The hierarchy looks like this:<br>LazyColumn → Card → Column → Row → <strong>Text (The Target)</strong></p><p>f we simply place the animation inside the Row, it will be clipped by the Card’s bounds. If we place it outside the Card, we lose the coordinate reference to the Text.</p><p>Here is our initial UI setup:</p><pre>@Composable<br>fun BookProgressCard(book: Book, modifier: Modifier = Modifier) {<br>    val progressPercentage = (book.progress * 100).toInt()<br>    <br>    // ... Animation states ...<br><br>    Card(<br>        modifier = modifier.fillMaxWidth(),<br>        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)<br>    ) {<br>        Column(modifier = Modifier.padding(16.dp)) {<br>            // Title, Author, etc...<br>            <br>            Row(verticalAlignment = Alignment.CenterVertically) {<br>                ProgressBar(modifier = Modifier.weight(1f))<br>                <br>                Spacer(modifier = Modifier.width(16.dp))<br>                <br>                // THIS is our target. We need the animation centered here.<br>                Text(<br>                    text = &quot;$progressPercentage%&quot;,<br>                    style = MaterialTheme.typography.bodyLarge,<br>                    color = MaterialTheme.colorScheme.primary<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>To overlay an animation correctly, we need to know where that Text is relative to the screen, or more importantly, relative to the container where the animation will live.</p><h3>The Spatial Dilemma: Choosing the Right Modifier</h3><p>To solve this, we need to extract layout coordinates. Historically, developers relied on OnGloballyPositioned. However, recent updates to Compose have introduced a superior alternative: OnLayoutRectChanged.</p><h4>1. The Legacy Approach: OnGloballyPositioned</h4><p>For years, this was the standard tool. It provides a LayoutCoordinates object.</p><p><strong>How it works:</strong> It provides LayoutCoordinates, allowing you to calculate position in the window or root.</p><p><strong>The Problem:</strong> It is computationally expensive. Calculating global coordinates requires traversing the UI tree and performing matrix multiplications for every parent up to the root.</p><p><strong>Performance Hit:</strong> It runs on the main thread and cannot be easily throttled. If used inside a LazyColumn, scrolling can trigger massive amounts of recalculations (“layout thrashing”), causing frame drops.</p><h4>2. The Modern Solution: onLayoutRectChanged</h4><p>Introduced to solve the overhead of the legacy approach, this modifier is designed for visibility tracking and relative positioning.</p><p><strong>Efficiency:</strong> It returns a RelativeLayoutBounds object, which is lightweight.</p><p><strong>Throttling:</strong> It has native support for debounceMillis and throttleMillis. You can limit updates to every 32ms or 64ms, drastically reducing the load during resizing or scrolling.</p><p><strong>The Strategy:</strong> Instead of asking “Where is the text on the screen?”, we ask two questions:</p><ol><li>Where is the <strong>Parent Box</strong> (the overlay container) in the Root?</li><li>Where is the <strong>Source Text</strong> in the Root?</li></ol><p>By subtracting the two, we get the exact Offset needed to place our animation, all while bypassing complex matrix math.</p><h3>The RelativeBox Pattern</h3><p>We will create a custom component called RelativeBox. It acts as a wrapper that accepts two things:</p><ol><li><strong>content</strong>: The UI that contains our target (the Card).</li><li><strong>floatingContent</strong>: The animation to overlay.</li></ol><blockquote>It injects a <em>modifier</em> into the content scope. We attach this modifier to the element we want to track.</blockquote><pre>@Composable<br>internal fun RelativeBox(<br>    modifier: Modifier = Modifier,<br>    debounceMillis: Long = 32, // Check ~30 times/sec, saving resources<br>    widthMarginDp: Dp = 0.dp,<br>    heightMarginDp: Dp = 0.dp,<br>    floatingContent: @Composable (Modifier, sourceWidth: Dp, sourceHeight: Dp) -&gt; Unit,<br>    content: @Composable (BoxScope.(Modifier) -&gt; Unit),<br>) {<br>    // 1. Track the bounds of this container (the reference point)<br>    val parentBounds = remember { mutableStateOf&lt;RelativeLayoutBounds?&gt;(null) }<br>    <br>    // 2. Track the bounds of the specific internal target<br>    val sourceBounds = remember { mutableStateOf&lt;RelativeLayoutBounds?&gt;(null) }<br><br>    Box(<br>        modifier = modifier.onLayoutRectChanged(debounceMillis = debounceMillis) { bounds -&gt;<br>            parentBounds.value = bounds<br>        }<br>    ) {<br>        // Pass the &quot;tracker&quot; modifier down to the content<br>        content(<br>            Modifier.onLayoutRectChanged(debounceMillis = debounceMillis) { bounds -&gt;<br>                sourceBounds.value = bounds<br>            }<br>        )<br><br>        // Only render floating content if we have both coordinates<br>        val currentParent = parentBounds.value ?: return@Box<br>        val currentSource = sourceBounds.value ?: return@Box<br><br>        RelativeBoxInternal(<br>            parentBounds = currentParent,<br>            sourceBounds = currentSource,<br>            widthMarginDp = widthMarginDp,<br>            heightMarginDp = heightMarginDp,<br>            floatingContent = floatingContent<br>        )<br>    }<br>}</pre><h4>The Mathematics of Alignment</h4><p>Inside RelativeBoxInternal, we calculate the exact pixel offset. By using derivedStateOf, we ensure that we only recompose the animation when positions actually change, not on every layout pass.</p><pre>@Composable<br>internal fun RelativeBoxInternal(<br>    parentBounds: RelativeLayoutBounds,<br>    sourceBounds: RelativeLayoutBounds,<br>    widthMarginDp: Dp,<br>    heightMarginDp: Dp,<br>    floatingContent: @Composable (Modifier, sourceWidth: Dp, sourceHeight: Dp) -&gt; Unit,<br>) {<br>    val density = LocalDensity.current<br><br>    // Convert source size to DP for the floating content<br>    val originalSizeDp by remember(sourceBounds.width, sourceBounds.height, density) {<br>        derivedStateOf {<br>            with(density) {<br>                Pair(sourceBounds.width.toDp(), sourceBounds.height.toDp())<br>            }<br>        }<br>    }<br>    val (originalWidthDp, originalHeightDp) = originalSizeDp<br><br>    // Calculate the precise offset<br>    val offset by remember(sourceBounds.positionInRoot, parentBounds.positionInRoot, density) {<br>        derivedStateOf {<br>            // The Delta: Source Position - Parent Position = Local Offset<br>            val offsetX = (sourceBounds.positionInRoot.x - parentBounds.positionInRoot.x)<br>            val offsetY = (sourceBounds.positionInRoot.y - parentBounds.positionInRoot.y)<br>            <br>            // Adjust for margins to center the animation<br>            val shiftX = with(density) { (widthMarginDp.toPx() / 2f).roundToInt() }<br>            val shiftY = with(density) { (heightMarginDp.toPx() / 2f).roundToInt() }<br><br>            IntOffset(x = offsetX - shiftX, y = offsetY - shiftY)<br>        }<br>    }<br><br>    // Render the overlay with absolute precision<br>    floatingContent(<br>        Modifier<br>            .absoluteOffset { offset }<br>            .size(<br>                width = originalWidthDp + widthMarginDp, <br>                height = originalHeightDp + heightMarginDp<br>            )<br>            // Debugging tool: helps visualize unnecessary recompositions<br>            // .recomposeHighlighter() get it from https://www.jetpackcompose.app/snippets/RecompositionHighlighter<br>        , <br>        originalWidthDp, <br>        originalHeightDp<br>    )<br>}</pre><h3>Integration</h3><p>Now, let’s implement this in our list. We use RelativeBox to wrap our Card, and we use the provided modifier to tag our “100%” text.</p><h4>Optimizing the Text Target</h4><p>A common pitfall with text is <strong>jitter</strong>. As the progress goes from 9% to 100%%, the width of the text changes, firing layout events. To prevent our animation from jumping around, we fix the width of the text container to the maximum possible width (“100%”). Also we need to apply the onLayoutRectChangedModifier provided by our RelativeBox</p><pre>@Composable<br>fun BookProgressCardWrapper(book: Book) {<br>    val progressPercentage = (book.progress * 100).toInt()<br><br>    RelativeBox(<br>        widthMarginDp = 100.dp, // Make animation larger than the text<br>        heightMarginDp = 100.dp,<br>        floatingContent = { modifier, _, _ -&gt;<br>            // Only show if finished<br>            if (progressPercentage == 100) {<br>                LottieExplosion(modifier = modifier)<br>            }<br>        }<br>    ) { matchModifier -&gt; // This is the magic modifier<br>        <br>        Card(modifier = Modifier.fillMaxWidth().padding(16.dp)) {<br>            // ... surrounding column code ...<br>            <br>            Row(verticalAlignment = Alignment.CenterVertically) {<br>                // ... Progress Bar ...<br>                <br>                // Pre-measure text to ensure stable layout width<br>                val measurer = rememberTextMeasurer()<br>                val stableWidth = remember(measurer) {<br>                    measurer.measure(<br>                        text = &quot;100%&quot;,<br>                        style = TextStyle.Default // Match your typography<br>                    ).size.width<br>                }<br><br>                Text(<br>                    text = &quot;$progressPercentage%&quot;,<br>                    modifier = Modifier<br>                        .width(with(LocalDensity.current) { stableWidth.toDp() })<br>                        // Attach the tracker here! <br>                        .then(matchModifier), <br>                    textAlign = TextAlign.End<br>                )<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wjyYTOKh13N7WTp33gsDLA.png" /></figure><h4>The Lottie Animation</h4><p>Using compottie, we load the asset and play it only when the state is reached.</p><pre>@Composable<br>fun LottieExplosion(modifier: Modifier = Modifier) {<br>    val composition by rememberLottieComposition {<br>        JsonString(Res.readBytes(&quot;files/confetti.json&quot;).decodeToString()) // or context.assets.open(assetPath).bufferedReader().use { it.readText() }<br>    }<br>    <br>    val animatable = rememberLottieAnimatable()<br>    <br>    LaunchedEffect(composition) {<br>        animatable.animate(composition)<br>    }<br><br>    Image(<br>        painter = rememberLottiePainter(<br>            composition = composition,<br>            progress = { animatable.progress },<br>        ),<br>        contentDescription = null,<br>        modifier = modifier, // Modifier passed from RelativeBox sets size/offset<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*snpZVAIGXipqYQoMdlxeJA.gif" /></figure><h3>Conclusion</h3><p>By moving away from OnGloballyPositioned and adopting the new OnLayoutRectChanged modifier, we achieved a highly performant “embedded overflow” effect.</p><p><strong>Why onLayoutRectChanged wins:</strong></p><ol><li><strong>Architecture:</strong> We decoupled the overlay logic from the card logic using a “Parent/Source” relationship.</li><li><strong>Precision:</strong> We achieved exact pixel alignment, regardless of padding, margins, or nesting depth.</li><li><strong>Performance:</strong> By leveraging debounceMillis, we ensure that our tracking logic doesn’t choke the main thread during scrolling or resizing, keeping our UI running at a buttery smooth 60fps (or 120fps!).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2febc476dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Delightful Offline Maps with MapLibre and Ramani Maps in Jetpack Compose]]></title>
            <link>https://medium.com/@TonyGnk/creating-delightful-offline-maps-with-maplibre-and-ramani-maps-in-jetpack-compose-28d6781409f1?source=rss-fc66e55e776c------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d6781409f1</guid>
            <category><![CDATA[maplibre]]></category>
            <category><![CDATA[mbtiles]]></category>
            <category><![CDATA[custom-map-tiles]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[offline-android-maps]]></category>
            <dc:creator><![CDATA[TonyGnk]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 16:36:50 GMT</pubDate>
            <atom:updated>2024-11-17T16:42:56.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Building offline-capable maps in Android apps presents unique challenges, especially when aiming for a polished user experience. This guide demonstrates how to create beautiful, offline maps using MapLibre and Ramani Maps with Jetpack Compose. Whether you’re developing a hiking app, travel companion, or location-based service, you’ll learn how to implement sophisticated mapping solutions that work seamlessly — even without an internet connection.</p><blockquote>Access the Full Code <a href="https://github.com/TonyGnk/map-libre-demo">Here</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWIamfktzJDKVf70lADhlw.png" /></figure><h3>Dependencies</h3><p>In your app module’s build.gradle.kts, add the following dependency:</p><pre>implementation(&quot;org.ramani-maps:ramani-maplibre:0.7.0&quot;)</pre><blockquote>💡 Check <a href="https://medium.com/link-to-repo">the official repository</a> for the latest version <a href="https://github.com/ramani-maps/ramani-maps/releases">here</a></blockquote><h3>Getting Assets</h3><p>Creating offline maps requires three essential components: style files, map tiles, and associated assets (sprites and glyphs). Let’s explore how to obtain and manage these assets effectively.</p><h4>Understanding Map Assets</h4><p>Before diving into the implementation, let’s understand what we need:</p><ol><li><strong>Map Tiles</strong>: Vector or raster data containing geographical information</li><li><strong>Style File</strong>: A JSON file that defines how your map looks</li><li><strong>Sprites</strong>: Icons and symbols used on the map</li><li><strong>Glyphs</strong>: Font files for map labels</li></ol><h4>Obtaining Map Tiles</h4><p>I found three main approaches to getting your map assets, each with its own trade-offs:</p><ol><li>Pre-packaged Solutions (Quick Start) ⚡</li></ol><p>The simplest way to get started is using pre-packaged versions of map data from MapTiler <a href="https://data.maptiler.com/downloads/planet/">here</a></p><p><strong>Pros:</strong></p><ul><li>Quick to implement</li><li>No setup required</li></ul><p><strong>Cons:</strong></p><ul><li>Limited customization</li><li>Fixed coverage areas</li></ul><p>2. Paid Solutions (Balanced Approach) 💼</p><p>For more control over your map data while maintaining ease of use:</p><p>1. Visit MapTiler custom extraction <a href="https://data.maptiler.com/extracts/">page</a><br>2. Select your coverage area<br>3. Choose zoom levels<br>4. Purchase and download the file</p><p>Pros: +Customizable coverage, Cons: +Recurring costs</p><p>3. Custom Generation (Full Control) 🛠️</p><p>For complete control over your map data, you can generate your own using Tilemaker. Find instruction for how to setup it <a href="https://github.com/systemed/tilemaker">here</a></p><p><strong>Pros:</strong></p><ul><li>Complete control over data</li><li>No ongoing costs</li><li>Custom styling options for everything!</li><li>Optimal app size</li></ul><p><strong>Cons:</strong></p><ul><li>Setup</li><li>Requires maintenance</li><li>More development time</li></ul><p>Once you’ve downloaded/generated your .mbtiles file, place it in your app’s assets directory.</p><h4>Setting Up Styles, Sprites, and Glyphs</h4><p>To configure map styles, download:</p><ul><li>A <strong>style file</strong> (e.g., <a href="https://github.com/TonyGnk/mapLibreDemo/blob/master/app/src/main/assets/style.json">my style file</a> or <a href="https://openmaptiles.org/styles/">other styles</a>).</li><li>Associated <a href="https://github.com/TonyGnk/mapLibreDemo/tree/master/app/src/main/assets"><strong>sprites and glyphs</strong></a><strong>.</strong></li></ul><p>For downloaded style files, update the JSON references to:</p><pre>{<br>  ...<br>  &quot;sources&quot;: {<br>    &quot;openmaptiles&quot;: {<br>      &quot;type&quot;: &quot;vector&quot;,<br>      &quot;url&quot;: &quot;___FILE_URI___&quot;<br>    }<br>  },<br>  &quot;sprite&quot;: &quot;asset://sprites/sprite&quot;,<br>  &quot;glyphs&quot;: &quot;asset://glyphs/{fontstack}/{range}.pbf&quot;,<br>  &quot;layers&quot;: [...]<br>  ...<br>}</pre><p>You can also download mine sprites and glyphs</p><p>All of these place it at assets folder</p><h3>Loading Map Assets</h3><p>Loading map assets properly is crucial for offline map functionality. This section covers how to manage and load your map style and tiles efficiently using a dedicated MapStyleManager class.</p><h4>Understanding the Asset Loading Process</h4><p>The asset loading process involves several key steps:</p><ol><li>Copying asset files from the app bundle to internal storage</li><li>Updating style file references</li><li>Managing the loading process with proper error handling</li></ol><h4>MapStyleManager Implementation</h4><p>Let’s break down the implementation and understand each component:</p><pre>class MapStyleManager(private val context: Context) {<br>    // Result wrapper for style setup operations<br>    sealed class StyleSetupResult {<br>        data class Success(val styleFile: File) : StyleSetupResult()<br>        data class Error(val exception: Exception) : StyleSetupResult()<br>    }<br><br>    /**<br>     * Main entry point for setting up the map style<br>     * Returns a StyleSetupResult indicating success or failure<br>     */<br>    fun setupStyle(): StyleSetupResult {<br>        return try {<br>            // Copy both style and mbtiles files to internal storage<br>            val styleFile = copyAssetToInternal(STYLE_FILENAME)<br>            val mbtilesFile = copyAssetToInternal(MBTILES_FILENAME)<br><br>            // Update the style file with correct mbtiles path<br>            updateStyleFileUri(styleFile, mbtilesFile)<br>            StyleSetupResult.Success(styleFile)<br>        } catch (e: Exception) {<br>            StyleSetupResult.Error(e)<br>        }<br>    }<br><br>    /**<br>     * Utility function to copy assets to internal storage<br>     * @param assetFileName Name of the file in assets directory<br>     * @return File object pointing to the copied file<br>     */<br>    private fun copyAssetToInternal(assetFileName: String): File {<br>        context.assets.open(assetFileName).use { input -&gt;<br>            val outputFile = File(context.filesDir, assetFileName)<br>            outputFile.outputStream().use { output -&gt;<br>                input.copyTo(output)<br>            }<br>            return outputFile<br>        }<br>    }<br><br>    /**<br>     * Updates the style file with the correct mbtiles URI<br>     * @param styleFile The style file to update<br>     * @param mbtilesFile The mbtiles file reference to insert<br>     */<br>    private fun updateStyleFileUri(styleFile: File, mbtilesFile: File) {<br>        val styleContent = styleFile.readText()<br>        val updatedContent = styleContent.replace(<br>            FILE_URI_PLACEHOLDER,<br>            &quot;mbtiles:///${mbtilesFile.absolutePath}&quot;<br>        )<br>        styleFile.writeText(updatedContent)<br>    }<br><br>    companion object {<br>        private const val STYLE_FILENAME = &quot;style.json&quot;<br>        private const val MBTILES_FILENAME = &quot;malta_europe.mbtiles&quot;<br>        private const val FILE_URI_PLACEHOLDER = &quot;___FILE_URI___&quot;<br>    }<br>}</pre><h3>Using MapStyleManager in Your App</h3><p>Here’s how to integrate the MapStyleManager into your application:</p><pre>@Composable<br>fun MyMap(<br>    modifier: Modifier = Modifier,<br>) {<br>    val context = LocalContext.current<br><br>    val styleBuilder = remember {<br>        val styleManager = MapStyleManager(context)<br>        val style = when (val result = styleManager.setupStyle()) {<br>            is MapStyleManager.StyleSetupResult.Error -&gt; {<br>                throw result.exception<br>            }<br><br>            is MapStyleManager.StyleSetupResult.Success -&gt; result.styleFile<br>        }<br>        Style.Builder().fromUri(<br>            Uri.fromFile(style).toString()<br>        )<br>    }<br><br>    val cameraPosition = rememberSaveable {<br>       CameraPosition(<br>            target = LatLng(35.9103, 14.419),<br>            zoom = 11.0,<br>        )<br>    }<br><br>    MapLibre(<br>        modifier = modifier,<br>        styleBuilder = styleBuilder,<br>        cameraPosition = cameraPosition<br>    ) {<br>        // Add map markers, polylines, etc.<br>    }<br>}</pre><p>Implementing offline maps with MapLibre and Ramani Maps in Jetpack Compose provides a powerful solution for Android developers. This approach offers flexibility in asset management, robust offline capabilities, and seamless integration with modern Android development practices.</p><p>Whether you choose pre-packaged solutions or custom generation, you now have the tools to create engaging, offline-capable map experiences that work reliably anywhere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d6781409f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Authentication: Using Android Credential Manager with Firebase for Google Sign-In]]></title>
            <link>https://medium.com/@TonyGnk/streamlining-authentication-using-android-credential-manager-with-firebase-for-google-sign-in-e4e75b6bd97d?source=rss-fc66e55e776c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4e75b6bd97d</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[credential-manager]]></category>
            <dc:creator><![CDATA[TonyGnk]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 18:58:02 GMT</pubDate>
            <atom:updated>2024-06-18T18:58:02.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the fast-paced world of mobile applications, seamless and secure user authentication is a must. Android’s credential sign-in system, available from version 4.4 (KitKat) onward, allows users to log in effortlessly without repeatedly entering their credentials. Combined with Firebase Authentication, developers can create robust and scalable sign-in systems that enhance security and user convenience.</p><p>This guide focuses on integrating Google Sign-In into your Android app using Firebase Authentication, offering a step-by-step walkthrough from setup to implementation.</p><figure><img alt="Mobile app screenshot showing a ‘Choose a sign-in for the app’ prompt using credencial manager" src="https://cdn-images-1.medium.com/max/872/1*IAy_jgfGxzdAfrAW47e2TA.png" /></figure><h3>Dependencies</h3><p>Before diving into the implementation, ensure you have the necessary libraries integrated into your project. These libraries provide the essential tools and methods required for Firebase Authentication and Google Sign-In.</p><h4>Step 1: Add Plugins</h4><p>In your <strong>build.gradle</strong> (Project) file, add the following plugin to include Google services:</p><pre>plugins {<br>   id(&quot;com.google.gms.google-services&quot;) version &quot;4.4.2&quot; apply false<br>}</pre><p>In your <strong>build.gradle</strong> (Module) file, apply the plugin:</p><pre>plugins {<br>   id(&quot;com.google.gms.google-services&quot;)<br>}</pre><h4>Step 2: Add Dependencies</h4><p>Add the necessary dependencies for Firebase Authentication, Google Sign-In, and Android Credential in your build.gradle (Module) file:</p><pre>dependencies {<br>   //Firebase<br>   implementation(platform(&quot;com.google.firebase:firebase-bom:33.1.0&quot;))<br>   implementation(&quot;com.google.firebase:firebase-auth-ktx&quot;)<br><br>   //Android Credential<br>   implementation(&quot;com.google.android.gms:play-services-auth:21.2.0&quot;)<br>   implementation(&quot;androidx.credentials:credentials:1.3.0-beta02&quot;)<br><br>   //Viewmodel<br>   implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.8.1&quot;)<br>}</pre><h3>Firebase Setup</h3><p>To start with Firebase Authentication, you need to set up a Firebase project and integrate it with your Android app. Follow these steps:</p><h4>Step 1: Create a Firebase Project</h4><ol><li>Go to the Firebase Console.</li><li>Click on “Add project” and follow the instructions to create a new project.</li><li>Add your Android app to the project by following the setup steps provided in the Firebase Console.</li></ol><h4>Step 2: Enable Firebase Authentication</h4><ol><li>In the Firebase Console, navigate to “Authentication” and select the “Sign-in method” tab.</li><li>Enable the “Google” sign-in method. You’ll return here later to use the Web client ID.</li></ol><h3>Implementing Google Sign-In Function</h3><p>Here’s a detailed explanation of how to implement Google Sign-In in your Android app using Firebase Authentication.</p><h4>Step 1: Obtain Web Client ID</h4><p>You need to get the Web Client ID from the Firebase Console:</p><ol><li>Go to the Firebase Console.</li></ol><p>2. Navigate to the “Authentication” section and select the “Google” sign-in method.</p><p>3. Copy the Web Client ID from the Web SDK configuration section. You’ll use this ID in your code.</p><h4>Step 2: Implement Sign-In Function</h4><p>The following Kotlin function handles the Google Sign-In process:</p><pre>private suspend fun googleSignIn(context: Context): Flow&lt;Result&lt;AuthResult&gt;&gt; {<br>    val firebaseAuth = FirebaseAuth.getInstance()<br>    return callbackFlow {<br>        try {<br>            // Initialize Credential Manager<br>            val credentialManager: CredentialManager = CredentialManager.create(context)<br>            <br>            // Generate a nonce (a random number used once)<br>            val ranNonce: String = UUID.randomUUID().toString()<br>            val bytes: ByteArray = ranNonce.toByteArray()<br>            val md: MessageDigest = MessageDigest.getInstance(&quot;SHA-256&quot;)<br>            val digest: ByteArray = md.digest(bytes)<br>            val hashedNonce: String = digest.fold(&quot;&quot;) { str, it -&gt; str + &quot;%02x&quot;.format(it) }<br><br>            // Set up Google ID option<br>            val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()<br>                .setFilterByAuthorizedAccounts(false)                <br>                .setServerClientId(&quot;YOUR_WEB_CLIENT_ID&quot;)<br>                .setNonce(hashedNonce)<br>                .build()<br><br>            // Request credentials<br>            val request: GetCredentialRequest = GetCredentialRequest.Builder()<br>                .addCredentialOption(googleIdOption)<br>                .build()<br><br>            // Get the credential result<br>            val result = credentialManager.getCredential(context, request)<br>            val credential = result.credential<br><br>            // Check if the received credential is a valid Google ID Token<br>            if (credential is CustomCredential &amp;&amp; credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {<br>                val googleIdTokenCredential =<br>                    GoogleIdTokenCredential.createFrom(credential.data)<br>                val authCredential =<br>                    GoogleAuthProvider.getCredential(googleIdTokenCredential.idToken, null)<br>                val authResult = firebaseAuth.signInWithCredential(authCredential).await()<br>                trySend(Result.success(authResult))<br>            } else {<br>                throw RuntimeException(&quot;Received an invalid credential type&quot;)<br>            }<br>        } catch (e: GetCredentialCancellationException) {<br>            trySend(Result.failure(Exception(&quot;Sign-in was canceled. Please try again.&quot;)))<br><br>        } catch (e: Exception) {<br>            trySend(Result.failure(e))<br>        }<br>        awaitClose { }<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>Credential Manager</strong>: Manages the retrieval of user credentials.</li><li><strong>Nonce</strong>: A random number used to ensure the security of the authentication request.</li><li><strong>Google ID Option</strong>: Configures the Google Sign-In parameters.</li><li><strong>Credential Request</strong>: Sends a request to get the user’s credentials.</li><li><strong>Credential Check</strong>: Verifies the type of credential received.</li><li><strong>Firebase Authentication</strong>: Uses the received credentials to sign in the user via Firebase.</li></ul><h3>UI Implementation</h3><p>Create a composable function for the Google Sign-In button, styled according to <a href="https://developers.google.com/identity/branding-guidelines">Google’s branding guidelines</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooSFniHHHwVjOS1UdCgM_A.png" /></figure><pre>@Composable<br>fun LoginScreen(<br>    viewModel: LoginViewModel = LoginViewModel(),<br>) {<br>    val isDarkTheme = isSystemInDarkTheme()<br>    val context = LocalContext.current as Activity<br>    val onClick = { viewModel.handleGoogleSignIn(context) }<br><br>    Box(<br>        contentAlignment = Alignment.Center,<br>        modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerHigh)<br>    ) {<br>        Surface(<br>            shape = CircleShape,<br>            color = when (isDarkTheme) {<br>                true -&gt; Color(0xFF131314)<br>                false -&gt; Color(0xFFFFFFFF)<br>            },<br>            modifier = Modifier<br>                .height(50.dp)<br>                .width(260.dp)<br>                .clip(CircleShape)<br>                .border(<br>                    BorderStroke(<br>                        width = 1.dp,<br>                        color = when (isDarkTheme) {<br>                            true -&gt; Color(0xFF8E918F)<br>                            false -&gt; Color.Transparent<br>                        }<br>                    ),<br>                    shape = CircleShape<br>                )<br>                .clickable { onClick() }<br>        ) {<br>            Row(<br>                verticalAlignment = Alignment.CenterVertically,<br>                modifier = Modifier.padding(vertical = 5.dp)<br>            ) {<br>                Spacer(modifier = Modifier.width(14.dp))<br>                Image(<br>                    painterResource(id = R.drawable.icons8_google),<br>                    contentDescription = null,<br>                    modifier = Modifier.padding(vertical = 5.dp)<br>                )<br>                Spacer(modifier = Modifier.weight(1f))<br>                Text(text = &quot;Continue with Google&quot;)<br>                Spacer(modifier = Modifier.weight(1f))<br>            }<br>        }<br><br>    }<br>}</pre><h4>Explanation</h4><ul><li><strong>LoginScreen</strong>: A composable function to render the Google Sign-In button.</li><li><strong>ViewModel Integration</strong>: Handles the sign-in logic.</li><li><strong>UI Customization</strong>: Adjusts the appearance based on the system’s dark theme.</li></ul><h4>ViewModel</h4><p>To manage the Google Sign-In process, create a LoginViewModel:</p><pre>class LoginViewModel() : ViewModel() {<br>    fun handleGoogleSignIn(context: Context) {<br>        viewModelScope.launch {<br>            googleSignIn(context).collect { result -&gt;<br>                result.fold(<br>                    onSuccess = {<br>                       // Handle success<br>                    },<br>                    onFailure = { e -&gt;<br>                        // Handle error<br>                    }<br>                )<br>            }<br>        }<br>    }<br><br>    private suspend fun googleSignIn(context: Context): Flow&lt;Result&lt;AuthResult&gt;&gt; {<br>      // The Google Sign-In function as detailed earlier<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>ViewModel</strong>: Manages UI-related data in a lifecycle-conscious way.</li><li><strong>handleGoogleSignIn</strong>: Initiates the Google Sign-In process.</li><li><strong>googleSignIn</strong>: The previously defined sign-in function.</li></ul><h3>Conclusion</h3><p>Implementing Google Sign-In with Firebase Authentication on Android provides a quick and secure way for users to access your app. This integration not only simplifies the sign-in process but also ensures robust security, making it an ideal choice for modern Android applications. By following this guide, you can efficiently implement Google Sign-In and provide a seamless login experience for your users.</p><p>Feel free to expand upon this guide to suit the specific needs of your app. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4e75b6bd97d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Theming in Jetpack Compose with Jetpack DataStore and View Models]]></title>
            <link>https://medium.com/@TonyGnk/dynamic-theming-in-jetpack-compose-with-jetpack-datastore-and-view-models-f7f56cb3a99e?source=rss-fc66e55e776c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f56cb3a99e</guid>
            <category><![CDATA[material-theming]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[TonyGnk]]></dc:creator>
            <pubDate>Sun, 12 May 2024 18:03:51 GMT</pubDate>
            <atom:updated>2024-05-12T19:06:49.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article explores the implementation of dynamic theming in a Jetpack Compose application using Jetpack DataStore and View Models.</p><p>Dynamic theming allows users to personalize the app’s look and feel by letting them choose between light, dark, or system themes. It goes a step further with Material You by enabling dynamic colors, which seamlessly adapt the UI based on the user’s wallpaper.</p><p>We’ll delve into how DataStore helps you persistently store user preferences, while View Models provide a clean way to manage and expose this data within your composables, allowing for seamless theme adjustments based on user choices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qgrr6jRiAigN8TWhmVh8IQ.png" /><figcaption>Final Result</figcaption></figure><h3>Dependencies</h3><p>In your `build.gradle.kts` file, add the following dependencies:</p><pre>dependencies {<br>  implementation(&quot;androidx.datastore:datastore-preferences:1.1.1&quot;)<br>  implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0&quot;)<br>}</pre><blockquote>Check latest version <a href="https://developer.android.com/topic/libraries/architecture/datastore">here</a></blockquote><h3>Setup DataStore</h3><h4>1. Creating a DataStore Repository</h4><p>This section explains how to create a StoreRepository class to manage theme preferences using Jetpack DataStore.</p><pre>// Key for storing dynamic theme preference<br>const val IS_DYNAMIC_THEME = &quot;is_dynamic_theme&quot;<br>const val THEME_TYPE = &quot;theme_type&quot;<br><br>enum class ThemeType { SYSTEM, LIGHT, DARK }</pre><p>The class defines constants for storing theme preference keys (IS_DYNAMIC_THEME, THEME_TYPE), and a ThemeType enum representing different theme options (system, light, dark).</p><pre>class StoreRepository(private val dataStore: DataStore&lt;Preferences&gt;) {<br>    private companion object {<br>        val isDynamicTheme = booleanPreferencesKey(IS_DYNAMIC_THEME)<br>        val themeType = intPreferencesKey(THEME_TYPE)<br>    }<br><br>    val isDynamicThemeFlow: Flow&lt;Boolean&gt; = dataStore.data.map { preferences -&gt;<br>        preferences[isDynamicTheme] ?: false<br>    }<br><br>    val themeTypeFlow: Flow&lt;ThemeType&gt; = dataStore.data.map { preferences -&gt;<br>        ThemeType.entries[preferences[themeType] ?: 0]<br>    }<br><br>    fun setDynamicTheme(value: Boolean, scope: CoroutineScope) {<br>        scope.launch {<br>            dataStore.edit { preferences -&gt;<br>                preferences[isDynamicTheme] = value<br>            }<br>        }<br>    }<br><br>    fun setThemeType(value: ThemeType, scope: CoroutineScope) {<br>        scope.launch {<br>            dataStore.edit { preferences -&gt;<br>                preferences[themeType] = value.ordinal<br>            }<br>        }<br>    }<br>}</pre><p>It also provides methods to retrieve theme preferences (isDynamicThemeFlow, themeTypeFlow) as flows, and functions to update theme preferences (setDynamicTheme, setThemeType) using coroutines.</p><blockquote><strong>Note</strong>: We take the scope as parameter and use it once without having to call the extra lamda launch every time we have to call it</blockquote><h4>2. Initializing DataStore in Application Class</h4><p>This class uses the dataStore by preferencesDataStore delegate to conveniently create a DataStore instance named “app_preferences”. The onCreate method initializes the storeRepository with this DataStore instance.</p><pre>private val Context.dataStore by preferencesDataStore(&quot;app_preferences&quot;)<br><br>class ApplicationSetup : Application() {<br>    lateinit var storeRepository: StoreRepository<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        storeRepository = StoreRepository(dataStore)<br>    }<br>}</pre><p>Finally, we update the AndroidManifest.xml to set the application class name to ApplicationSetup.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;application<br>        android:name=&quot;.ApplicationSetup&quot;<br>        ...<br>        &gt;<br>    &lt;/application&gt;<br><br>&lt;/manifest&gt;</pre><h3>Observing Theme Preferences in Theme.kt</h3><h4>1. Creating View Models and Observing DataStore</h4><p>We create a ModelProvider object that provides a centralized factory for creating view models. The viewModelFactory lambda allows us to specify how view models are created.</p><pre>object ModelProvider {<br>    val Factory = viewModelFactory {<br>        initializer {<br>            //Not yet implemented<br>            ThemeModel(appViewModelProvider().storeRepository)<br>        }<br><br>        initializer {<br>            //Not yet implemented<br>            SettingsModel(appViewModelProvider().storeRepository)<br>        }<br>    }<br>}<br><br><br>fun CreationExtras.appViewModelProvider(): ApplicationSetup =<br>    (this[AndroidViewModelFactory.APPLICATION_KEY] as ApplicationSetup)</pre><p>The appViewModelProvider function is a helper function used within the factory to safely retrieve the ApplicationSetup instance from the context.</p><h4>2. Create the Theme View Model</h4><pre>class ThemeModel(storeRepository: StoreRepository) : ViewModel() {<br>    // Observe the DataStore flow for dynamic theme preference<br>    val isDynamic: StateFlow&lt;Boolean&gt; =<br>        storeRepository.isDynamicThemeFlow.map { it }.stateIn(<br>            scope = viewModelScope,<br>            started = SharingStarted.WhileSubscribed(5_000),<br>            initialValue = true<br>        )<br><br>    // Observe the DataStore flow for theme type preference<br>    val isDarkTheme: StateFlow&lt;ThemeType&gt; =<br>        storeRepository.themeTypeFlow.map { it }.stateIn(<br>            scope = viewModelScope,<br>            started = SharingStarted.WhileSubscribed(5_000),<br>            initialValue = ThemeType.SYSTEM<br>        )<br>}</pre><h4>3. Update the Theme.kt</h4><p>We retrieve the ThemeModel instance using the viewModel composable with the ModelProvider.Factory.</p><p>We then use collectAsState on both isDynamic and isDarkTheme StateFlow properties within the view model. This allows us to observe the latest theme preference values within the composable function’s lifecycle.</p><pre>@Composable<br>fun MyTheme(content: @Composable () -&gt; Unit) {<br>    val model: ThemeModel = viewModel(factory = ModelProvider.Factory)<br><br>    val isDynamic by model.isDynamic.collectAsState()<br>    val isDarkTheme = when (model.isDarkTheme.collectAsState().value) {<br>        ThemeType.SYSTEM -&gt; isSystemInDarkTheme()<br>        ThemeType.LIGHT -&gt; false<br>        ThemeType.DARK -&gt; true<br>    }<br><br>    val colorScheme = when {<br>        isDynamic &amp;&amp; Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S -&gt; {<br>            val context = LocalContext.current<br>            if (isDarkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(<br>                context<br>            )<br>        }<br>        isDarkTheme -&gt; darkScheme<br>        else -&gt; lightScheme<br>    }<br><br>    // For status bar<br>    val view = LocalView.current<br>    if (!view.isInEditMode) {<br>        SideEffect {<br>            val window = (view.context as Activity).window<br>            window.navigationBarColor = colorScheme.surfaceContainerHighest.toArgb()<br>            WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !isDarkTheme<br>            WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = !isDarkTheme<br>        }<br>    }<br>    MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content)<br>}</pre><h3>Building the Settings Screen</h3><h4>1. Creating the Settings ViewModel and Data Classes</h4><p>The SettingsModel class manages settings data and interacts with the DataStore (storeRepository) to update theme preferences.</p><p>It holds properties for dialog visibility (dialogVisibly), current theme (themeType), and dynamic theme preference (isDynamic).</p><pre>class SettingsModel(private val storeRepository: StoreRepository) : ViewModel() {<br><br>    val dialogVisibly = MutableStateFlow(false)<br><br>    val themeType: StateFlow&lt;ThemeTypeState&gt; =<br>        storeRepository.themeTypeFlow.map { ThemeTypeState(it) }.stateIn(<br>            scope = viewModelScope,<br>            started = SharingStarted.WhileSubscribed(5_000),<br>            initialValue = ThemeTypeState(ThemeType.SYSTEM)<br>        )<br><br>    val isDynamic: StateFlow&lt;Boolean&gt; =<br>        storeRepository.isDynamicThemeFlow.map { it }.stateIn(<br>            scope = viewModelScope,<br>            started = SharingStarted.WhileSubscribed(5_000),<br>            initialValue = false<br>        )<br><br>    fun setDialogVisibility(value: Boolean) {<br>        dialogVisibly.value = value<br>    }<br><br>    fun updateIsDynamicTheme() {<br>        storeRepository.setDynamicTheme(!isDynamic.value, viewModelScope)<br>    }<br><br>    fun updateThemeType(themeType: ThemeType) {<br>        storeRepository.setThemeType(themeType, viewModelScope)<br>    }<br>}</pre><p>Also it provides functions to update these and persist changes in DataStore.</p><pre>//Holds selected theme and theme options.<br>data class ThemeTypeState(<br>    val selectedRadio: ThemeType,<br>    val radioItems: List&lt;RadioItem&gt; = listOf(<br>        RadioItem(ThemeType.SYSTEM, &quot;System&quot;),<br>        RadioItem(ThemeType.LIGHT, &quot;Light&quot;),<br>        RadioItem(ThemeType.DARK, &quot;Dark&quot;),<br>    ),<br>)<br><br>//Simple holder for theme type and its title (for radio buttons).<br>data class RadioItem(val value: ThemeType, val title: String)</pre><h4>2. Building the Settings Screen with Composable Functions</h4><p>The main SettingScreen retrieves data from the SettingsModel using viewModel and collectAsState to access state flows for visibility, theme type, and dynamic theme preference. It then conditionally renders the theme selection dialog and displays a column containing an app bar text and the ThemeAndDynamicTile composable.</p><pre>@Composable<br>@Preview<br>fun SettingScreen() {<br>    val model: SettingsModel = viewModel(factory = ModelProvider.Factory)<br>    val dialogVisibly by model.dialogVisibly.collectAsState()<br>    val isDynamic by model.isDynamic.collectAsState()<br>    val themeType by model.themeType.collectAsState()<br><br>    Surface(<br>        //...<br>    ) {<br>        if (dialogVisibly) ThemeDialog(model, themeType)<br><br>        Column(<br>          //...<br>        ) {<br>            AppBarText() // Assume this displays an app bar title<br>            ThemeAndDynamicTile(model, isDynamic)<br>        }<br>    }<br>}</pre><p>The ThemeAndDynamicTile composable displays theme and dynamic theme options. It uses isDynamic to conditionally display the toggle for dynamic theme selection.</p><pre>@Composable<br>fun ThemeAndDynamicTile(model: SettingsModel, isDynamic: Boolean) {<br>    Column {<br>        Text( text = &quot;Appearance&quot; )<br>        Column {<br>            ListItem(<br>                headlineContent = { Text( &quot;Theme&quot; ) }, <br>                trailingContent = {<br>                    Icon(<br>                        imageVector = Icons.AutoMirrored.Default.KeyboardArrowRight,<br>                        contentDescription = &quot;Change App Theme&quot;<br>                    )<br>                },<br>                modifier = Modifier<br>                    .clickable { model.setDialogVisibility(true) }<br>            )<br>            HorizontalDivider()<br>            // Hide Dynamic Color option for pre-Android 12 devices<br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S)<br>                ListItem(<br>                    headlineContent = { Text( &quot;Dynamic Color&quot; ) }, <br>                    trailingContent = {<br>                        Switch(<br>                            checked = (isDynamic),<br>                            onCheckedChange = { model.updateIsDynamicTheme() }<br>                        )<br>                    },<br>                    modifier = Modifier<br>                        .clickable { model.updateIsDynamicTheme() }<br>                )<br>        }<br>    }<br>}</pre><p>The ThemeDialog composable displays a dialog for choosing the app theme. It uses the RadioButtons composable to present available theme options as radio buttons with corresponding text labels.</p><p>Lastly, RadioButtons loops through theme options, presenting them with radio buttons and updating the chosen theme in the model.</p><pre>@Composable<br>fun ThemeDialog(model: SettingsModel, state: ThemeTypeState) {<br>    AlertDialog(<br>        onDismissRequest = { model.setDialogVisibility(false) },<br>        title = { Text(text = &quot;Choose Theme&quot;) },<br>        text = { RadioButtons(model, state) },<br>        confirmButton = {<br>            Button( onClick = { model.setDialogVisibility(false) }<br>            ) { Text(&quot;Confirm&quot;) }<br>        }<br>    )<br>}<br><br>@Composable<br>fun RadioButtons(model: SettingsModel, state: ThemeTypeState) {<br>    Column {<br>        state.radioItems.forEach {<br>            Row(<br>                modifier = Modifier.selectable(<br>                    selected = (it.value == state.selectedRadio),<br>                    onClick = { model.updateThemeType(it.value) }<br>                )<br>            ) {<br>                RadioButton(<br>                    selected = (it.value == state.selectedRadio),<br>                    onClick = { model.updateThemeType(it.value) }<br>                )<br>                Text(text = it.title)<br>            }<br>        }<br>    }<br>}</pre><h3>That’s it!</h3><p>With DataStore, you can seamlessly manage theme preferences and provide a dynamic user experience. This approach allows users to personalize their app’s look and feel effortlessly, enhancing their overall enjoyment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RukZPNPrR9I-HIG0" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f56cb3a99e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>