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
k

kotlinforandroid

06/08/2022, 1:42 PM
tl;dr: Is there a way to hook into the native text line-breaking algorithm (if there is one)? I created a Composable for handling HTML ruby text. It's basically markup that can be used to add additional information to text. It's often used for providing readings in Japanese for example. For that the text is displayed above the Japanese characters (see image). My composable if made out of
RubyText
that contains text and optionally a ruby text that dictate it's reading. These are packed inside a
FlowRow
.The problem I am facing is that I can't control line breaking properly this way. If there is a long slice of text without reading annotations they are packed into the same
RubyText
composable. Thus they cannot break in the middle. Is there a way to hook into the native line-breaking and take advantage of it? Or do I have to re-implement it myself to make my rubied text work properly?
@Composable
fun RubyText(
    text: String,
    ruby: String? = null,
    rubyVisible: Boolean = true,
    style: TextStyle = TextStyle.Default,
) {
    val rubyFontSize = LocalTextStyle.current.fontSize / 2
    val boxHeight = rubyFontSize.toDp()

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Box(modifier = Modifier.requiredHeight(boxHeight + 3.dp)) {
            ruby?.let {
                if (rubyVisible) {
                    Text(text = it, style = TextStyle(fontSize = rubyFontSize))
                }
            }
        }
        Text(text = text, style = style)
    }
}

// This renders the second image (nside of the thread).
fun example2() {
        RubyText(text = "このルールを")
        RubyText(text = "守", ruby = "まも")
        RubyText(text = "るらない")
        RubyText(text = "人", ruby = "ひと")
        RubyText(text = "は")
        RubyText(text = "旅行", ruby = "りょこう")
        RubyText(text = "ができなくなることもあります。")
}
The problem is visible pretty clearly here. Compared to how android natively renders it (third image).
z

Zach Klippenstein (he/him) [MOD]

06/08/2022, 2:45 PM
There's no way to hook into the algorithm, but this seems like something we might be able to support with some other api? Please file a feature request
e

ephemient

06/09/2022, 9:45 AM
HACK:
val (annotatedString, inlineContent) = "このルールを守まもるらない人ひとは旅行りょこうができなくなることもあります。".toRuby()
Text(text = annotatedString, inlineContent = inlineContent)

private val RUBY_REGEX = "\uFFF9([^\uFFF9\uFFFA\uFFFB]*)\uFFFA([^\uFFF9\uFFFA\uFFFB]*)\uFFFB".toRegex()
private fun String.toRuby(): Pair<AnnotatedString, Map<String, InlineTextContent>> {
    val inlineContent = mutableMapOf<String, InlineTextContent>()
    return buildAnnotatedString {
        var position = 0
        for (match in RUBY_REGEX.findAll(this@toRuby)) {
            append(substring(startIndex = position, endIndex = match.range.first))
            position = match.range.last + 1
            val id = match.value
            val (text, annotation) = match.destructured
            appendInlineContent(id, text)
            inlineContent[id] = InlineTextContent(
                placeholder = Placeholder((2 * text.length).em, 3.em, PlaceholderVerticalAlign.Bottom),
                children = {
                    Column(
                        modifier = Modifier.fillMaxHeight(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Bottom,
                    ) {
                        BasicText(text = annotation)
                        BasicText(text = text)
                    }
                }
            )
        }
        append(substring(startIndex = position))
    } to inlineContent
}
of course, something built-in could work much much better than this
you could possibly tweak this to look more-or-less passable on some simple usages, but it really needs more to be built into the text layout so that styling, selection, etc. all work
if you've created a feature request, drop it here so I can it :)
k

kotlinforandroid

06/09/2022, 12:46 PM
@ephemient I didn't create a feature request since I lacked an account for the issue tracker. Could you explain the example above a bit more clearly? What exactly should
toRuby
do?
e

ephemient

06/09/2022, 12:51 PM
it's replacing
\uFFF9..\uFFFA..\uFFFB
(the Unicode interlinear annotations for ruby text, but you could of course use whatever else you want, this is just an example) with inline content inline content means that the string contains "旅行" (which is important for accessibility) but when it is drawn, the given
@Composable
is used instead of that substring https://developer.android.com/reference/kotlin/androidx/compose/foundation/text/InlineTextContent
there isn't a good way to get the placeholder sizing right without having some integration with text layout too, so this is not a great solution, just a stopgap that might work in some use cases
z

Zach Klippenstein (he/him) [MOD]

06/09/2022, 3:01 PM
For future reference, anyone can make an account for free, it's helpful to be able to file requests and bugs.
k

kotlinforandroid

06/09/2022, 4:44 PM
@Zach Klippenstein (he/him) [MOD] I know, I moved away from Google products a couple of years ago. I just don't feel comfortable to have to create a new account just to file a feature request. I am thankful for ephemient.
@ephemient Would you be so kind to edit your feature description to add that, depending on how the text is rendered, the annotation position changes? Japanese (as well as Chinese IIRC) can also be written top to bottom. And vertical lines are then written right to left. In these cases readings are rendered on the right side of the characters (see here: https://en.wikipedia.org/wiki/Furigana). I am not sure if Android/Compose even supports top to bottom text via
Text
or some sibling class.
e

ephemient

06/09/2022, 4:48 PM
neither Android nor web supports top-to-bottom text as far as I know
👍 1
k

kotlinforandroid

06/09/2022, 4:49 PM
Web not directly, but a website could use CSS to render it properly. But this might be out-of-scope for Compose I suppose.
e

ephemient

06/09/2022, 5:05 PM
I am wrong, CSS
writing-mode: vertical-rl
has been implemented in many web engines (very recently): https://caniuse.com/mdn-css_properties_writing-mode_horizontal_vertical_values
and it looks like CSS
ruby-position
has similar support: https://caniuse.com/mdn-css_properties_ruby-position
in any case, I've added a link to https://netflixtechblog.com/implementing-japanese-subtitles-on-netflix-c165fbe61989 to the issue, as it discusses these details about rubies (although unfortunately, their implementation does not appear to be public)
👀 1