Artifacts.svelte 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. }
  111. selectedContentIdx = contents ? contents.length - 1 : 0;
  112. };
  113. function navigateContent(direction: 'prev' | 'next') {
  114. console.log(selectedContentIdx);
  115. selectedContentIdx =
  116. direction === 'prev'
  117. ? Math.max(selectedContentIdx - 1, 0)
  118. : Math.min(selectedContentIdx + 1, contents.length - 1);
  119. console.log(selectedContentIdx);
  120. }
  121. const iframeLoadHandler = () => {
  122. iframeElement.contentWindow.addEventListener(
  123. 'click',
  124. function (e) {
  125. const target = e.target.closest('a');
  126. if (target && target.href) {
  127. e.preventDefault();
  128. const url = new URL(target.href, iframeElement.baseURI);
  129. if (url.origin === window.location.origin) {
  130. iframeElement.contentWindow.history.pushState(
  131. null,
  132. '',
  133. url.pathname + url.search + url.hash
  134. );
  135. } else {
  136. console.log('External navigation blocked:', url.href);
  137. }
  138. }
  139. },
  140. true
  141. );
  142. // Cancel drag when hovering over iframe
  143. iframeElement.contentWindow.addEventListener('mouseenter', function (e) {
  144. e.preventDefault();
  145. iframeElement.contentWindow.addEventListener('dragstart', (event) => {
  146. event.preventDefault();
  147. });
  148. });
  149. };
  150. const showFullScreen = () => {
  151. if (iframeElement.requestFullscreen) {
  152. iframeElement.requestFullscreen();
  153. } else if (iframeElement.webkitRequestFullscreen) {
  154. iframeElement.webkitRequestFullscreen();
  155. } else if (iframeElement.msRequestFullscreen) {
  156. iframeElement.msRequestFullscreen();
  157. }
  158. };
  159. onMount(() => {});
  160. </script>
  161. <div class=" w-full h-full relative flex flex-col bg-gray-50 dark:bg-gray-850">
  162. <div class="w-full h-full flex-1 relative">
  163. {#if overlay}
  164. <div class=" absolute top-0 left-0 right-0 bottom-0 z-10"></div>
  165. {/if}
  166. <div class="absolute pointer-events-none z-50 w-full flex items-center justify-start p-4">
  167. <button
  168. class="self-center pointer-events-auto p-1 rounded-full bg-white dark:bg-gray-850"
  169. on:click={() => {
  170. showArtifacts.set(false);
  171. }}
  172. >
  173. <ArrowLeft className="size-3.5 text-gray-900 dark:text-white" />
  174. </button>
  175. </div>
  176. <div class=" absolute pointer-events-none z-50 w-full flex items-center justify-end p-4">
  177. <button
  178. class="self-center pointer-events-auto p-1 rounded-full bg-white dark:bg-gray-850"
  179. on:click={() => {
  180. dispatch('close');
  181. showControls.set(false);
  182. showArtifacts.set(false);
  183. }}
  184. >
  185. <XMark className="size-3.5 text-gray-900 dark:text-white" />
  186. </button>
  187. </div>
  188. <div class="flex-1 w-full h-full">
  189. <div class=" h-full flex flex-col">
  190. {#if contents.length > 0}
  191. <div class="max-w-full w-full h-full">
  192. {#if contents[selectedContentIdx].type === 'iframe'}
  193. <iframe
  194. bind:this={iframeElement}
  195. title="Content"
  196. srcdoc={contents[selectedContentIdx].content}
  197. class="w-full border-0 h-full rounded-none"
  198. sandbox="allow-scripts allow-forms allow-same-origin"
  199. on:load={iframeLoadHandler}
  200. ></iframe>
  201. {:else if contents[selectedContentIdx].type === 'svg'}
  202. <SvgPanZoom
  203. className=" w-full h-full max-h-full overflow-hidden"
  204. svg={contents[selectedContentIdx].content}
  205. />
  206. {/if}
  207. </div>
  208. {:else}
  209. <div class="m-auto font-medium text-xs text-gray-900 dark:text-white">
  210. {$i18n.t('No HTML, CSS, or JavaScript content found.')}
  211. </div>
  212. {/if}
  213. </div>
  214. </div>
  215. </div>
  216. {#if contents.length > 0}
  217. <div class="flex justify-between items-center p-2.5 font-primar text-gray-900 dark:text-white">
  218. <div class="flex items-center space-x-2">
  219. <div class="flex items-center gap-0.5 self-center min-w-fit" dir="ltr">
  220. <button
  221. 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"
  222. on:click={() => navigateContent('prev')}
  223. disabled={contents.length <= 1}
  224. >
  225. <svg
  226. xmlns="http://www.w3.org/2000/svg"
  227. fill="none"
  228. viewBox="0 0 24 24"
  229. stroke="currentColor"
  230. stroke-width="2.5"
  231. class="size-3.5"
  232. >
  233. <path
  234. stroke-linecap="round"
  235. stroke-linejoin="round"
  236. d="M15.75 19.5 8.25 12l7.5-7.5"
  237. />
  238. </svg>
  239. </button>
  240. <div class="text-xs self-center dark:text-gray-100 min-w-fit">
  241. {$i18n.t('Version {{selectedVersion}} of {{totalVersions}}', {
  242. selectedVersion: selectedContentIdx + 1,
  243. totalVersions: contents.length
  244. })}
  245. </div>
  246. <button
  247. 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"
  248. on:click={() => navigateContent('next')}
  249. disabled={contents.length <= 1}
  250. >
  251. <svg
  252. xmlns="http://www.w3.org/2000/svg"
  253. fill="none"
  254. viewBox="0 0 24 24"
  255. stroke="currentColor"
  256. stroke-width="2.5"
  257. class="size-3.5"
  258. >
  259. <path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
  260. </svg>
  261. </button>
  262. </div>
  263. </div>
  264. <div class="flex items-center gap-1">
  265. <button
  266. 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"
  267. on:click={() => {
  268. copyToClipboard(contents[selectedContentIdx].content);
  269. copied = true;
  270. setTimeout(() => {
  271. copied = false;
  272. }, 2000);
  273. }}>{copied ? $i18n.t('Copied') : $i18n.t('Copy')}</button
  274. >
  275. {#if contents[selectedContentIdx].type === 'iframe'}
  276. <Tooltip content={$i18n.t('Open in full screen')}>
  277. <button
  278. 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"
  279. on:click={showFullScreen}
  280. >
  281. <ArrowsPointingOut className="size-3.5" />
  282. </button>
  283. </Tooltip>
  284. {/if}
  285. </div>
  286. </div>
  287. {/if}
  288. </div>