-
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathapp.js
More file actions
362 lines (323 loc) · 12.7 KB
/
app.js
File metadata and controls
362 lines (323 loc) · 12.7 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
// @ts-check
import { EditorSystem } from './editor.js';
import ts from 'typescript';
import { TypeProcessor } from './processor.js';
import { CodeShareManager } from './code-share.js';
import {
createSystem,
createDefaultMapFromCDN,
createVirtualCompilerHost
} from '@typescript/vfs';
/**
* @typedef {import('../../Bundle/bridge-js.js').PlayBridgeJS} PlayBridgeJS
*/
/**
* The main controller for the BridgeJS Playground.
*/
export class BridgeJSPlayground {
/**
* Creates a new instance of the BridgeJSPlayground.
*/
constructor() {
this.editorSystem = new EditorSystem();
/** @type {PlayBridgeJS | null} */
this.playBridgeJS = null;
/** @type {ReturnType<typeof setTimeout> | null} */
this.generateTimeout = null;
/** @type {boolean} */
this.isInitialized = false;
/** @type {HTMLDivElement} */
this.errorDisplay = /** @type {HTMLDivElement} */ (document.getElementById('errorDisplay'));
/** @type {HTMLDivElement} */
this.errorMessage = /** @type {HTMLDivElement} */ (document.getElementById('errorMessage'));
/** @type {HTMLButtonElement} */
this.shareButton = /** @type {HTMLButtonElement} */ (document.getElementById('shareButton'));
/** @type {HTMLDialogElement} */
this.shareDialog = /** @type {HTMLDialogElement} */ (document.getElementById('shareDialog'));
/** @type {HTMLInputElement} */
this.shareUrlInput = /** @type {HTMLInputElement} */ (document.getElementById('shareUrl'));
/** @type {HTMLButtonElement} */
this.copyButton = /** @type {HTMLButtonElement} */ (document.getElementById('copyButton'));
/** @type {HTMLButtonElement} */
this.closeShareDialogButton = /** @type {HTMLButtonElement} */ (document.getElementById('closeShareDialog'));
// Progress UI elements
/** @type {HTMLDivElement | null} */
this.progressBar = /** @type {HTMLDivElement} */ (document.getElementById('progressBar'));
/** @type {HTMLDivElement | null} */
this.progressFill = /** @type {HTMLDivElement} */ (document.getElementById('progressFill'));
/** @type {HTMLDivElement | null} */
this.progressLabel = /** @type {HTMLDivElement} */ (document.getElementById('progressLabel'));
}
/**
* Initializes the application.
* @param {{swift: string, dts: string}} sampleCode - The sample code to initialize the application with.
*/
async initialize(sampleCode) {
if (this.isInitialized) {
return;
}
try {
this.showProgress('Starting…', 5);
// Initialize editor system
await this.editorSystem.init();
this.setProgress('Editor ready', 30);
// Initialize BridgeJS
await this.initializeBridgeJS();
this.setProgress('BridgeJS ready', 70);
// Set up event listeners
this.setupEventListeners();
// Check for shared code in URL
this.setProgress('Checking shared code…', 80);
const sharedCode = await CodeShareManager.extractCodeFromUrl();
if (sharedCode) {
this.editorSystem.setInputs(sharedCode);
} else {
// Load sample code
this.editorSystem.setInputs(sampleCode);
}
this.setProgress('Finalizing…', 95);
this.isInitialized = true;
console.log('BridgeJS Playground initialized successfully');
this.setProgress('Ready', 100);
setTimeout(() => this.hideProgress(), 400);
} catch (error) {
console.error('Failed to initialize BridgeJS Playground:', error);
this.showError('Failed to initialize application: ' + error.message);
this.hideProgress();
}
}
// Initialize BridgeJS
async initializeBridgeJS() {
try {
// Import the BridgeJS module
this.setProgress('Loading BridgeJS…', 50);
const { init } = await import("../../Bundle/index.js");
const virtualHost = await this.createTS2SwiftFactory();
this.setProgress('Preparing TypeScript host…', 60);
const { exports } = await init({
getImports: () => ({
createTS2Swift: () => this.createTS2Swift(virtualHost)
})
});
this.setProgress('Creating runtime…', 65);
this.playBridgeJS = new exports.PlayBridgeJS();
console.log('BridgeJS initialized successfully');
} catch (error) {
console.error('Failed to initialize BridgeJS:', error);
throw new Error('BridgeJS initialization failed: ' + error.message);
}
}
// Set up event listeners
setupEventListeners() {
// Add change listeners for real-time generation
this.editorSystem.addChangeListeners(() => {
// Debounce generation to avoid excessive calls
if (this.generateTimeout) {
clearTimeout(this.generateTimeout);
}
this.generateTimeout = setTimeout(() => this.generateCode(), 300);
});
// Set up share functionality
this.setupShareListeners();
}
// Set up share-related event listeners
setupShareListeners() {
// Show share dialog
this.shareButton.addEventListener('click', async () => {
try {
const inputs = this.editorSystem.getInputs();
const shareUrl = await CodeShareManager.generateShareUrl(inputs);
this.shareUrlInput.value = shareUrl;
this.shareDialog.classList.remove('hidden');
this.shareUrlInput.select();
} catch (error) {
console.error('Failed to generate share URL:', error);
this.showError('Failed to generate share URL: ' + error.message);
}
});
// Copy share URL
this.copyButton.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(this.shareUrlInput.value);
const originalText = this.copyButton.textContent;
this.copyButton.textContent = 'Copied!';
this.copyButton.classList.add('copied');
setTimeout(() => {
this.copyButton.textContent = originalText;
this.copyButton.classList.remove('copied');
}, 2000);
} catch (error) {
console.error('Failed to copy URL:', error);
this.shareUrlInput.select();
}
});
// Close share dialog
this.closeShareDialogButton.addEventListener('click', () => {
this.shareDialog.classList.add('hidden');
});
// Close dialog when clicking outside
document.addEventListener('click', (event) => {
if (!this.shareDialog.classList.contains('hidden')) {
const dialogContent = this.shareDialog.querySelector('.share-dialog-content');
const target = event.target;
if (dialogContent && target instanceof Node && !dialogContent.contains(target) &&
this.shareButton && !this.shareButton.contains(target)) {
this.shareDialog.classList.add('hidden');
}
}
});
// Close dialog with Escape key
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !this.shareDialog.classList.contains('hidden')) {
this.shareDialog.classList.add('hidden');
}
});
}
async createTS2SwiftFactory() {
const createVirtualHost = async () => {
const fsMap = await createDefaultMapFromCDN(
{ target: ts.ScriptTarget.ES2015 },
ts.version,
true,
ts
);
const system = createSystem(fsMap);
const compilerOptions = {
target: ts.ScriptTarget.ES2015,
lib: ["es2015", "dom"],
};
return createVirtualCompilerHost(system, compilerOptions, ts);
}
return await createVirtualHost();
}
/**
* @param {ReturnType<typeof createVirtualCompilerHost>} virtualHost
*/
createTS2Swift(virtualHost) {
return {
/**
* @param {string} dtsCode
* @returns {string}
*/
convert: (dtsCode) => {
// Create TypeScript program from d.ts content
const virtualFilePath = "bridge-js.d.ts"
const sourceFile = ts.createSourceFile(virtualFilePath, dtsCode, ts.ScriptTarget.ES2015);
virtualHost.updateFile(sourceFile);
const tsProgram = ts.createProgram({
rootNames: [virtualFilePath],
host: virtualHost.compilerHost,
options: {
noEmit: true,
declaration: true,
}
})
// Create diagnostic engine for error reporting
const diagnosticEngine = {
print: (level, message, node) => {
console.log(`[${level}] ${message}`);
if (level === 'error') {
this.showError(`TypeScript Error: ${message}`);
}
}
};
// Process the TypeScript definitions to generate skeleton
const processor = new TypeProcessor(tsProgram.getTypeChecker(), diagnosticEngine);
const { content } = processor.processTypeDeclarations(tsProgram, virtualFilePath);
return content;
}
}
}
/**
* Generates code through BridgeJS.
*/
async generateCode() {
if (!this.playBridgeJS) {
this.showError('BridgeJS is not initialized');
return;
}
try {
this.hideError();
this.editorSystem.clearDiagnostics();
const inputs = this.editorSystem.getInputs();
const swiftCode = inputs.swift;
const dtsCode = inputs.dts;
// Process the code and get PlayBridgeJSOutput
const result = this.playBridgeJS.updateDetailed(swiftCode, dtsCode);
const diagnostics = result.diagnostics;
if (diagnostics && diagnostics.length > 0) {
const mapped = diagnostics.map(d => ({
file: d.file,
startLineNumber: d.startLine,
startColumn: d.startColumn,
endLineNumber: d.endLine,
endColumn: d.endColumn,
message: d.message
}));
this.editorSystem.showDiagnostics(mapped);
return;
}
const output = result.output;
if (output) {
// Update outputs using the PlayBridgeJSOutput object
this.editorSystem.updateOutputs(output);
this.hideError();
console.log('Code generated successfully');
} else {
this.showError('No output produced.');
}
} catch (error) {
console.error('Error generating code:', error);
this.showError('Error generating code: ' + error.message);
}
}
/**
* Shows an error message.
* @param {string} message - The message to show.
*/
showError(message) {
this.errorMessage.textContent = message;
this.errorDisplay.classList.add('show');
}
/**
* Hides the error message.
*/
hideError() {
this.errorDisplay.classList.remove('show');
}
/**
* Shows progress bar.
* @param {string} label
* @param {number} percent
*/
showProgress(label, percent) {
if (this.progressBar) {
this.progressBar.classList.add('show');
this.progressBar.classList.remove('hidden');
}
this.setProgress(label, percent);
}
/**
* Updates progress label and percentage.
* @param {string} label
* @param {number} percent
*/
setProgress(label, percent) {
if (this.progressLabel) {
this.progressLabel.textContent = label;
}
if (this.progressFill) {
const clamped = Math.max(0, Math.min(100, Number(percent) || 0));
this.progressFill.style.width = clamped + '%';
}
}
/**
* Hides progress bar.
*/
hideProgress() {
if (this.progressBar) {
this.progressBar.classList.remove('show');
this.progressBar.classList.add('hidden');
}
}
}