Skip to content

Commit

Permalink
Fixed undo on first click into editor
Browse files Browse the repository at this point in the history
- Migrated to material3
- Updated other libraries
- Renamed androidExample project as it caused gradle problems?
  • Loading branch information
Wavesonics committed Jan 31, 2023
1 parent b894e7e commit 76a1a9b
Show file tree
Hide file tree
Showing 40 changed files with 128 additions and 70 deletions.
13 changes: 8 additions & 5 deletions androidExample/build.gradle.kts → android/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
val compose_version: String by extra
val library_version: String by extra
val android_compile_sdk: String by extra
val android_target_sdk: String by extra
val android_min_sdk: String by extra

plugins {
id("org.jetbrains.compose")
Expand All @@ -14,19 +17,19 @@ dependencies {
implementation(project(":richtexteditor"))
implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.5.1")
implementation("androidx.activity:activity-compose:1.5.1")
implementation("androidx.activity:activity-compose:1.6.1")

implementation("androidx.compose.ui:ui:$compose_version")
implementation("androidx.compose.material:material:$compose_version")
implementation("androidx.compose.ui:ui-tooling-preview:$compose_version")
}

android {
compileSdk = 31
compileSdk = android_compile_sdk.toInt()
defaultConfig {
applicationId = "com.darkrockstudios.example.richtexteditor"
minSdk = 24
targetSdk = 31
minSdk = android_min_sdk.toInt()
targetSdk = android_target_sdk.toInt()
versionCode = 1
versionName = "1.0-SNAPSHOT"
}
Expand All @@ -45,7 +48,7 @@ android {
}
packagingOptions {
resources {
excludes += mutableSetOf("/META-INF/{AL2.0,LGPL2.1}")
excludes += setOf("/META-INF/{AL2.0,LGPL2.1}")
}
}
}
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Surface
Expand All @@ -30,6 +31,22 @@ import com.darkrockstudios.richtexteditor.ui.defaultRichTextFieldStyle
import com.darkrockstudios.richtexteditor.ui.defaultRichTextStyle
import kotlin.random.Random

private val text =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
"Why do we use it?\n" +
"\n" +
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\n" +
"\n" +
"Where does it come from?\n" +
"\n" +
"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\n" +
"\n" +
"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.\n" +
"Where can I get some?\n" +
"\n" +
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc."


class MainActivity : ComponentActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
Expand All @@ -39,7 +56,8 @@ class MainActivity : ComponentActivity() {
Surface(modifier = Modifier.fillMaxSize()) {
var value by remember {
mutableStateOf(
RichTextValue.get(
RichTextValue.fromString(
text = text,
// Optional parameter; leave it blank if you want to use provided styles
// But if you want to customize the user experience you're free to do that
// by providing a custom StyleMapper
Expand Down Expand Up @@ -68,7 +86,8 @@ class MainActivity : ComponentActivity() {
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray)
.padding(16.dp),
.padding(16.dp)
.verticalScroll(rememberScrollState()),
value = value,
textStyle = defaultRichTextStyle().copy(
textColor = Color.Black,
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Surface
Expand All @@ -23,6 +24,20 @@ import com.darkrockstudios.richtexteditor.ui.defaultRichTextFieldStyle
import com.darkrockstudios.richtexteditor.ui.defaultRichTextStyle
import kotlin.random.Random

private val text =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
"Why do we use it?\n" +
"\n" +
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\n" +
"\n" +
"Where does it come from?\n" +
"\n" +
"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\n" +
"\n" +
"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.\n" +
"Where can I get some?\n" +
"\n" +
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc."

fun main() = application {
Window(
Expand All @@ -32,7 +47,8 @@ fun main() = application {
Surface(modifier = Modifier.fillMaxSize()) {
var value by remember {
mutableStateOf(
RichTextValue.get(
RichTextValue.fromString(
text = text,
// Optional parameter; leave it blank if you want to use provided styles
// But if you want to customize the user experience you're free to do that
// by providing a custom StyleMapper
Expand Down Expand Up @@ -61,7 +77,8 @@ fun main() = application {
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray)
.padding(16.dp),
.padding(16.dp)
.verticalScroll(rememberScrollState()),
value = value,
textStyle = defaultRichTextStyle().copy(
textColor = Color.Black,
Expand Down
13 changes: 8 additions & 5 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
kotlin.code.style=official
kotlin.native.enableDependencyPropagation=false
library_version=1.3.0
library_version=1.4.0
android.useAndroidX=true
kotlin.version=1.7.0
agp.version=7.2.1
compose_version=1.2.0
jetbrains_compose_version=1.2.0-alpha01-dev753
android_compile_sdk=33
android_target_sdk=33
android_min_sdk=26
kotlin.version=1.8.0
agp.version=7.3.1
compose_version=1.3.0
jetbrains_compose_version=1.3.0
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
4 changes: 2 additions & 2 deletions local.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Tue Jun 21 01:05:59 PDT 2022
sdk.dir=C\:\\Users\\adam\\AppData\\Local\\Android\\Sdk
#Thu Dec 29 17:59:06 PST 2022
sdk.dir=C\:\\Users\\adamw\\AppData\\Local\\Android\\Sdk
15 changes: 9 additions & 6 deletions richtexteditor/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import org.jetbrains.compose.compose
import java.net.URI

val library_version: String by extra
val kotlin_version = extra["kotlin.version"] as String
val android_compile_sdk: String by extra
val android_target_sdk: String by extra
val android_min_sdk: String by extra

plugins {
kotlin("multiplatform")
Expand Down Expand Up @@ -33,13 +35,14 @@ kotlin {
}
}
sourceSets {
@OptIn(org.jetbrains.compose.ExperimentalComposeLibrary::class)
val commonMain by getting {
dependencies {
api(compose.runtime)
api(compose.foundation)
api(compose.material)
api(compose.material3)
implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlin_version")
api("com.arkivanov.essenty:parcelable:0.6.0")
api("com.arkivanov.essenty:parcelable:0.10.0")
}
}
val commonTest by getting {
Expand Down Expand Up @@ -154,11 +157,11 @@ signing {
}

android {
compileSdk = 31
compileSdk = android_compile_sdk.toInt()
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdk = 24
targetSdk = 31
minSdk = android_min_sdk.toInt()
targetSdk = android_target_sdk.toInt()
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
package com.darkrockstudios.richtexteditor.common

actual fun systemLineSeparator(): String = System.lineSeparator()
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext

actual fun systemLineSeparator(): String = System.lineSeparator()
actual val defaultDispatcher: CoroutineContext = Dispatchers.Default
actual val uiDispatcher: CoroutineContext = Dispatchers.Main
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
package com.darkrockstudios.richtexteditor.common

import kotlin.coroutines.CoroutineContext

@Suppress("NO_ACTUAL_FOR_EXPECT")
expect fun systemLineSeparator(): String
expect fun systemLineSeparator(): String

expect val defaultDispatcher: CoroutineContext
expect val uiDispatcher: CoroutineContext
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,14 @@ abstract class RichTextValue {
): RichTextValue = RichTextValueImpl(styleMapper).apply {
restoreFromSnapshot(snapshot)
}

fun fromString(
text: String,
styleMapper: StyleMapper = StyleMapper()
): RichTextValue {
val value = RichTextValueImpl(styleMapper)
value.restoreFromSnapshot(RichTextValueSnapshot(text = text))
return value
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,12 @@ internal typealias StyleRange<T> = AnnotatedStringBuilder.MutableRange<T>

internal class RichTextValueImpl(override val styleMapper: StyleMapper) : RichTextValue() {

private val annotatedStringBuilder = AnnotatedStringBuilder()
val annotatedStringBuilder = AnnotatedStringBuilder()
private var selection: TextRange = TextRange.Zero
private var composition: TextRange? = null

private var historyOffset: Int = 0
private val historySnapshots = mutableListOf(
RichTextValueSnapshot.fromAnnotatedStringBuilder(
annotatedStringBuilder,
selectionPosition = selection.start
)
)
private val historySnapshots = mutableListOf<RichTextValueSnapshot>()
private val currentSnapshot: RichTextValueSnapshot?
get() = historySnapshots.elementAtOrNull(
historySnapshots.lastIndex - historyOffset
Expand Down Expand Up @@ -278,33 +273,36 @@ internal class RichTextValueImpl(override val styleMapper: StyleMapper) : RichTe

override fun redo() = this.copy().redoInternal()

override fun updatedValueAndStyles(value: TextFieldValue): Boolean {
override fun updatedValueAndStyles(newValue: TextFieldValue): Boolean {
var updateText = true
val updatedStyles = annotatedStringBuilder.updateStyles(
previousSelection = selection,
currentValue = value.text,
currentValue = newValue.text,
onCollapsedParagraphsCallback = { updateText = false },
onEscapeParagraphCallback = {
updateText = false
annotatedStringBuilder.text = it
}
)

if (updatedStyles || annotatedStringBuilder.text != value.text ||
selection != value.selection || composition != value.composition
if (updatedStyles || annotatedStringBuilder.text != newValue.text ||
selection != newValue.selection || composition != newValue.composition
) {
if (updateText) {
annotatedStringBuilder.text = value.text
selection = value.selection
composition = value.composition
annotatedStringBuilder.text = newValue.text
selection = newValue.selection
composition = newValue.composition
}

currentSnapshot?.run {
if (value.text.length - text.length >= MIN_LENGTH_DIFFERENCE) {
val snapshot = currentSnapshot
if (snapshot != null) {
if (newValue.text.length - snapshot.text.length >= MIN_LENGTH_DIFFERENCE) {
updateHistory()
} else if (value.text != text) {
} else if (newValue.text != snapshot.text) {
clearRedoStack()
}
} else if (newValue.text.isNotEmpty()) {
updateHistory()
}

return true
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.darkrockstudios.richtexteditor.ui

import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
Expand Down Expand Up @@ -32,8 +32,8 @@ fun RichText(

@Composable
fun defaultRichTextStyle() = RichTextStyle(
textStyle = MaterialTheme.typography.body1,
textColor = MaterialTheme.colors.onPrimary,
textStyle = MaterialTheme.typography.bodySmall,
textColor = MaterialTheme.colorScheme.onSurface,
)

data class RichTextStyle(
Expand Down
Loading

0 comments on commit 76a1a9b

Please sign in to comment.