File size: 9,941 Bytes
b931367
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e4938d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b931367
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e4938d
 
b931367
 
 
 
 
 
6e4938d
 
b931367
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<script>
(function () {

    console.info("Space App JS executing...");

    // --- Logger utility (structured, levelled, timestamped) ---
    const SpaceApp = {

        hasBooted: false,
        fnUnloadLastTab: null,

        toastInfo: function(...args) {
            // use toastify
            window.Toastify({
                text: args.join(' '),
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "green",
            }).showToast();
            console.info("TOAST_INFO", ...args);
        },

        toastError: function(...args) {
            window.Toastify({
                text: args.join(' '),
                duration: 5000,
                gravity: "top",
                position: "right",
                backgroundColor: "red",
            }).showToast();
            console.error("TOAST_ERROR", ...args);
        },

        unloadLastTab: function() {
            if (this.fnUnloadLastTab) {
                this.fnUnloadLastTab();
                this.fnUnloadLastTab = null;
            }
        },

        TextGeneratorTab: (function () {
            return {
                init: function () {
                    console.info("TextGeneratorTab initialized.");
                },
                toggle: function () {
                    // Placeholder for future functionality
                    SpaceApp.toastInfo("TextGeneratorTab toggled.");
                    SpaceApp.unloadLastTab();
                }
            };
        })(),

        WebGeneratorTab: (function () {
            return {
                init: function () {
                    console.info("WebGeneratorTab initialized.");
                },
                toggle: function () {
                    // Placeholder for future functionality
                    SpaceApp.toastInfo("WebGeneratorTab toggled.");
                    SpaceApp.unloadLastTab();
                },
                toggleFullscreen: function (event) {
                    const isFullscreen = event.detail?.isFullscreen;
                    console.info(`Handling Fullscreen Toggle. Target State: ${isFullscreen}`);

                    const left = document.getElementById('left-panel');
                    const right = document.getElementById('right-panel');
                    
                    // If isFullscreen is true, we want to HIDE panels (enter fullscreen)
                    // If isFullscreen is false, we want to SHOW panels (exit fullscreen)
                    const shouldHide = isFullscreen;
                    const displayStyle = shouldHide ? 'none' : 'flex'; 

                    if (left) {
                         left.style.display = displayStyle;
                         // Also toggle class for good measure/CSS priority
                         left.classList.toggle('hidden-panel', shouldHide);
                    }
                    if (right) {
                         right.style.display = displayStyle;
                         right.classList.toggle('hidden-panel', shouldHide);
                    }

                    // Trigger resize to help charts/iframes adjust
                    setTimeout(() => window.dispatchEvent(new Event('resize')), 100);
                }
            };
        })(),

        WritingAssistantTab: (function () {
            return {
                init: function () {
                    console.info("WritingAssistantTab initialized.");
                },
            };
        })(),

        registerEventListeners: function() {
            const listeners = {
                'tabSelect.chat': () => SpaceApp.TextGeneratorTab.toggle(),
                'tabSelect.code': () => SpaceApp.WebGeneratorTab.toggle(),
                'tabSelect.writing': () => SpaceApp.WritingAssistantTab.toggle(),
                // New listener for fullscreen toggle
                'tab.code.toggleFullscreen': (e) => SpaceApp.WebGeneratorTab.toggleFullscreen(e),
            };
            for (const [event, handler] of Object.entries(listeners)) {
                window.addEventListener(event, handler);
                console.info(`Registered event listener for ${event}`);
            }



            // type_filter, handler
            // Listen for messages {type: string, payload: object}
            const messages = {
                'iframeError': (data) => {
                    // 1. Show visual toast
                    SpaceApp.toastError("Iframe Error Detected:", JSON.stringify(data));
                    
                    // 2. Propagate to Backend via Gradio
                    const jsErrorChannel = document.querySelector('.js_error_channel textarea');
                    if (jsErrorChannel) {
                        // Format as string for backend
                        const errorMessage = data.message || JSON.stringify(data);
                        const timestamp = new Date().toLocaleTimeString();
                        jsErrorChannel.value = `[${timestamp}] ${errorMessage}\nStack: ${data.stack || 'N/A'}`;
                        jsErrorChannel.dispatchEvent(new Event('input', { bubbles: true }));
                    } else {
                        console.warn("Gradio channel '.js_error_channel' not found. Backend logging skipped.");
                    }
                },
            }
            window.addEventListener('message', (event) => {
                const {type, payload} = event.data || {};
                if (type && messages[type]) {
                    messages[type](payload);
                }
            });

        },

    };

    // Expose bootstrap globally so external scripts can call it after page load
    window.bootApp = function () {
        if (SpaceApp.hasBooted) {
            console.warn("Space App has already booted. Ignoring duplicate boot call.");
            return;
        }
        SpaceApp.hasBooted = true;
        SpaceApp.toastInfo("Booting Space App...");
        SpaceApp.registerEventListeners();
        SpaceApp.TextGeneratorTab.init();
        SpaceApp.WebGeneratorTab.init();
        SpaceApp.WritingAssistantTab.init();
        SpaceApp.toastInfo("Space App booted successfully.");
    };

    window.SpaceApp = SpaceApp;

    console.info("Space App JS execution completed.");

})();
</script>
<script>
    // 注册一个 appStart 事件监听器,在 Gradio app 启动时调用 bootApp
    window.addEventListener('appStart', function () {
        console.info("Gradio appStart event detected. Booting Space App...");
        if (typeof window.bootApp === "function") {
            window.bootApp();
        } else {
            console.error("bootApp function is not defined.");
        }
    });
