artifact.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import { useEffect, useState, useRef, useMemo } from "react";
  2. import { useParams } from "react-router";
  3. import { useWindowSize } from "@/app/utils";
  4. import { IconButton } from "./button";
  5. import { nanoid } from "nanoid";
  6. import ExportIcon from "../icons/share.svg";
  7. import CopyIcon from "../icons/copy.svg";
  8. import DownloadIcon from "../icons/download.svg";
  9. import GithubIcon from "../icons/github.svg";
  10. import LoadingButtonIcon from "../icons/loading.svg";
  11. import Locale from "../locales";
  12. import { Modal, showToast } from "./ui-lib";
  13. import { copyToClipboard, downloadAs } from "../utils";
  14. import { Path, ApiPath, REPO_URL } from "@/app/constant";
  15. import { Loading } from "./home";
  16. import styles from "./artifact.module.scss";
  17. export function HTMLPreview(props: {
  18. code: string;
  19. autoHeight?: boolean;
  20. height?: number | string;
  21. onLoad?: (title?: string) => void;
  22. }) {
  23. const ref = useRef<HTMLIFrameElement>(null);
  24. const frameId = useRef<string>(nanoid());
  25. const [iframeHeight, setIframeHeight] = useState(600);
  26. const [title, setTitle] = useState("");
  27. /*
  28. * https://stackoverflow.com/questions/19739001/what-is-the-difference-between-srcdoc-and-src-datatext-html-in-an
  29. * 1. using srcdoc
  30. * 2. using src with dataurl:
  31. * easy to share
  32. * length limit (Data URIs cannot be larger than 32,768 characters.)
  33. */
  34. useEffect(() => {
  35. const handleMessage = (e: any) => {
  36. const { id, height, title } = e.data;
  37. setTitle(title);
  38. if (id == frameId.current) {
  39. setIframeHeight(height);
  40. }
  41. };
  42. window.addEventListener("message", handleMessage);
  43. return () => {
  44. window.removeEventListener("message", handleMessage);
  45. };
  46. }, []);
  47. const height = useMemo(() => {
  48. if (!props.autoHeight) return props.height || 600;
  49. if (typeof props.height === "string") {
  50. return props.height;
  51. }
  52. const parentHeight = props.height || 600;
  53. return iframeHeight + 40 > parentHeight ? parentHeight : iframeHeight + 40;
  54. }, [props.autoHeight, props.height, iframeHeight]);
  55. const srcDoc = useMemo(() => {
  56. const script = `<script>new ResizeObserver((entries) => parent.postMessage({id: '${frameId.current}', height: entries[0].target.clientHeight}, '*')).observe(document.body)</script>`;
  57. if (props.code.includes("</head>")) {
  58. props.code.replace("</head>", "</head>" + script);
  59. }
  60. return props.code + script;
  61. }, [props.code]);
  62. const handleOnLoad = () => {
  63. if (props?.onLoad) {
  64. props.onLoad(title);
  65. }
  66. };
  67. return (
  68. <iframe
  69. className={styles["artifact-iframe"]}
  70. id={frameId.current}
  71. ref={ref}
  72. sandbox="allow-forms allow-modals allow-scripts"
  73. style={{ height }}
  74. srcDoc={srcDoc}
  75. onLoad={handleOnLoad}
  76. />
  77. );
  78. }
  79. export function ArtifactShareButton({
  80. getCode,
  81. id,
  82. style,
  83. fileName,
  84. }: {
  85. getCode: () => string;
  86. id?: string;
  87. style?: any;
  88. fileName?: string;
  89. }) {
  90. const [loading, setLoading] = useState(false);
  91. const [name, setName] = useState(id);
  92. const [show, setShow] = useState(false);
  93. const shareUrl = useMemo(
  94. () => [location.origin, "#", Path.Artifact, "/", name].join(""),
  95. [name],
  96. );
  97. const upload = (code: string) =>
  98. id
  99. ? Promise.resolve({ id })
  100. : fetch(ApiPath.Artifact, {
  101. method: "POST",
  102. body: code,
  103. })
  104. .then((res) => res.json())
  105. .then(({ id }) => {
  106. if (id) {
  107. return { id };
  108. }
  109. throw Error();
  110. })
  111. .catch((e) => {
  112. showToast(Locale.Export.Artifact.Error);
  113. });
  114. return (
  115. <>
  116. <div className="window-action-button" style={style}>
  117. <IconButton
  118. icon={loading ? <LoadingButtonIcon /> : <ExportIcon />}
  119. bordered
  120. title={Locale.Export.Artifact.Title}
  121. onClick={() => {
  122. setLoading(true);
  123. upload(getCode())
  124. .then((res) => {
  125. if (res?.id) {
  126. setShow(true);
  127. setName(res?.id);
  128. }
  129. })
  130. .finally(() => setLoading(false));
  131. }}
  132. />
  133. </div>
  134. {show && (
  135. <div className="modal-mask">
  136. <Modal
  137. title={Locale.Export.Artifact.Title}
  138. onClose={() => setShow(false)}
  139. actions={[
  140. <IconButton
  141. key="download"
  142. icon={<DownloadIcon />}
  143. bordered
  144. text={Locale.Export.Download}
  145. onClick={() => {
  146. downloadAs(getCode(), `${fileName || name}.html`).then(() =>
  147. setShow(false),
  148. );
  149. }}
  150. />,
  151. <IconButton
  152. key="copy"
  153. icon={<CopyIcon />}
  154. bordered
  155. text={Locale.Chat.Actions.Copy}
  156. onClick={() => {
  157. copyToClipboard(shareUrl).then(() => setShow(false));
  158. }}
  159. />,
  160. ]}
  161. >
  162. <div>
  163. <a target="_blank" href={shareUrl}>
  164. {shareUrl}
  165. </a>
  166. </div>
  167. </Modal>
  168. </div>
  169. )}
  170. </>
  171. );
  172. }
  173. export function Artifact() {
  174. const { id } = useParams();
  175. const [code, setCode] = useState("");
  176. const [loading, setLoading] = useState(true);
  177. const [fileName, setFileName] = useState("");
  178. useEffect(() => {
  179. if (id) {
  180. fetch(`${ApiPath.Artifact}?id=${id}`)
  181. .then((res) => {
  182. if (res.status > 300) {
  183. throw Error("can not get content");
  184. }
  185. return res;
  186. })
  187. .then((res) => res.text())
  188. .then(setCode)
  189. .catch((e) => {
  190. showToast(Locale.Export.Artifact.Error);
  191. });
  192. }
  193. }, [id]);
  194. return (
  195. <div className={styles["artifact"]}>
  196. <div className={styles["artifact-header"]}>
  197. <a href={REPO_URL} target="_blank" rel="noopener noreferrer">
  198. <IconButton bordered icon={<GithubIcon />} shadow />
  199. </a>
  200. <div className={styles["artifact-title"]}>NextChat Artifact</div>
  201. <ArtifactShareButton id={id} getCode={() => code} fileName={fileName} />
  202. </div>
  203. <div className={styles["artifact-content"]}>
  204. {loading && <Loading />}
  205. {code && (
  206. <HTMLPreview
  207. code={code}
  208. autoHeight={false}
  209. height={"100%"}
  210. onLoad={(title) => {
  211. setFileName(title as string);
  212. setLoading(false);
  213. }}
  214. />
  215. )}
  216. </div>
  217. </div>
  218. );
  219. }