https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
i

iamthevoid

11/26/2021, 4:08 PM
I want to add spaces in text field. I’d did all what i can for achieve this, but looks like some kind of visual artifacts exists even after i ensure that offsets in
OffsetMapping
mapping correctly. I’ll add scratch in thread. Logic next When price entering then
filter
of
VisualTransformation
calls and i creating
Price
object. It contains three values integer(string, with spaces), fractional(string) and boolean describes is there comma or no. This object stores in my class, implements
VisualTransformation
and
OffsetMapper
. mapping of offset happens based on this object. It stores price (with spaces) and price payload. For example if
price
is
8 994,34
payload
should be
8994,34
(witout spaces). Based on this values i am calculating offset. I even simulate this in scratch file [screenshot] and all looks good. But in dynamic, when i interact with input - i see artifacts! i For example: when i try to backspace number then backspaced not the number, that i want to backspace, but backspace previous, but not always And then i understood. The problem is that offsets that i calculate is dynamic. That changes when integer length changes. Example
9 999
offset at position 2, and when i enter another digit whenever
99 989
offset now at position 3. So when i backspace digit offset positions also changes during editing. This situation can be solved?
val entered = "7345678"
val price = "7 345 678"

fun originalToTransformed(offset: Int): Int {

    val ensureOffset = minOf(offset, entered.length)
    val entered = entered.subSequence(0, minOf(ensureOffset + 1, entered.length))
    var spacesCount = 0
    for (i in entered.indices) {
        if (entered[i] != price[i + spacesCount] && price.getOrNull(i + spacesCount + 1) != null) {
            spacesCount++
        }
    }
    return ensureOffset + spacesCount
}

fun transformedToOriginal(offset: Int): Int {
    val ensureOffset = minOf(price.length, offset)
    return offset - price.subSequence(0, ensureOffset + 1).trim()
        .sumOf { if (it == ' ') 1L else 0L }.toInt()
}
t

tad

11/28/2021, 3:19 AM
I will paste some code if you remind me on Monday, as I've written a currency input for Compose
c

Carl Benson

11/29/2021, 8:21 AM
I would love to see this example too @tad 🙏
i

iamthevoid

11/29/2021, 8:24 AM
I’d fixed my case, but i want too ) I fixed by reduce complexity. Before i had sealed class with values Empty, Incorrect, Price - and use it in Visual Transformations in
filter
fun, but i should filter input in
onValueChange
at first. I go that way and operate with price only in Visual Transformation
m

Mayank Saini

02/10/2022, 10:26 AM
@tad Can you paste your code for currency input? ^
i

iamthevoid

02/12/2022, 6:50 AM
data class AmountInput(val rubles: Int, val pennies: Penny, val hasComma: Boolean) {

    val amount: Amount
        get() = Amount(rubles, pennies.value ?: 0)

    fun originalToTransformed(offset: Int): Int {
        val transformed = format(beautify = true)

        var count = 0
        var index = 0

        transformed.forEachIndexed { i, c ->
            if (c != SPACE) count++
            if (count == offset) {
                index = i + 1
                return@forEachIndexed
            }
        }
        return if (offset > index) transformed.length else index
    }

    fun transformedToOriginal(offset: Int): Int {
        val transformed = format(beautify = true)
        return with(transformed.substring(0, minOf(offset, transformed.length))) {
            length - count { it == SPACE }
        }
    }

    fun format(beautify: Boolean = false): String {
        return buildString {
            rubles.toString().apply {
                if (beautify) {
                    val mod = length % GROUP_RUBLES_BY
                    val formatted = foldRightIndexed(initial = "", { index, char, acc ->
                        "${if (index % GROUP_RUBLES_BY == mod) "$SPACE" else ""}$char$acc"
                    }).trim()
                    append(formatted)
                } else {
                    append(this)
                }
            }
            if (hasComma) append(COMMA)
            with(pennies) {
                if (enteredCount > 0) {
                    value?.also {
                        append(it.toString().take(enteredCount).padStart(enteredCount, ZERO))
                    }
                }
            }
        }
    }

