-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1050 from gemini-hlsw/copy-text-to-clipboard
Component to copy to clipboard
- Loading branch information
Showing
2 changed files
with
33 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
modules/ui/src/main/scala/lucuma/ui/components/CopyTextToClipboard.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 You can pass an optional callback, will be called when text is | ||
* copied | ||
*/ | ||
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)) |