Artifacts.svelte 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { onMount, getContext, createEventDispatcher } from 'svelte';
  4. const i18n = getContext('i18n');
  5. const dispatch = createEventDispatcher();
  6. import { chatId, showArtifacts, showControls } from '$lib/stores';
  7. import XMark from '../icons/XMark.svelte';
  8. import { copyToClipboard, createMessagesList } from '$lib/utils';
  9. import ArrowsPointingOut from '../icons/ArrowsPointingOut.svelte';
  10. import Tooltip from '../common/Tooltip.svelte';
  11. import SvgPanZoom from '../common/SVGPanZoom.svelte';
  12. import ArrowLeft from '../icons/ArrowLeft.svelte';
  13. export let overlay = false;
  14. export let history;
  15. let messages = [];
  16. let contents: Array<{ type: string; content: string }> = [];
  17. let selectedContentIdx = 0;
  18. let copied = false;
  19. let iframeElement: HTMLIFrameElement;
  20. $: if (history) {
  21. messages = createMessagesList(history, history.currentId);
  22. getContents();
  23. } else {
  24. messages = [];
  25. getContents();
  26. }
  27. const getContents = () => {
  28. contents = [];
  29. messages.forEach((message) => {
  30. if (message?.role !== 'user' && message?.content) {
  31. const codeBlockContents = message.content.match(/```[\s\S]*?```/g);
  32. let codeBlocks = [];
  33. if (codeBlockContents) {
  34. codeBlockContents.forEach((block) => {
  35. const lang = block.split('\n')[0].replace('```', '').trim().toLowerCase();
  36. const code = block.replace(/```[\s\S]*?\n/, '').replace(/```$/, '');
  37. codeBlocks.push({ lang, code });
  38. });
  39. }
  40. let htmlContent = '';
  41. let cssContent = '';
  42. let jsContent = '';
  43. codeBlocks.forEach((block) => {
  44. const { lang, code } = block;
  45. if (lang === 'html') {
  46. htmlContent += code + '\n';
  47. } else if (lang === 'css') {
  48. cssContent += code + '\n';
  49. } else if (lang === 'javascript' || lang === 'js') {
  50. jsContent += code + '\n';
  51. }
  52. });
  53. const inlineHtml = message.content.match(/<html>[\s\S]*?<\/html>/gi);
  54. const inlineCss = message.content.match(/<style>[\s\S]*?<\/style>/gi);
  55. const inlineJs = message.content.match(/<script>[\s\S]*?<\/script>/gi);
  56. if (inlineHtml) {
  57. inlineHtml.forEach((block) => {
  58. const content = block.replace(/<\/?html>/gi, ''); // Remove <html> tags
  59. htmlContent += content + '\n';
  60. });
  61. }
  62. if (inlineCss) {
  63. inlineCss.forEach((block) => {
  64. const content = block.replace(/<\/?style>/gi, ''); // Remove <style> tags
  65. cssContent += content + '\n';
  66. });
  67. }
  68. if (inlineJs) {
  69. inlineJs.forEach((block) => {
  70. const content = block.replace(/<\/?script>/gi, ''); // Remove <script> tags
  71. jsContent += content + '\n';
  72. });
  73. }
  74. if (htmlContent || cssContent || jsContent) {
  75. const renderedContent = `
  76. <!DOCTYPE html>
  77. <html lang="en">
  78. <head>
  79. <meta charset="UTF-8">
  80. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  81. <${''}style>
  82. body {
  83. background-color: white; /* Ensure the iframe has a white background */
  84. }
  85. ${cssContent}
  86. </${''}style>
  87. </head>
  88. <body>
  89. ${htmlContent}
  90. <${''}script>
  91. ${jsContent}
  92. </${''}script>
  93. </body>
  94. </html>
  95. `;
  96. contents = [...contents, { type: 'iframe', content: renderedContent }];
  97. } else {
  98. // Check for SVG content
  99. for (const block of codeBlocks) {
  100. if (block.lang === 'svg' || (block.lang === 'xml' && block.code.includes('<svg'))) {
  101. contents = [...contents, { type: 'svg', content: block.code }];
  102. }
  103. }
  104. }
  105. }
  106. });
  107. if (contents.length === 0) {
  108. showControls.set(false);
  109. showArtifacts.set(false);
  110. toast.error($i18n.t('No HTML, CSS, or JavaScript content found.'));
  111. }
  112. selectedContentIdx = contents ? contents.length - 1 : 0;
  113. };
  114. function navigateContent(direction: 'prev' | 'next') {
  115. console.log(selectedContentIdx);
  116. selectedContentIdx =
  117. direction === 'prev'
  118. ? Math.max(selectedContentIdx - 1, 0)
  119. : Math.min(selectedContentIdx + 1, contents.length - 1);
  120. console.log(selectedContentIdx);
  121. }
  122. const iframeLoadHandler = () => {
  123. iframeElement.contentWindow.addEventListener(
  124. 'click',
  125. function (e) {
  126. const target = e.target.closest('a');
  127. if (target && target.href) {
  128. e.preventDefault();
  129. const url = new URL(target.href, iframeElement.baseURI);
  130. if (url.origin === window.location.origin) {
  131. iframeElement.contentWindow.history.pushState(
  132. null,
  133. '',
  134. url.pathname + url.search + url.hash
  135. );
  136. } else {
  137. console.log('External navigation blocked:', url.href);
  138. }
  139. }
  140. },
  141. true
  142. );
  143. // Cancel drag when hovering over iframe
  144. iframeElement.contentWindow.addEventListener('mouseenter', function (e) {
  145. e.preventDefault();
  146. iframeElement.contentWindow.addEventListener('dragstart', (event) => {
  147. event.preventDefault();
  148. });
  149. });
  150. };
  151. const showFullScreen = () => {
  152. if (iframeElement.requestFullscreen) {
  153. iframeElement.requestFullscreen();
  154. } else if (iframeElement.webkitRequestFullscreen) {
  155. iframeElement.webkitRequestFullscreen();
  156. } else if (iframeElement.msRequestFullscreen) {
  157. iframeElement.msRequestFullscreen();
  158. }
  159. };
  160. onMount(() => {});
  161. </script>
  162. <div class=" w-full h-full relative flex flex-col bg-gray-50 dark:bg-gray-850">
  163. <div class="w-full h-full flex-1 relative">
  164. {#if overlay}
  165. <div class=" absolute top-0 left-0 right-0 bottom-0 z-10"></div>
  166. {/if}
  167. <div class="absolute pointer-events-none z-50 w-full flex items-center justify-start p-4">
  168. <button
  169. class="self-center pointer-events-auto p-1 rounded-full bg-white dark:bg-gray-850"
  170. on:click={() => {
  171. showArtifacts.set(false);
  172. }}
  173. >
  174. <ArrowLeft className="size-3.5 text-gray-900 dark:text-white" />
  175. </button>
  176. </div>
  177. <div class=" absolute pointer-events-none z-50 w-full flex items-center justify-end p-4">
  178. <button
  179. class="self-center pointer-events-auto p-1 rounded-full bg-white dark:bg-gray-850"
  180. on:click={() => {
  181. dispatch('close');
  182. showControls.set(false);
  183. showArtifacts.set(false);
  184. }}
  185. >
  186. <XMark className="size-3.5 text-gray-900 dark:text-white" />
  187. </button>
  188. </div>
  189. <div class="flex-1 w-full h-full">
  190. <div class=" h-full flex flex-col">
  191. {#if contents.length > 0}
  192. <div class="max-w-full w-full h-full">
  193. {#if contents[selectedContentIdx].type === 'iframe'}
  194. <iframe
  195. bind:this={iframeElement}
  196. title="Content"
  197. srcdoc={contents[selectedContentIdx].content}
  198. class="w-full border-0 h-full rounded-none"
  199. sandbox="allow-scripts allow-forms allow-same-origin"
  200. on:load={iframeLoadHandler}
  201. ></iframe>
  202. {:else if contents[selectedContentIdx].type === 'svg'}
  203. <SvgPanZoom
  204. className=" w-full h-full max-h-full overflow-hidden"
  205. svg={contents[selectedContentIdx].content}
  206. />
  207. {/if}
  208. </div>
  209. {:else}
  210. <div class="m-auto font-medium text-xs text-gray-900 dark:text-white">
  211. {$i18n.t('No HTML, CSS, or JavaScript content found.')}
  212. </div>
  213. {/if}
  214. </div>
  215. </div>
  216. </div>
  217. {#if contents.length > 0}
  218. <div class="flex justify-between items-center p-2.5 font-primar text-gray-900 dark:text-white">
  219. <div class="flex items-center space-x-2">
  220. <div class="flex items-center gap-0.5 self-center min-w-fit" dir="ltr">
  221. <button
  222. class="self-center p-1 hover:bg-black/5 dark:hover:bg-white/5 dark:hover:text-white hover:text-black rounded-md transition disabled:cursor-not-allowed"
  223. on:click={() => navigateContent('prev')}
  224. disabled={contents.length <= 1}
  225. >
  226. <svg
  227. xmlns="http://www.w3.org/2000/svg"
  228. fill="none"
  229. viewBox="0 0 24 24"
  230. stroke="currentColor"
  231. stroke-width="2.5"
  232. class="size-3.5"
  233. >
  234. <path
  235. stroke-linecap="round"
  236. stroke-linejoin="round"
  237. d="M15.75 19.5 8.25 12l7.5-7.5"
  238. />
  239. </svg>
  240. </button>
  241. <div class="text-xs self-center dark:text-gray-100 min-w-fit">
  242. {$i18n.t('Version {{selectedVersion}} of {{totalVersions}}', {
  243. selectedVersion: selectedContentIdx + 1,
  244. totalVersions: contents.length
  245. })}
  246. </div>
  247. <button
  248. class="self-center p-1 hover:bg-black/5 dark:hover:bg-white/5 dark:hover:text-white hover:text-black rounded-md transition disabled:cursor-not-allowed"
  249. on:click={() => navigateContent('next')}
  250. disabled={contents.length <= 1}
  251. >
  252. <svg
  253. xmlns="http://www.w3.org/2000/svg"
  254. fill="none"
  255. viewBox="0 0 24 24"
  256. stroke="currentColor"
  257. stroke-width="2.5"
  258. class="size-3.5"
  259. >
  260. <path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
  261. </svg>
  262. </button>
  263. </div>
  264. </div>
  265. <div class="flex items-center gap-1">
  266. <button
  267. class="copy-code-button bg-none border-none text-xs bg-gray-50 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-800 transition rounded-md px-1.5 py-0.5"
  268. on:click={() => {
  269. copyToClipboard(contents[selectedContentIdx].content);
  270. copied = true;
  271. setTimeout(() => {
  272. copied = false;
  273. }, 2000);
  274. }}>{copied ? $i18n.t('Copied') : $i18n.t('Copy')}</button
  275. >
  276. {#if contents[selectedContentIdx].type === 'iframe'}
  277. <Tooltip content={$i18n.t('Open in full screen')}>
  278. <button
  279. class=" bg-none border-none text-xs bg-gray-50 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-800 transition rounded-md p-0.5"
  280. on:click={showFullScreen}
  281. >
  282. <ArrowsPointingOut className="size-3.5" />
  283. </button>
  284. </Tooltip>
  285. {/if}
  286. </div>
  287. </div>
  288. {/if}
  289. </div>