Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Listen to browser clipboard events and bind them with Compose TextFieldSelectionManager and SelectionManager #1206

Merged
merged 4 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,8 @@ internal fun CoreTextField(
val coroutineScope = rememberCoroutineScope()
val bringIntoViewRequester = remember { BringIntoViewRequester() }

rememberClipboardEventsHandler(manager, state.hasFocus)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what worries me that we are introducing a platform-specific hook to the common so that we do something on one platform. I do realise that this is sometimes unavoidable, all I'm trying to say that before it's unavoidable it worth to invest into investigating any non-invasiva alternative/

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked once again and I reach a conclusion that to implement this feature, we can't avoid changing common. Here is what I base my conclusion on:

  • the events handler needs to "know" some textfield state (what text field is active, what text is selected, etc.). In this case the necesary state is provided by TextFieldSelectionManager (it's internal in foundation module)
  • there is no global state of text fields. TextFieldState and TextFieldSelectionManager are created (and remembered) for every CoreTextField during its initialization. It makse CoreTextField a convenient place to initialize our event handler too.
  • An alternative approach to find a focused node and to dispatch an event to it would require changes in common too, because currently the nodes can handle just key events, but not higher-level clipboard events.

There're similar cases when one platform has a feature/function implemented, while all other platfroms have just empty function body.
The fact that we change the common code here, doesn't require us to urgently upstream this change, because it's an internal implementation detail which doesn't affect android behaviour.


// Focus
val focusModifier = Modifier.textFieldFocusModifier(
enabled = enabled,
Expand Down Expand Up @@ -1191,3 +1193,9 @@ private fun notifyFocusedRect(
internal const val USE_WINDOW_FOCUS_ENABLED = false
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this a flag of a kind? Is this supposed to be set externally somehow?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be honest, I don't know. The logic I added is not related (at least directly) by this flag. It was there before.

internal fun isWindowFocusedBehindFlag(windowInfo: WindowInfo) =
if (USE_WINDOW_FOCUS_ENABLED) windowInfo.isWindowFocused else true

@Composable
internal expect inline fun rememberClipboardEventsHandler(
textFieldSelectionManager: TextFieldSelectionManager,
isFocused: Boolean
)
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.ClipboardManager
import androidx.compose.ui.platform.TextToolbar
Expand Down Expand Up @@ -600,6 +599,22 @@ internal class TextFieldSelectionManager(
setHandleState(HandleState.None)
}

internal fun onCopyWithResult(cancelSelection: Boolean = true): String? {
if (value.selection.collapsed) return null
val selectedText = value.getSelectedText().text

if (!cancelSelection) return selectedText

val newCursorOffset = value.selection.max
val newValue = createTextFieldValue(
annotatedString = value.annotatedString,
selection = TextRange(newCursorOffset, newCursorOffset)
)
onValueChange(newValue)
setHandleState(HandleState.None)
return selectedText
}

/**
* The method for pasting text.
*
Expand All @@ -626,6 +641,21 @@ internal class TextFieldSelectionManager(
undoManager?.forceNextSnapshot()
}

internal fun paste(text: AnnotatedString) {
val newText = value.getTextBeforeSelection(value.text.length) +
text +
value.getTextAfterSelection(value.text.length)
val newCursorOffset = value.selection.min + text.length

val newValue = createTextFieldValue(
annotatedString = newText,
selection = TextRange(newCursorOffset, newCursorOffset)
)
onValueChange(newValue)
setHandleState(HandleState.None)
undoManager?.forceNextSnapshot()
}

/**
* The method for cutting text.
*
Expand Down Expand Up @@ -654,6 +684,25 @@ internal class TextFieldSelectionManager(
undoManager?.forceNextSnapshot()
}

internal fun onCutWithResult(): String? {
if (value.selection.collapsed) return null
val selectedText = value.getSelectedText().text

val newText = value.getTextBeforeSelection(value.text.length) +
value.getTextAfterSelection(value.text.length)
val newCursorOffset = value.selection.min

val newValue = createTextFieldValue(
annotatedString = newText,
selection = TextRange(newCursorOffset, newCursorOffset)
)
onValueChange(newValue)
setHandleState(HandleState.None)
undoManager?.forceNextSnapshot()

return selectedText
}

/*@VisibleForTesting*/
internal fun selectAll() {
val newValue = createTextFieldValue(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.compose.foundation.text

import androidx.compose.foundation.text.selection.TextFieldSelectionManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.ui.text.AnnotatedString
import kotlinx.browser.document
import org.w3c.dom.clipboard.ClipboardEvent
import org.w3c.dom.events.Event
import org.w3c.dom.events.EventListener

@Composable
@NonRestartableComposable
internal actual inline fun rememberClipboardEventsHandler(
textFieldSelectionManager: TextFieldSelectionManager,
isFocused: Boolean
) {
if (isFocused) {
DisposableEffect(textFieldSelectionManager) {

val onCopy = EventListenerWrapper { event ->
val textToCopy = textFieldSelectionManager.onCopyWithResult()
if (textToCopy != null && event is ClipboardEvent) {
event.clipboardData?.setData("text/plain", textToCopy)
event.preventDefault()
}
}

val onPaste = EventListenerWrapper { event ->
if (event is ClipboardEvent) {
val textToPaste = event.clipboardData?.getData("text/plain") ?: ""
event.preventDefault()
textFieldSelectionManager.paste(AnnotatedString(textToPaste))
}
}

val onCut = EventListenerWrapper { event ->
if (event is ClipboardEvent) {
val cutText = textFieldSelectionManager.onCutWithResult()
event.clipboardData?.setData("text/plain", cutText ?: "")
event.preventDefault()
}
}

document.addEventListener("copy", onCopy)
document.addEventListener("paste", onPaste)
document.addEventListener("cut", onCut)

return@DisposableEffect onDispose {
document.removeEventListener("copy", onCopy)
document.removeEventListener("paste", onPaste)
document.removeEventListener("cut", onCut)
}
}
}
}

private fun EventListenerWrapper(handler: (Event) -> Unit): EventListener =
EventListener { handler(it) }
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a new file. It was renamed from KeyMapping.js.kt + updated for clipboard related key events

* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.compose.foundation.text

import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.isMetaPressed
import androidx.compose.ui.input.key.key
import org.jetbrains.skiko.OS
import org.jetbrains.skiko.hostOs

internal actual val platformDefaultKeyMapping: KeyMapping = createPlatformDefaultKeyMapping(hostOs)

internal fun createPlatformDefaultKeyMapping(platform: OS): KeyMapping {
val keyMapping = when (platform) {
OS.MacOS -> createMacosDefaultKeyMapping()
else -> defaultKeyMapping
}
return object : KeyMapping {
private val clipboardKeys = setOf(Key.C, Key.V, Key.X)

override fun map(event: KeyEvent): KeyCommand? {
val isCtrlOrCmd = if (hostOs.isMacOS) event.isMetaPressed else event.isCtrlPressed
if (isCtrlOrCmd && event.key in clipboardKeys) {
// we let a browser dispatch a clipboard event
return null
}
return keyMapping.map(event)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023 The Android Open Source Project
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,14 +16,13 @@

package androidx.compose.foundation.text

import org.jetbrains.skiko.OS
import org.jetbrains.skiko.hostOs
import androidx.compose.foundation.text.selection.TextFieldSelectionManager
import androidx.compose.runtime.Composable

internal actual val platformDefaultKeyMapping: KeyMapping = createPlatformDefaultKeyMapping(hostOs)

internal fun createPlatformDefaultKeyMapping(platform: OS): KeyMapping {
return when (platform) {
OS.MacOS -> createMacosDefaultKeyMapping()
else -> defaultKeyMapping
}
@Composable
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: github is displaying this incorrectly. File KeyMapping.jsMain.kt was renamed into KeyMapping.web.kt.

But file Actuals.jvm.kt is actually a new file.

internal actual inline fun rememberClipboardEventsHandler(
textFieldSelectionManager: TextFieldSelectionManager,
isFocused: Boolean
) {
// nothing to do
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.compose.foundation.text

import androidx.compose.foundation.text.selection.TextFieldSelectionManager
import androidx.compose.runtime.Composable

@Composable
internal actual inline fun rememberClipboardEventsHandler(
textFieldSelectionManager: TextFieldSelectionManager,
isFocused: Boolean
) {
// nothing to do
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.compose.foundation.text

import androidx.compose.foundation.text.selection.TextFieldSelectionManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.ui.text.AnnotatedString
import kotlinx.browser.document
import org.w3c.dom.clipboard.ClipboardEvent
import org.w3c.dom.events.Event
import org.w3c.dom.events.EventListener

@Composable
@NonRestartableComposable
internal actual inline fun rememberClipboardEventsHandler(
textFieldSelectionManager: TextFieldSelectionManager,
isFocused: Boolean
) {
if (isFocused) {
DisposableEffect(textFieldSelectionManager) {

val onCopy = EventListenerWrapper { event ->
val textToCopy = textFieldSelectionManager.onCopyWithResult()
if (textToCopy != null && event is ClipboardEvent) {
event.clipboardData?.setData("text/plain", textToCopy)
event.preventDefault()
}
}

val onPaste = EventListenerWrapper { event ->
if (event is ClipboardEvent) {
val textToPaste = event.clipboardData?.getData("text/plain") ?: ""
event.preventDefault()
textFieldSelectionManager.paste(AnnotatedString(textToPaste))
}
}

val onCut = EventListenerWrapper { event ->
if (event is ClipboardEvent) {
val cutText = textFieldSelectionManager.onCutWithResult()
event.clipboardData?.setData("text/plain", cutText ?: "")
event.preventDefault()
}
}

document.addEventListener("copy", onCopy)
document.addEventListener("paste", onPaste)
document.addEventListener("cut", onCut)

return@DisposableEffect onDispose {
document.removeEventListener("copy", onCopy)
document.removeEventListener("paste", onPaste)
document.removeEventListener("cut", onCut)
}
}
}
}

private fun EventListenerWrapper(handler: (Event) -> Unit): EventListener =
js("(event) => { handler(event) }")
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.jetbrains.skiko.SkiaLayer
import org.jetbrains.skiko.SkikoInputModifiers
import org.jetbrains.skiko.SkikoKey
import org.jetbrains.skiko.SkikoKeyboardEvent
import org.jetbrains.skiko.SkikoKeyboardEventKind
import org.jetbrains.skiko.SkikoPointerEventKind
import org.w3c.dom.AddEventListenerOptions
Expand Down
Loading