artifact.tsx 6.3 KB

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