2020-04-17 22:58:56 -07:00
|
|
|
import React, { useState, ReactNode } from "react";
|
|
|
|
|
|
|
|
type CopyableProps = {
|
2020-04-17 23:15:02 -07:00
|
|
|
text: string;
|
|
|
|
children: ReactNode;
|
2020-05-02 12:55:12 +08:00
|
|
|
bottom?: boolean;
|
2020-05-23 16:45:07 +08:00
|
|
|
right?: boolean;
|
2020-04-17 23:15:02 -07:00
|
|
|
};
|
2020-04-17 22:58:56 -07:00
|
|
|
|
2020-04-22 22:01:56 +08:00
|
|
|
type State = "hide" | "copy" | "copied";
|
|
|
|
|
2020-05-23 16:47:35 +08:00
|
|
|
function Popover({
|
|
|
|
state,
|
|
|
|
bottom,
|
2020-06-24 16:07:47 +08:00
|
|
|
right,
|
2020-05-23 16:47:35 +08:00
|
|
|
}: {
|
|
|
|
state: State;
|
|
|
|
bottom?: boolean;
|
|
|
|
right?: boolean;
|
|
|
|
}) {
|
2020-04-22 22:01:56 +08:00
|
|
|
if (state === "hide") return null;
|
|
|
|
const text = state === "copy" ? "Copy" : "Copied!";
|
|
|
|
return (
|
2020-05-23 16:47:35 +08:00
|
|
|
<div
|
|
|
|
className={`popover bs-popover-${bottom ? "bottom" : "top"}${
|
|
|
|
right ? " right" : ""
|
|
|
|
} show`}
|
|
|
|
>
|
2020-05-23 16:45:07 +08:00
|
|
|
<div className={`arrow${right ? " right" : ""}`} />
|
2020-04-22 22:01:56 +08:00
|
|
|
<div className="popover-body">{text}</div>
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
2020-04-17 22:58:56 -07:00
|
|
|
|
2020-05-23 16:45:07 +08:00
|
|
|
function Copyable({ bottom, right, text, children }: CopyableProps) {
|
2020-04-22 22:01:56 +08:00
|
|
|
const [state, setState] = useState<State>("hide");
|
2020-04-17 22:58:56 -07:00
|
|
|
|
|
|
|
const copyToClipboard = () => navigator.clipboard.writeText(text);
|
|
|
|
const handleClick = () =>
|
2020-04-17 23:15:02 -07:00
|
|
|
copyToClipboard().then(() => {
|
2020-04-22 22:01:56 +08:00
|
|
|
setState("copied");
|
|
|
|
setTimeout(() => setState("hide"), 1000);
|
2020-04-17 23:15:02 -07:00
|
|
|
});
|
2020-04-17 22:58:56 -07:00
|
|
|
|
|
|
|
return (
|
2020-05-02 12:55:12 +08:00
|
|
|
<div
|
2020-05-23 16:45:07 +08:00
|
|
|
className="popover-container c-pointer"
|
2020-05-02 12:55:12 +08:00
|
|
|
onClick={handleClick}
|
|
|
|
onMouseOver={() => setState("copy")}
|
|
|
|
onMouseOut={() => state === "copy" && setState("hide")}
|
|
|
|
>
|
|
|
|
{children}
|
2020-05-23 16:45:07 +08:00
|
|
|
<Popover bottom={bottom} right={right} state={state} />
|
2020-04-17 22:58:56 -07:00
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-04-17 23:15:02 -07:00
|
|
|
export default Copyable;
|