Artifacts.svelte 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 { showArtifacts, showControls } from '$lib/stores';
  7. import XMark from '../icons/XMark.svelte';
  8. import { createMessagesList } from '$lib/utils';
  9. export let overlay = false;
  10. export let history;
  11. let messages = [];
  12. let contents: Array<{ content: string }> = [];
  13. let selectedContentIdx = 0;
  14. let iframeElement: HTMLIFrameElement;
  15. $: if (history) {
  16. messages = createMessagesList(history, history.currentId);
  17. getContents();
  18. } else {
  19. messages = [];
  20. getContents();
  21. }
  22. function getContents() {
  23. contents = [];
  24. messages.forEach((message) => {
  25. if (message.content) {
  26. let htmlContent = '';
  27. let cssContent = '';
  28. let jsContent = '';
  29. const codeBlocks = message.content.match(/```[\s\S]*?```/g);
  30. if (codeBlocks) {
  31. codeBlocks.forEach((block) => {
  32. const lang = block.split('\n')[0].replace('```', '').trim().toLowerCase();
  33. const code = block.replace(/```[\s\S]*?\n/, '').replace(/```$/, '');
  34. if (lang === 'html') {
  35. htmlContent += code + '\n';
  36. } else if (lang === 'css') {
  37. cssContent += code + '\n';
  38. } else if (lang === 'javascript' || lang === 'js') {
  39. jsContent += code + '\n';
  40. }
  41. });
  42. }
  43. const inlineHtml = message.content.match(/<html>[\s\S]*?<\/html>/gi);
  44. const inlineCss = message.content.match(/<style>[\s\S]*?<\/style>/gi);
  45. const inlineJs = message.content.match(/<script>[\s\S]*?<\/script>/gi);
  46. if (inlineHtml) {
  47. inlineHtml.forEach((block) => {
  48. const content = block.replace(/<\/?html>/gi, ''); // Remove <html> tags
  49. htmlContent += content + '\n';
  50. });
  51. }
  52. if (inlineCss) {
  53. inlineCss.forEach((block) => {
  54. const content = block.replace(/<\/?style>/gi, ''); // Remove <style> tags
  55. cssContent += content + '\n';
  56. });
  57. }
  58. if (inlineJs) {
  59. inlineJs.forEach((block) => {
  60. const content = block.replace(/<\/?script>/gi, ''); // Remove <script> tags
  61. jsContent += content + '\n';
  62. });
  63. }
  64. if (htmlContent || cssContent || jsContent) {
  65. const renderedContent = `
  66. <!DOCTYPE html>
  67. <html lang="en">
  68. <head>
  69. <meta charset="UTF-8">
  70. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  71. <${''}style>
  72. body {
  73. background-color: white; /* Ensure the iframe has a white background */
  74. }
  75. ${cssContent}
  76. </${''}style>
  77. </head>
  78. <body>
  79. ${htmlContent}
  80. <${''}script>
  81. ${jsContent}
  82. </${''}script>
  83. </body>
  84. </html>
  85. `;
  86. contents = [...contents, { content: renderedContent }];
  87. }
  88. }
  89. });
  90. if (messages.length === 0 || (messages.at(-1)?.done && contents.length === 0)) {
  91. showArtifacts.set(false);
  92. showControls.set(false);
  93. }
  94. selectedContentIdx = contents ? contents.length - 1 : 0;
  95. }
  96. function navigateContent(direction: 'prev' | 'next') {
  97. console.log(selectedContentIdx);
  98. selectedContentIdx =
  99. direction === 'prev'
  100. ? Math.max(selectedContentIdx - 1, 0)
  101. : Math.min(selectedContentIdx + 1, contents.length - 1);
  102. console.log(selectedContentIdx);
  103. }
  104. const iframeLoadHandler = () => {
  105. iframeElement.contentWindow.addEventListener(
  106. 'click',
  107. function (e) {
  108. const target = e.target.closest('a');
  109. if (target && target.href) {
  110. e.preventDefault();
  111. const url = new URL(target.href, iframeElement.baseURI);
  112. if (url.origin === window.location.origin) {
  113. iframeElement.contentWindow.history.pushState(
  114. null,
  115. '',
  116. url.pathname + url.search + url.hash
  117. );
  118. } else {
  119. console.log('External navigation blocked:', url.href);
  120. }
  121. }
  122. },
  123. true
  124. );
  125. // Cancel drag when hovering over iframe
  126. iframeElement.contentWindow.addEventListener('mouseenter', function (e) {
  127. e.preventDefault();
  128. iframeElement.contentWindow.addEventListener('dragstart', (event) => {
  129. event.preventDefault();
  130. });
  131. });
  132. };
  133. </script>
  134. <div class=" w-full h-full relative flex flex-col bg-gray-850">
  135. <div class="w-full h-full flex-1 relative">
  136. {#if overlay}
  137. <div class=" absolute top-0 left-0 right-0 bottom-0 z-10"></div>
  138. {/if}
  139. <div class=" absolute z-50 w-full flex items-center justify-end p-4 dark:text-gray-100">
  140. <button
  141. class="self-center"
  142. on:click={() => {
  143. dispatch('close');
  144. showControls.set(false);
  145. showArtifacts.set(false);
  146. }}
  147. >
  148. <XMark className="size-4" />
  149. </button>
  150. </div>
  151. <div class="flex-1 w-full h-full">
  152. <div class=" h-full flex flex-col">
  153. {#if contents.length > 0}
  154. <div class="max-w-full w-full h-full">
  155. <iframe
  156. bind:this={iframeElement}
  157. title="Content"
  158. srcdoc={contents[selectedContentIdx].content}
  159. class="w-full border-0 h-full rounded-none"
  160. sandbox="allow-scripts allow-forms allow-same-origin"
  161. on:load={iframeLoadHandler}
  162. ></iframe>
  163. </div>
  164. {:else}
  165. <div class="m-auto text-xs">{$i18n.t('No HTML, CSS, or JavaScript content found.')}</div>
  166. {/if}
  167. </div>
  168. </div>
  169. </div>
  170. {#if contents.length > 0}
  171. <div class="flex justify-between items-center p-2.5 font-primary">
  172. <div class="flex items-center space-x-2">
  173. <div class="flex self-center min-w-fit" dir="ltr">
  174. <button
  175. 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"
  176. on:click={() => navigateContent('prev')}
  177. disabled={contents.length <= 1}
  178. >
  179. <svg
  180. xmlns="http://www.w3.org/2000/svg"
  181. fill="none"
  182. viewBox="0 0 24 24"
  183. stroke="currentColor"
  184. stroke-width="2.5"
  185. class="size-3.5"
  186. >
  187. <path
  188. stroke-linecap="round"
  189. stroke-linejoin="round"
  190. d="M15.75 19.5 8.25 12l7.5-7.5"
  191. />
  192. </svg>
  193. </button>
  194. <div class="text-xs self-center dark:text-gray-100 min-w-fit">
  195. {$i18n.t('Version {{selectedVersion}} of {{totalVersions}}', {
  196. selectedVersion: selectedContentIdx + 1,
  197. totalVersions: contents.length
  198. })}
  199. </div>
  200. <button
  201. 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"
  202. on:click={() => navigateContent('next')}
  203. disabled={contents.length <= 1}
  204. >
  205. <svg
  206. xmlns="http://www.w3.org/2000/svg"
  207. fill="none"
  208. viewBox="0 0 24 24"
  209. stroke="currentColor"
  210. stroke-width="2.5"
  211. class="size-3.5"
  212. >
  213. <path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
  214. </svg>
  215. </button>
  216. </div>
  217. </div>
  218. </div>
  219. {/if}
  220. </div>