From e3d102648ebd5a3784be47a7e45a87f8fae9b275 Mon Sep 17 00:00:00 2001 From: Carlos Quiroz Date: Sat, 9 Mar 2024 13:47:50 -0300 Subject: [PATCH] Component to copy to clipboard --- .../lucuma/ui/components/CopyControl.scala | 3 +- .../ui/components/CopyTextToClipboard.scala | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 modules/ui/src/main/scala/lucuma/ui/components/CopyTextToClipboard.scala diff --git a/modules/ui/src/main/scala/lucuma/ui/components/CopyControl.scala b/modules/ui/src/main/scala/lucuma/ui/components/CopyControl.scala index 098f1f7fe..0dae8cea1 100644 --- a/modules/ui/src/main/scala/lucuma/ui/components/CopyControl.scala +++ b/modules/ui/src/main/scala/lucuma/ui/components/CopyControl.scala @@ -6,7 +6,6 @@ package lucuma.ui.components import japgolly.scalajs.react.* import japgolly.scalajs.react.vdom.html_<^.* import lucuma.core.util.NewType -import lucuma.react.clipboard.CopyToClipboard import lucuma.react.common.ReactFnProps import lucuma.ui.syntax.all.given @@ -29,7 +28,7 @@ object CopyControl: LoginStyles.Uncopied.unless(copied.value.value) )( props.label, - CopyToClipboard( + CopyTextToClipboard( text = props.textToCopy, onCopy = (_, copiedCallback) => copied.setState(Copied(copiedCallback)) *> diff --git a/modules/ui/src/main/scala/lucuma/ui/components/CopyTextToClipboard.scala b/modules/ui/src/main/scala/lucuma/ui/components/CopyTextToClipboard.scala new file mode 100644 index 000000000..931cb126d --- /dev/null +++ b/modules/ui/src/main/scala/lucuma/ui/components/CopyTextToClipboard.scala @@ -0,0 +1,32 @@ +// Copyright (c) 2016-2023 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +package lucuma.ui.components + +import japgolly.scalajs.react.* +import japgolly.scalajs.react.vdom.html_<^.* +import lucuma.react.common.* +import org.scalajs.dom.window.navigator + +type OnCopy = (String, Boolean) => Callback + +/** + * Text to be copied to clipboard Optional callback, will be called when text is copied Optional + * copy-to-clipboard options. + */ +case class CopyTextToClipboard( + text: String, + onCopy: OnCopy = (_, _) => Callback.empty +) extends ReactFnPropsWithChildren[CopyTextToClipboard](CopyTextToClipboard.component) + +object CopyTextToClipboard: + private type Props = CopyTextToClipboard + + private def copy(p: CopyTextToClipboard): Callback = + AsyncCallback.fromJsPromise(navigator.clipboard.writeText(p.text)).toCallback.attempt.flatMap { + case Right(_) => p.onCopy(p.text, true) + case Left(_) => p.onCopy(p.text, false) + } + + private val component = ScalaFnComponent + .withChildren[Props]((p, c) => <.div(^.onClick --> copy(p), c))