Skip to content

Commit

Permalink
Component to copy to clipboard
Browse files Browse the repository at this point in the history
  • Loading branch information
cquiroz committed Mar 9, 2024
1 parent b82aa9f commit e3d1026
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)) *>
Expand Down
Original file line number Diff line number Diff line change
@@ -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))

0 comments on commit e3d1026

Please sign in to comment.