    companion object {

        private const val SPACE = ' '
        private const val COMMA = ','
        private const val ZERO = '0'

        private const val GROUP_RUBLES_BY = 3
        private const val PENNIES_INPUT_LENGTH = 2

        fun from(value: String, rublesMaxLength: Int): AmountInput {
            return value.split(Regex("[.,]+"))
                .let { splitties ->
                    val rubles = splitties.getOrNull(0)?.take(rublesMaxLength)?.toIntOrNull() ?: 0

                    val penniesString = splitties.getOrNull(1)?.removeLeadingExcessZeroes()
                    val pennies = penniesString?.take(PENNIES_INPUT_LENGTH)
                        ?.padEnd(PENNIES_INPUT_LENGTH, ZERO)?.toIntOrNull()

                    AmountInput(
                        rubles,
                        Penny(pennies, minOf(PENNIES_INPUT_LENGTH, penniesString.orEmpty().length)),
                        hasComma = splitties.size > 1
                    )
                }
        }

        fun from(amount: Amount, rublesMaxLength: Int, hasComma: Boolean, enteredCount: Int): AmountInput {
            val rubles = amount.rubles.toString().takeLast(rublesMaxLength).toInt()
            return AmountInput(rubles, with(amount) { Penny(pennies, enteredCount) }, hasComma)
        }

        private fun String.removeLeadingExcessZeroes() =
            foldIndexed("", { index, acc, c ->
                if (acc.isEmpty() && c == ZERO && getOrNull(index + 1) == ZERO) acc else "$acc$c"
            })
    }

    data class Penny(val value: Int?, val enteredCount: Int)
}
class AmountTransformation(private val integersCount: Int) : VisualTransformation, OffsetMapping {

    private lateinit var input: AmountInput

    override fun filter(text: AnnotatedString): TransformedText {
        input = AmountInput.from(text.toString(), integersCount)
        return TransformedText(AnnotatedString(input.format(beautify = true)), this)
    }

    override fun originalToTransformed(offset: Int): Int {
        return input.originalToTransformed(offset)
    }

    override fun transformedToOriginal(offset: Int): Int {
        return input.transformedToOriginal(offset)
    }
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
internal fun EnterAmountTextField(
    priceIntegersCount: Int,
    amount: Amount,
    onValueChange: (Amount) -> Unit
) {
    val transformation by remember { mutableStateOf(AmountTransformation(integersCount = priceIntegersCount)) }
    var enteredCount by remember { mutableStateOf(0) }
    var hasComma by remember { mutableStateOf(false) }

    Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
        Row(
            modifier = Modifier.wrapContentWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            BasicTextField(
                AmountInput.from(amount, priceIntegersCount, hasComma, enteredCount).format(),
                onValueChange = { newValue ->
                    val input = AmountInput.from(newValue, priceIntegersCount)
                    hasComma = input.hasComma
                    enteredCount = input.pennies.enteredCount
                    onValueChange(input.amount)
                },
                singleLine = true,
                modifier = Modifier.width(IntrinsicSize.Min),
                textStyle = Typography.heading0.copy(fontWeight = FontWeight.Normal),
                cursorBrush = SolidColor(Palette.Primary.Purple),
                keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
                visualTransformation = transformation
            )
            Text(
                stringResource(R.string.currency),
                style = Typography.heading0.copy(fontWeight = FontWeight.Normal, color = Palette.Transparent.o25)
            )
        }

        AnimatedVisibility(PaymentRuleTypes.isAmountInvalid(amount)) {
            Text(amount.errorText(), style = Typography.descriptionRegular.copy(color = Palette.System.Error))
        }
    }
}
data class Amount(val value: Int) {

    constructor(
        rubles: Int = 0,
        pennies: Int = 0
    ) : this((rubles + pennies / kopeckInRuble) * kopeckInRuble + pennies % kopeckInRuble)

    val rubles: Int
        get() = value / kopeckInRuble

    val pennies: Int
        get() = value.absoluteValue % kopeckInRuble

    fun formatPrice(showCurrencySign: Boolean = false): String =
        "${formatPrice()}${if (showCurrencySign) " ₽" else "" }"

    fun formatPrice(): String = buildString {
        val integer = "$rubles".replace(NON_DIGIT_REGEX, DASH)
        mutableListOf<CharSequence>().apply {
            for (i in integer.length downTo 1 step DIGIT_GROUP_LENGTH) {
                add(integer.subSequence(maxOf(i - DIGIT_GROUP_LENGTH, 0), i))
            }
        }.reversed().apply {
            forEachIndexed { index, charSequence ->
                append(charSequence)
                if (index != lastIndex && charSequence != DASH) append(' ')
            }
        }
        if (pennies > 0) append(",$pennies")
    }

    operator fun plus(amount: Amount): Amount = Amount(value + amount.value)

    operator fun minus(amount: Amount): Amount = Amount(value - amount.value)

    operator fun times(times: Int): Amount = Amount(value * times)

    operator fun compareTo(amount: Amount): Int = value.compareTo(amount.value)

    operator fun compareTo(amount: Int): Int = value.compareTo(amount)

    fun positive(): Boolean = value > 0

    fun negative(): Boolean = value < 0

    companion object {

        private const val kopeckInRuble = 100

        private const val DIGIT_GROUP_LENGTH = 3

        private const val DASH = "−"

        private val NON_DIGIT_REGEX by lazy { Regex("\\D") }

        val DEFAULT = Amount(-1)
        val EMPTY = Amount(0)
    }
}