Artifacts.svelte 9.5 KB

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