File size: 12,153 Bytes
49ee472
 
 
 
 
 
 
 
 
 
 
 
51e770a
 
49ee472
 
 
 
 
 
52301d8
 
 
49ee472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52301d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49ee472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51e770a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49ee472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52301d8
49ee472
 
 
 
52301d8
49ee472
 
 
 
52301d8
49ee472
 
 
 
52301d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49ee472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Riaslink Port Builder — frontend logic.
// No framework, no build step: this is the entire client-side behavior for
// the build form, talking to the plain FastAPI routes in app.py.

(() => {
    'use strict';

    const form = document.getElementById('build-form');
    const buildBtn = document.getElementById('build-btn');
    const buildBtnLabel = buildBtn.querySelector('.build-btn-label');
    const statusPill = document.getElementById('status-pill');
    const logOutput = document.getElementById('log-output');
    const copyLogBtn = document.getElementById('copy-log-btn');
    const copyLogIcon = document.getElementById('copy-log-icon');
    const downloadArea = document.getElementById('download-area');
    const downloadLink = document.getElementById('download-link');

    const fileInput = document.getElementById('www_zip');
    const fileDrop = document.getElementById('file-drop');
    const fileDropLabel = document.getElementById('file-drop-label');
    const uploadRing = document.getElementById('upload-ring');
    const uploadRingProgress = document.getElementById('upload-ring-progress');
    const uploadRingLabel = document.getElementById('upload-ring-label');

    const accentColor = document.getElementById('accent_hex');
    const accentColorText = document.getElementById('accent_hex_text');

    // -------------------------------------------------------------------
    // File drop UX (native <input type="file"> still handles the actual
    // selection — this just adds drag-over styling and a filename label).
    // -------------------------------------------------------------------

    fileInput.addEventListener('change', () => {
        updateFileDropLabel();
    });

    ['dragenter', 'dragover'].forEach((evt) => {
        fileDrop.addEventListener(evt, (e) => {
            e.preventDefault();
            fileDrop.classList.add('drag-over');
        });
    });

    ['dragleave', 'drop'].forEach((evt) => {
        fileDrop.addEventListener(evt, (e) => {
            e.preventDefault();
            fileDrop.classList.remove('drag-over');
        });
    });

    fileDrop.addEventListener('drop', (e) => {
        const dropped = e.dataTransfer?.files;
        if (dropped && dropped.length > 0) {
            fileInput.files = dropped;
            updateFileDropLabel();
        }
    });

    function updateFileDropLabel() {
        const file = fileInput.files[0];
        if (file) {
            fileDropLabel.textContent = file.name;
            fileDropLabel.classList.add('has-file');
        } else {
            fileDropLabel.textContent = 'Dosya seç ya da buraya sürükle';
            fileDropLabel.classList.remove('has-file');
        }
    }

    // Matches the fixed stroke-dasharray in style.css (2 * pi * r, r=15.5).
    const CIRCLE_CIRCUMFERENCE = 97.389;

    function showUploadRing() {
        fileDrop.classList.add('uploading');
        uploadRing.classList.remove('hidden');
        setUploadProgress(0);
    }

    function hideUploadRing() {
        fileDrop.classList.remove('uploading');
        uploadRing.classList.add('hidden');
    }

    function setUploadProgress(fraction) {
        const clamped = Math.max(0, Math.min(1, fraction));
        const offset = CIRCLE_CIRCUMFERENCE * (1 - clamped);
        uploadRingProgress.style.strokeDashoffset = String(offset);
        uploadRingLabel.textContent = `${Math.round(clamped * 100)}%`;
    }

    // -------------------------------------------------------------------
    // Color picker <-> hex text field, kept in sync both directions.
    // -------------------------------------------------------------------

    accentColor.addEventListener('input', () => {
        accentColorText.value = accentColor.value;
    });

    accentColorText.addEventListener('input', () => {
        const value = accentColorText.value.trim();
        if (/^#[0-9a-fA-F]{6}$/.test(value)) {
            accentColor.value = value;
        }
    });

    // -------------------------------------------------------------------
    // Log rendering helpers
    // -------------------------------------------------------------------

    let logHasContent = false;

    function clearLog() {
        logOutput.innerHTML = '';
        logHasContent = false;
    }

    function appendLogLine(text, kind) {
        if (!logHasContent) {
            logOutput.innerHTML = '';
            logHasContent = true;
        }
        const line = document.createElement('div');
        if (kind) {
            line.className = `log-line-${kind}`;
        }
        line.textContent = text;
        logOutput.appendChild(line);
        logOutput.scrollTop = logOutput.scrollHeight;
    }

    function setStatus(state, label) {
        statusPill.dataset.state = state;
        statusPill.textContent = label;
    }

    function getLogText() {
        // Each log line is its own <div> (see appendLogLine) — reading
        // logOutput.textContent directly would run every line together
        // with no separator, so each line's own text is collected and
        // joined with real newlines instead.
        return Array.from(logOutput.children)
            .map((line) => line.textContent)
            .join('\n');
    }

    copyLogBtn.addEventListener('click', async () => {
        const text = getLogText();
        if (!text) return;

        try {
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(text);
            } else {
                // navigator.clipboard is only available in secure contexts
                // (HTTPS) — this covers plain-HTTP deployments with the
                // older document.execCommand approach instead.
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
            }
            showCopyFeedback(true);
        } catch (err) {
            showCopyFeedback(false);
        }
    });

    let copyFeedbackTimeout = null;

    function showCopyFeedback(success) {
        clearTimeout(copyFeedbackTimeout);
        copyLogBtn.classList.toggle('copied', success);
        copyLogIcon.textContent = success ? '✅' : '⚠️';
        copyLogBtn.title = success ? 'Kopyalandı' : 'Kopyalanamadı';

        copyFeedbackTimeout = setTimeout(() => {
            copyLogBtn.classList.remove('copied');
            copyLogIcon.textContent = '📋';
            copyLogBtn.title = 'Günlüğü kopyala';
        }, 1600);
    }

    // -------------------------------------------------------------------
    // Form submission
    // -------------------------------------------------------------------

    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        if (!fileInput.files[0]) {
            appendLogLine('Önce bir www.zip dosyası seç.', 'error');
            return;
        }

        buildBtn.disabled = true;
        buildBtnLabel.textContent = 'Başlatılıyor...';
        downloadArea.classList.add('hidden');
        clearLog();
        setStatus('running', 'Çalışıyor');

        const formData = new FormData(form);
        // FormData already grabs www_zip from the <input type="file">, and
        // the checkbox only appears in FormData when checked — FastAPI's
        // Form(bool) parses "on"/"true"/"1" etc., but an absent field would
        // be missing entirely rather than "false", so it's added explicitly
        // here to always send a real value either way.
        formData.set('fps_default_visible', document.getElementById('fps_default_visible').checked ? 'true' : 'false');

        let buildId;
        try {
            const data = await uploadWithProgress('/api/build', formData);
            buildId = data.build_id;
        } catch (err) {
            appendLogLine(`Build başlatılamadı: ${err.message}`, 'error');
            setStatus('failed', 'Hata');
            hideUploadRing();
            resetButton();
            return;
        }

        hideUploadRing();
        buildBtnLabel.textContent = 'Build çalışıyor...';
        streamBuildLog(buildId);
    });

    // fetch() has no upload-progress event — only XMLHttpRequest exposes
    // xhr.upload.onprogress, which is what drives the circular ring below.
    // Wrapped in a Promise so the call site can stay a plain `await`.
    function uploadWithProgress(url, formData) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', url);

            xhr.upload.onprogress = (event) => {
                if (event.lengthComputable) {
                    if (uploadRing.classList.contains('hidden')) {
                        showUploadRing();
                    }
                    setUploadProgress(event.loaded / event.total);
                }
            };

            xhr.onload = () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        resolve(JSON.parse(xhr.responseText));
                    } catch (err) {
                        reject(new Error('Sunucu yanıtı okunamadı.'));
                    }
                } else {
                    reject(new Error(`Sunucu hatası (${xhr.status}): ${xhr.responseText}`));
                }
            };

            xhr.onerror = () => reject(new Error('Ağ hatası — yükleme başarısız oldu.'));

            xhr.send(formData);
        });
    }

    function resetButton() {
        buildBtn.disabled = false;
        buildBtnLabel.textContent = 'APK Oluştur';
    }

    // -------------------------------------------------------------------
    // Server-Sent Events: live log streaming from /api/build/{id}/stream
    // -------------------------------------------------------------------

    function streamBuildLog(buildId) {
        const source = new EventSource(`/api/build/${buildId}/stream`);

        source.onmessage = (event) => {
            let payload;
            try {
                payload = JSON.parse(event.data);
            } catch {
                return;
            }

            if (payload.type === 'log') {
                appendLogLine(payload.line);
            } else if (payload.type === 'error') {
                appendLogLine(payload.message, 'error');
                setStatus('failed', 'Hata');
                resetButton();
                source.close();
            } else if (payload.type === 'done') {
                source.close();
                resetButton();

                if (payload.status === 'success') {
                    setStatus('success', 'Tamamlandı');
                    appendLogLine('✅ Build tamamlandı.', 'success');
                    if (payload.download_url) {
                        downloadLink.href = payload.download_url;
                        downloadArea.classList.remove('hidden');
                    }
                } else {
                    setStatus('failed', 'Başarısız');
                    if (payload.error_message) {
                        appendLogLine(`❌ ${payload.error_message}`, 'error');
                    }
                }
            }
        };

        source.onerror = () => {
            // EventSource auto-retries on transient network errors, so this
            // only means something is actually wrong (server gone, build id
            // invalid) if the connection doesn't recover — close it and let
            // the person retry manually rather than retrying forever.
            source.close();
            if (statusPill.dataset.state === 'running') {
                appendLogLine('Bağlantı kesildi. Sayfayı yenileyip tekrar dene.', 'error');
                setStatus('failed', 'Bağlantı Hatası');
            }
            resetButton();
        };
    }
})();