</script>
<script>
    (function() {

        const ErrorPoller = {
            lastErrorMessage: '',
            startPolling: () => {

            },
            stopPolling: () => {

            }
        }

        console.info('Iframe Error Poller Initialized');
        let lastErrorMessage = '';

        // Function to start polling for errors in the iframe
        function startPolling() {

            console.info('Starting to poll iframe for errors...');

            setInterval(() => {
                // Re-select the iframe on every interval tick because Gradio replaces it.
                const previewIframe = document.querySelector('iframe[srcdoc]');
                if (!previewIframe) return;

                try {
                    const iframeDoc = previewIframe.contentWindow.document;
                    const errorContainer = iframeDoc.querySelector('#global-error');

                    const jsErrorChannel = document.querySelector('.js_error_channel textarea');
                    if (!jsErrorChannel) {
                        console.error("Gradio channel '.js_error_channel' not found.");
                        return;
                    }

                    if (errorContainer && errorContainer.style.display !== 'none') {
                        const currentErrorMessage = errorContainer.innerText;

                        // If the error message is new, send it to the backend
                        if (currentErrorMessage && currentErrorMessage !== lastErrorMessage) {
                            lastErrorMessage = currentErrorMessage;

                            // Set the value on the hidden Gradio textbox
                            jsErrorChannel.value = currentErrorMessage;

                            // Dispatch an 'input' event to notify Gradio of the change
                            jsErrorChannel.dispatchEvent(new Event('input', { bubbles: true }));
                        }
                    } else {
                        // If the error container is not visible or doesn't exist, and there was a previous error, clear it.
                        if (lastErrorMessage) {
                            lastErrorMessage = '';
                            jsErrorChannel.value = '';
                            jsErrorChannel.dispatchEvent(new Event('input', { bubbles: true }));
                        }
                    }
                } catch (e) {
                    // This can happen due to cross-origin restrictions if the iframe src changes.
                    // We can ignore it for srcdoc iframes.
                }
            }, 1000);

        }

        // 在页面加载之后设置
        document.addEventListener('readystatechange', (event) => {
            if (document.readyState === 'complete') {
                setTimeout(startPolling, 500);
            }
        });

        console.info('Iframe Error Poller Script Loaded');
    })();
</script>
<script>
// 我们当前存活在一个 iframe 里面。观察 document, window, window.parent。

console.log('document is', document);
console.log('window is ', window);
console.log('window parent is ', window.parent);

</script>