artifact.tsx 6.2 KB

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