-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathindex.html
More file actions
1023 lines (863 loc) · 38.4 KB
/
index.html
File metadata and controls
1023 lines (863 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<meta name="viewport" content="initial-scale=0.75">
<title>OpenArtifacts</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs/loader.js"></script>
<script>
self.MonacoEnvironment = {
getWorkerUrl: function(moduleId, label) {
return './editor.worker.js';
}
};
let manualEditMode = false;
let manualEditsMade = false;
window.onload = function() {
require.config({ paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs' } });
require(['vs/editor/editor.main'], function() {
let editor = monaco.editor.create(document.getElementById('code-editor'), {
value: '// Generated code will appear here',
language: 'javascript',
automaticLayout: true,
wordWrap: 'on'
});
window.editor = editor;
editor.onDidChangeModelContent(function(e) {
if(manualEditMode === true) {
let currentCode = window.editor.getValue();
fileContents[currentOpenFilename] = currentCode;
manualEditsMade = true;
const refreshButton = document.querySelector('#refresh-button');
refreshButton.classList.remove('hidden');
}
});
});
};
</script>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.logo {
font-size: 30px;
margin-bottom: 3px;
padding-right: 10px;
color: #57392d;
text-shadow: 1px 1px 1px #e2dbd1;
}
.credits {
text-align: center;
font-size: 20px;
line-height: 30px;
display: block;
padding: 10px;
border-radius: 5px;
}
a,
a:visited {
color: #105c64;
}
.container {
display: flex;
flex-direction: column;
height: 100%;
}
iframe {
width: calc(100% - 20px);
height: calc(100% - 30px);
margin: 9px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.form-group {
display: flex;
align-items: top;
margin-bottom: 5px;
font-family: Arial, sans-serif;
}
.form-group label {
width: 150px;
margin-right: 10px;
margin-top: 3px;
text-align: right;
}
.form-group input,
.form-group textarea {
flex: 1;
padding: 5px 10px;
border: none;
border-bottom: 1px solid #ddd;
border-radius: 4px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
color: #333;
}
.form-group textarea {
resize: vertical;
font-size: 14px;
min-height: 150px;
color: #000;
}
.form-group button {
margin-left: 160px;
padding: 10px 15px 10px 15px;
border: none;
font-size: 16px;
border-radius: 4px;
background-color: #4e7850;
color: white;
cursor: pointer;
}
.form-group button .kb-shortcut {
font-size: 15px;
color: #dfd;
background-color: rgba(0, 0, 0, 0.6);
padding: 2px 4px;
margin-left: 10px;
border-radius: 4px;
}
.form-group button:hover {
background-color: #45a049;
}
.tab-section {
display: none;
position: relative;
flex-grow: 1;
overflow-y: auto;
}
.tab-section.current {
display: block;
}
.tabs {
flex-shrink: 0;
display: flex;
justify-content: left;
/* border-bottom: 1px solid #ccc; */
padding: 0 50px;
margin-bottom: 20px;
padding-top: 10px;
background-color: #d3beb4;
}
.tab-btn {
padding: 0px 20px;
font-size: 15px;
position: relative;
color: #57392d;
border: none;
border-bottom: none;
background-color: #f4ebe6;
cursor: pointer;
margin-right: 2px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
box-shadow: inset 0px -10px 10px -10px rgba(0, 0, 0, 0.2);
}
.tab-btn.current {
background-color: #fff;
border-bottom: none;
position: relative;
box-shadow: none;
top: 1px;
}
#tab-form {
padding: 20px;
}
.files-container {
display: flex;
height: calc(100% - 20px);
position: relative;
margin: 0;
padding: 10px;
border-radius: 5px;
overflow: auto;
}
.files-sidebar {
width: 200px;
padding: 20px;
overflow-y: auto;
}
.files-sidebar ul {
list-style-type: none;
padding: 0;
margin: 0;
}
.files-sidebar li {
padding: 5px 10px;
cursor: pointer;
border-radius: 5px;
}
.files-sidebar li.current {
background-color: #f6eded;
}
.files-sidebar li:hover {
outline: 1px solid #ccc;
}
#code-editor {
flex-grow: 1;
height: calc(100% - 20px);
border-left: 1px solid #e2dbd1;
padding: 20px;
overflow-y: scroll;
overflow-x: hidden;
}
.about-container {
max-width: 800px;
margin: 0 auto;
font-family: Arial, sans-serif;
padding: 20px;
font-size: 16px;
}
#refresh-button {
filter: sepia(1);
}
#refresh-button.hidden {
display: none;
}
.loading-indicator {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
}
#download-button {
margin-top: 10px;
background-color: #2f382f;
color: white;
cursor: pointer;
border: none;
border-radius: 4px;
line-height: 30px;
padding: 0 20px;
}
#download-button.hidden {
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="tabs">
<div class='logo'> OpenArtifacts </div>
<button class="tab-btn current" id="button-tab-form" onclick="openTab('tab-form')">Form</button>
<button class="tab-btn" id="button-tab-code" onclick="openTab('tab-code')">Code</button>
<button class="tab-btn" id="button-tab-app" onclick="openTab('tab-app')">
App
<span id="refresh-button" class="hidden">
🔄
</span>
</button>
<button class="tab-btn" id="button-tab-about" onclick="openTab('tab-about')">?</button>
</div>
<div class="tab-section current" id="tab-form">
<form id="api-form">
<div class="form-group">
<label for="api-endpoint"></label>
<div style="font-size: 12px; opacity: 0.6;">
<a href="#" onclick="chooseApi(event, 'openai')">OpenAI</a>,
<!-- <a href="#" onclick="chooseApi(e, 'anthropic')">Anthropic</a>, -->
<a href="#" onclick="chooseApi(event, 'llamacpp')">Llama.cpp</a>,
<a href="#" onclick="chooseApi(event, 'ollama')">Ollama</a>,
<a href="#" onclick="chooseApi(event, 'openrouter')">OpenRouter</a>,
<a href="#" onclick="chooseApi(event, 'groq')">Groq</a>,
Claude (coming soon)
</div>
</div>
<div class="form-group">
<label for="api-endpoint">API Endpoint:</label>
<input type="text" id="api-endpoint" name="api-endpoint"
value="https://api.openai.com/v1/chat/completions">
</div>
<div class="form-group">
<label for="api-key">API key:</label>
<input type="password" id="key" name="api-key" value="" placeholder="sk-xxx-yyyyyyyzzzzzzzz" />
</div>
<div class="form-group">
<label for="model-name">Model Name:</label>
<input type="text" id="model-name" name="model-name" value="gpt-4o">
</div>
<div class="form-group">
<label for="prompt">App Description:</label>
<textarea id="prompt" name="prompt" rows="4"
placeholder="Describe your front-end app in a few sentences"></textarea>
</div>
<div class="form-group">
<button type="submit">Submit <span class="kb-shortcut">⌘+Enter</span></button>
</div>
</form>
<div class="credits">
by <a href="https://x.com/mayfer">murat</a><br />
clone on <a href="https://github.com/mayfer/open-artifacts">github</a>
</div>
</div>
<div class="tab-section" id="tab-code">
<div class="files-container">
<div class="files-sidebar">
<ul id="files-list">
</ul>
<button id="download-button" class="hidden" onclick="downloadZip(fileContents)">
⬇ Download .zip
</button>
<!--
<br />
<button id="upload-button" class="hidden" onclick="triggerFileUpload()">
Upload .zip
</button>
<input type="file" id="fileInput" accept=".zip" style="display: none;" onChange="uploadZip()" />
-->
</div>
<div class="file-content" id="code-editor">
</div>
</div>
</div>
<div class="tab-section" id="tab-app">
<div class="loading-indicator" style="display: none;">
<svg width="100px" height="100px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<style>
.spinner_ajPY {
transform-origin: center;
animation: spinner_AtaB .75s infinite linear;
}
@keyframes spinner_AtaB {
100% { transform: rotate(360deg); }
}
</style>
<path d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z" opacity=".25" fill="#3498db"></path>
<path d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z" class="spinner_ajPY" fill="#566d91"></path>
</svg>
</div>
<iframe></iframe>
</div>
<div class="tab-section" id="tab-about">
<div class="about-container">
<h1>OpenArtifacts</h1>
<p>
OpenArtifacts is a clone of Antrhopic's Claude Artifacts which immediately runs the generated code in the browser.
</p>
<p>
While the Claude version relies on a server to bundle the code, OpenArtifacts runs the bundler (esbuild-wasm) straight in the browser, and uses CDNs for all module dependencies instead of npm-style installers.
</p>
<p>
The result is a single html file that can be opened in any browser, and the code is immediately runnable, even by double clicking the file instead of running a web server.
</p>
<h2>Limitations</h2>
<p>
Due to some hacky tricks required to get the bundler working on browser-side directly, there may be some libraries or file types that are not supported. If you find any, please open an issue on <a href="https://github.com/mayfer/open-artifacts">github</a>.
</p>
<h2>Credits</h2>
<p>
OpenArtifcats is a project by <a href="https://x.com/mayfer">murat</a>. This is a complement project to <a href="https:/appcrapper.com">AppCrapper</a>, which is a similar project that generates both frontend & backend code but requires a server to execute.
</p>
<p>
Clone on <a href="https://github.com/mayfer/open-artifacts">github</a>
</p>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/esbuild-wasm@0.23.0"></script>
<script>
let fileContents = {};
let currentAppendFilename = "";
let currentOpenFilename = "";
function openTab(tabId) {
const tabBtn = document.getElementById(`button-${tabId}`);
const tabSection = document.getElementById(tabId);
document.querySelectorAll('.tab-btn').forEach(tabBtn => {
tabBtn.classList.remove('current');
});
document.querySelectorAll('.tab-section').forEach(tabSection => {
tabSection.classList.remove('current');
});
tabBtn.classList.add('current');
tabSection.classList.add('current');
if(tabId === 'tab-app' && manualEditMode && manualEditsMade) {
renderGeneratedApp(fileContents)
}
}
function chooseApi(e, api) {
e.preventDefault();
const apiEndpoint = document.querySelector('#api-endpoint');
const modelName = document.querySelector('#model-name');
if (api == 'openai') {
apiEndpoint.value = 'https://api.openai.com/v1/chat/completions';
modelName.value = 'gpt-4o-2024-08-06';
} else if (api == 'anthropic') {
apiEndpoint.value = 'https://api.anthropic.com/v1/complete';
} else if (api == 'llamacpp') {
apiEndpoint.value = 'http://localhost:8080/v1/chat/completions';
} else if (api == 'ollama') {
apiEndpoint.value = 'http://localhost:11434/v1/chat/completions';
} else if (api == 'openrouter') {
apiEndpoint.value = 'https://openrouter.ai/api/v1/chat/completions';
modelName.value = 'meta-llama/llama-3.1-405b-instruct';
} else if (api == 'groq') {
apiEndpoint.value = 'https://api.groq.com/openai/v1/chat/completions';
modelName.value = 'llama-3.1-70b-versatile';
}
}
const form = document.getElementById('api-form');
function saveToLocalStorage() {
const formData = {};
form.querySelectorAll('input, textarea').forEach(element => {
formData[element.name] = element.value;
});
localStorage.setItem('apiFormData', JSON.stringify(formData));
}
function loadFromLocalStorage() {
const storedData = localStorage.getItem('apiFormData');
if (storedData) {
const formData = JSON.parse(storedData);
Object.keys(formData).forEach(key => {
const element = form.elements[key];
if (element) {
element.value = formData[key];
}
});
}
}
function addFileToList(new_filename) {
const fileList = document.getElementById('files-list');
fileList.querySelectorAll('li').forEach(li => {
li.classList.remove('current');
});
const fileItem = document.createElement('li');
fileItem.textContent = new_filename;
fileItem.classList.add('current');
fileItem.addEventListener('click', function (e) {
e.preventDefault();
if(manualEditMode) {
const filename = e.target.textContent;
currentOpenFilename = filename;
const fileList = document.getElementById('files-list');
fileList.querySelectorAll('li').forEach(li => {
li.classList.remove('current');
});
e.target.classList.add('current');
// output.textContent = fileContents[filename];
editor.setValue(fileContents[filename]);
} else {
alert("Please wait until the app is generated first. Sorry this is a dumb limitation. Will refactor to support this later.");
}
});
fileList.appendChild(fileItem);
}
window.addEventListener('load', loadFromLocalStorage);
form.addEventListener('input', saveToLocalStorage);
form.addEventListener('submit', function (e) {
e.preventDefault();
saveToLocalStorage();
});
form.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
form.dispatchEvent(new Event('submit'));
}
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
manualEditMode = false;
manualEditsMade = false;
const refreshButton = document.querySelector('#refresh-button');
refreshButton.classList.add('hidden');
const downloadButton = document.querySelector('#download-button');
downloadButton.classList.add('hidden');
window.editor.updateOptions({ readOnly: true });
const iframeElem = document.querySelector('iframe');
iframeElem.src = '';
// empty rendered files list
const filesList = document.getElementById('files-list');
filesList.innerHTML = '';
// const fileContent = document.getElementById('file-content');
// fileContent.textContent = '';
const prompt = form.prompt.value;
const fullprompt = `You are an expert front-end developer. Generate a React component (called App, and render into div #root) that follows the following specifications: ${prompt}\n\n\nStart by generating a code block for a file called README.md, generated just like the other code files. In the readme, list methods you'll likely need for the component(s), the files you'll need, and then immediately generate the code blocks after. Before each readme or code block, name the file in square brackes like this:
[FILENAME: README.md]
\`\`\`markdown
...
\`\`\`
[FILENAME: index.jsx]
\`\`\`jsx
...
\`\`\`
Other notes:
* Do not generate or import css files, only use javascript/react (jsx). You can use styled-components if you prefer.
* The entry point is index.jsx, you MUST generate this file.
* Once code is generated, no further explanation is required.
* If using three.js, use appropriate device pixel ratio
* Make sure all libraries are imported (i.e. it's common to forget three.js addons), or module addons registered if needed (such as chart.js registrables)`;
const apiKey = document.querySelector('#key').value;
const apiEndpoint = document.querySelector('#api-endpoint').value;
const modelName = document.querySelector('#model-name').value;
// const output = window.editor;
const editor = window.editor;
currentAppendFilename = "";
let accumulatedContent = '';
let accumulatorState = "WAITING_FOR_FILENAME";
// output.textContent = '';
editor.setValue('');
openTab('tab-code');
async function processStream(response, editor) {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
let responseText = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
({ buffer, responseText } = processBuffer(buffer, editor, responseText));
}
// Handle any remaining data in the buffer
processChunk(buffer.trim(), editor, responseText);
return responseText;
}
function processBuffer(buffer, editor, responseText) {
while (true) {
const boundary = buffer.indexOf('\n');
if (boundary === -1) break;
const chunk = buffer.slice(0, boundary).trim();
buffer = buffer.slice(boundary + 1);
({ responseText } = processChunk(chunk, editor, responseText));
}
return { buffer, responseText };
}
function appendText(editor, text) {
var model = editor.getModel();
var lastLine = model.getLineCount();
var lastColumn = model.getLineMaxColumn(lastLine);
var range = new monaco.Range(lastLine, lastColumn, lastLine, lastColumn);
model.pushEditOperations([], [{ range: range, text: text }]);
}
function processChunk(chunk, editor, responseText) {
if (chunk.startsWith('data: ')) {
const dataStr = chunk.slice(6).trim();
if (dataStr !== '[DONE]') {
let json;
try {
json = JSON.parse(dataStr);
} catch (e) {
console.error("Error parsing JSON:", e);
}
if (json && json.choices && json.choices.length > 0) {
const content = json.choices[0].delta.content;
if (content) {
accumulatedContent += content;
responseText += content;
}
const fileNameMatches = Array.from(accumulatedContent.matchAll(/\[FILENAME:\s*(.+?)\]/g));
let lastFileName;
try {
lastFileName = fileNameMatches[fileNameMatches.length - 1][1];
} catch (e) {
// console.error("Error parsing file name", e);
}
if(lastFileName) {
const correctedFileName = lastFileName.startsWith("/") ? lastFileName : `/${lastFileName}`;
if (correctedFileName !== currentAppendFilename) {
currentAppendFilename = correctedFileName;
currentOpenFilename = correctedFileName;
editor.setValue('');
addFileToList(currentAppendFilename);
}
const _fileContents = extractFileContents(accumulatedContent);
if(!_fileContents[currentAppendFilename]) {
_fileContents[currentAppendFilename] = '';
}
const prevFileState = fileContents[currentAppendFilename] || '';
const newTextToAppend = _fileContents[currentAppendFilename].slice(prevFileState.length);
appendText(editor, newTextToAppend);
fileContents[currentAppendFilename] = _fileContents[currentAppendFilename];
}
}
}
}
return { responseText };
}
function extractFileContents(text) {
const fileMap = {};
const regex = /\[FILENAME:\s*(.+?)\]\s*```(\w*)\n([\s\S]*?)(```|$)/g;
let match;
while ((match = regex.exec(text)) !== null) {
const [, filename, language, content] = match;
fileMap[(filename.startsWith("/") ? "" : "/") + filename.trim()] = content.trim();
}
return fileMap;
}
async function handleResponse(response, editor) {
if (response.ok) {
const responseText = await processStream(response, editor);
const fileContents = extractFileContents(responseText);
const downloadButton = document.querySelector('#download-button');
downloadButton.classList.remove('hidden');
renderGeneratedApp(fileContents);
openTab('tab-app');
manualEditMode = true;
editor.updateOptions({ readOnly: false });
} else {
const responseText = await response.text();
editor.setValue('Error: ' + responseText);
}
}
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: modelName,
messages: [{ role: 'user', content: fullprompt }],
// provider: {
// "order": [
// "Hyperbolic"
// ],
// },
max_tokens: 4096,
temperature: 0,
stream: true
})
});
handleResponse(response, editor);
});
const htmlWrapper = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<title>iFrame renderer</title>
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module">
[[APP_CODE]]
<\/script>
</body>
</html>
`;
async function renderGeneratedApp(fileContents) {
const loadingIndicator = document.querySelector('.loading-indicator');
loadingIndicator.style.display = 'block';
const refreshButton = document.querySelector('#refresh-button');
refreshButton.classList.add('hidden');
manualEditsMade = false;
await esbuild.initialize({ wasmURL: 'https://cdn.jsdelivr.net/npm/esbuild-wasm@0.23.0/esbuild.wasm' })
async function getLatestVersion(packageName) {
const response = await fetch(`https://registry.npmjs.org/${packageName}`);
const data = await response.json();
return data['dist-tags'].latest;
}
const virtualModules = {
name: 'virtual-modules',
setup(build) {
// Intercept all import/require calls
build.onResolve({ filter: /.*/ }, (args) => {
const resolveImport = (importPath) => {
// Normalize the path
const normalizedPath = importPath.startsWith('/') ? importPath : `/${importPath}`;
const possiblePaths = [
normalizedPath,
`${normalizedPath}.js`,
`${normalizedPath}.jsx`,
`${normalizedPath}.css`,
`${normalizedPath}/index.js`,
`${normalizedPath}/index.jsx`,
];
// Handle relative imports
if (importPath.startsWith('.')) {
const currentDir = args.importer.split('/').slice(0, -1).join('/');
const absolutePath = normalizePath(`${currentDir}/${importPath}`);
possiblePaths.push(
absolutePath,
`${absolutePath}.js`,
`${absolutePath}.jsx`,
`${absolutePath}.css`,
`${absolutePath}/index.js`,
`${absolutePath}/index.jsx`
);
}
for (const path of possiblePaths) {
if (path in fileContents) {
return path;
}
}
return null;
};
const resolvedPath = resolveImport(args.path);
if (resolvedPath) {
return { path: resolvedPath, namespace: 'virtual-modules' };
}
// If no match found in virtual modules, return undefined
// This allows the next plugin (openartifactPlugin) to handle it
return undefined;
});
// Load virtual modules
build.onLoad({ filter: /.*/, namespace: 'virtual-modules' }, (args) => {
if (args.path in fileContents) {
const pathWithoutLeadingDot = args.path.startsWith('.') ? args.path.slice(1) : args.path;
return {
contents: fileContents[pathWithoutLeadingDot],
loader: args.path.endsWith('.jsx') ? 'jsx' : 'js',
};
}
});
},
};
// Helper function to normalize paths
function normalizePath(path) {
const parts = path.split('/');
const result = [];
for (const part of parts) {
if (part === '..') {
result.pop();
} else if (part !== '.' && part !== '') {
result.push(part);
}
}
return '/' + result.join('/');
}
const openartifactPlugin = {
name: 'openartifact-plugin',
setup(build) {
const cache = {};
const module_host = 'https://cdn.jsdelivr.net';
const module_url_prefix = '/npm/';
function extractPackageName(input) {
// Regular expression to match package names
const pattern = /^(?:\/npm\/)?(@?[\w-]+(?:\/[\w-]+)?)/;
const match = input.match(pattern);
return match ? match[1] : null;
}
function extractPackageIdentifier(input) {
// Remove /npm/ prefix and /+esm suffix
let cleaned = input.replace(/^\/npm\//, '').replace(/\/\+esm$/, '');
// Regular expression to match package names with version and additional path
const pattern = /^(@?[\w-]+(?:\/[\w-]+)?)(.*)$/;
const match = cleaned.match(pattern);
if (match) {
const [, packageName, rest] = match;
return packageName + rest;
}
return null;
}
build.onResolve({ filter: /.*/ }, async (args) => {
let packageName, packageUrl;
packageIdentifier = extractPackageIdentifier(args.path);
// remove version number to avoid loading same lib twice if it's react or three.js
if(packageIdentifier.includes('react') || packageIdentifier.includes('three')) {
packageName = packageIdentifier.replace(/@[\d.]+/, '');
pacageIdentifier = packageName;
} else {
packageName = packageIdentifier;
}
const cached = cache[packageName];
if (cached) {
console.log(`Using cached ${packageName} from ${cached} (${args.path})`);
return { path: cached, namespace: 'cdn' };
} else {
packageUrl = `${module_host}${module_url_prefix}${packageIdentifier}/+esm`;
cache[packageName] = packageUrl;
console.log(`Fetching ${packageName} from ${packageUrl} (${args.path})`);
return { path: packageUrl, namespace: 'cdn' };
}
});
build.onLoad({ filter: /^https:\/\/cdn.jsdelivr.net\// }, async (args) => {
const response = await fetch(args.path);
const contents = await response.text();
return { contents, loader: 'js' };
});
},
};
const appEntryCode = fileContents['/index.jsx'];
try {
const result = await esbuild.build({
stdin: {
contents: appEntryCode,
resolveDir: '',
loader: 'jsx',
},
// outfile: 'out.js',
bundle: true,
format: 'esm',
minify: false,
keepNames: true,
// treeShaking: false,
jsx: 'automatic',
target: 'es2020',
platform: 'browser',
plugins: [virtualModules, openartifactPlugin],
write: false,
loader: { '.js': 'jsx' },
})
const output = result.outputFiles[0].text;
const newAppHtml = htmlWrapper.split('[[APP_CODE]]').join(output);
const appHtmlBlob = new Blob([newAppHtml], { type: 'text/html' });
const appHtmlUrl = URL.createObjectURL(appHtmlBlob);
const iframeElem = document.querySelector('iframe');
iframeElem.src = appHtmlUrl;
iframeElem.onload = () => {
// URL.revokeObjectURL(url);
};
} catch (error) {
console.error('Build failed:', error);
} finally {
esbuild.stop();
loadingIndicator.style.display = 'none';
}
}
// openTab('tab-app');
// renderGeneratedApp({
// "/index.jsx": exampleApp
// });
function downloadZip(files) {
const zip = new JSZip();
Object.keys(files).forEach(function (filePath) {
zip.file("open-artifact-app" + filePath, files[filePath]);
});
zip.generateAsync({ type: "blob" }).then(function (content) {
saveAs(content, "open-artifact-app.zip");
});
}
function triggerFileUpload() {
document.getElementById('fileInput').click();
}
async function uploadZip(event) {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
fileContents = {};
const filesList = document.getElementById('files-list');
filesList.innerHTML = '';
if (file && file.name.endsWith('.zip')) {
const zip = await JSZip.loadAsync(file);