File size: 9,139 Bytes
5a81b95
 
 
 
 
 
 
e523b2e
 
038a1a3
 
 
 
 
 
 
 
 
 
5a81b95
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
e523b2e
5a81b95
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
e523b2e
5a81b95
 
 
 
 
e523b2e
5a81b95
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
 
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
e523b2e
5a81b95
 
 
 
 
 
 
 
 
 
 
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
/**
 * WidgeTDC Browser Extension - Content Script
 * Captures page content and enables AI assistance
 */

class WidgeTDCAssistant {
    constructor() {
        this.apiUrl = 'http://localhost:3001/api';
        this.sidebar = null;

        // Try to load from storage
        try {
            chrome.storage.sync.get({ widgetdc_api_url: 'http://localhost:3001' }, (items) => {
                this.apiUrl = `${items.widgetdc_api_url}/api`;
            });
        } catch (e) {
            // Fallback if storage access fails
        }

        this.init();
    }

    async init() {
        // Listen for messages from background script
        chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
            this.handleMessage(message, sendResponse);
            return true; // Keep channel open for async response
        });

        // Add context menu handler
        document.addEventListener('mouseup', this.handleTextSelection.bind(this));
    }

    /**
     * Handle messages from background script
     */
    async handleMessage(message, sendResponse) {
        switch (message.action) {
            case 'captureContent':
                const content = this.capturePageContent();
                await this.sendToBackend('/memory/ingest', content);
                sendResponse({ success: true, content });
                break;

            case 'searchSimilar':
                const results = await this.searchSimilar(message.query);
                sendResponse({ success: true, results });
                break;

            case 'toggleSidebar':
                this.toggleSidebar();
                sendResponse({ success: true });
                break;

            case 'askQuestion':
                const answer = await this.askQuestion(message.question);
                sendResponse({ success: true, answer });
                break;

            default:
                sendResponse({ success: false, error: 'Unknown action' });
        }
    }

    /**
     * Capture page content
     */
    capturePageContent() {
        // Extract main content (remove scripts, styles, etc.)
        const clone = document.cloneNode(true);
        const scripts = clone.querySelectorAll('script, style, noscript');
        scripts.forEach(el => el.remove());

        // Get text content
        const text = clone.body.innerText.trim();

        // Extract metadata
        const metadata = {
            author: this.getMetaContent('author'),
            publishedDate: this.getMetaContent('article:published_time'),
            description: this.getMetaContent('description'),
        };

        return {
            url: window.location.href,
            title: document.title,
            text: text.substring(0, 10000), // Limit to 10k chars
            metadata,
        };
    }

    /**
     * Get meta tag content
     */
    getMetaContent(name) {
        const meta = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`);
        return meta ? meta.getAttribute('content') : undefined;
    }

    /**
     * Handle text selection
     */
    handleTextSelection(event) {
        const selection = window.getSelection();
        const selectedText = selection ? selection.toString().trim() : '';

        if (selectedText && selectedText.length > 10) {
            // Show floating action button
            this.showFloatingButton(event.clientX, event.clientY, selectedText);
        }
    }

    /**
     * Show floating action button
     */
    showFloatingButton(x, y, text) {
        // Remove existing button
        const existing = document.getElementById('widgetdc-floating-btn');
        if (existing) existing.remove();

        // Create button
        const button = document.createElement('div');
        button.id = 'widgetdc-floating-btn';
        button.className = 'widgetdc-floating-button';
        button.innerHTML = `
      <button class="widgetdc-btn" data-action="save">💾 Save</button>
      <button class="widgetdc-btn" data-action="search">🔍 Search Similar</button>
      <button class="widgetdc-btn" data-action="ask">❓ Ask AI</button>
    `;
        button.style.position = 'fixed';
        button.style.left = `${x}px`;
        button.style.top = `${y + 10}px`;
        button.style.zIndex = '10000';

        // Add event listeners
        button.querySelectorAll('.widgetdc-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                const action = e.target.getAttribute('data-action');
                await this.handleAction(action, text);
                button.remove();
            });
        });

        document.body.appendChild(button);

        // Remove on click outside
        setTimeout(() => {
            document.addEventListener('click', () => button.remove(), { once: true });
        }, 100);
    }

    /**
     * Handle floating button action
     */
    async handleAction(action, text) {
        switch (action) {
            case 'save':
                await this.saveText(text);
                this.showNotification('Text saved to WidgeTDC');
                break;

            case 'search':
                const results = await this.searchSimilar(text);
                this.showSidebarWithResults(results);
                break;

            case 'ask':
                const answer = await this.askQuestion(text);
                this.showSidebarWithAnswer(answer);
                break;
        }
    }

    /**
     * Save text to backend
     */
    async saveText(text) {
        await this.sendToBackend('/memory/ingest', {
            content: text,
            source: 'browser_selection',
            url: window.location.href,
            timestamp: new Date().toISOString(),
        });
    }

    /**
     * Search for similar content
     */
    async searchSimilar(query) {
        const response = await this.sendToBackend('/search', { query, limit: 5 });
        return response.results || [];
    }

    /**
     * Ask AI a question
     */
    async askQuestion(question) {
        const response = await this.sendToBackend('/query', { question });
        return response.answer || 'No answer available';
    }

    /**
     * Send data to backend
     */
    async sendToBackend(endpoint, data) {
        try {
            const response = await fetch(`${this.apiUrl}${endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('WidgeTDC API error:', error);
            return { error: String(error) };
        }
    }

    /**
     * Toggle sidebar
     */
    toggleSidebar() {
        if (this.sidebar) {
            this.sidebar.remove();
            this.sidebar = null;
        } else {
            this.createSidebar();
        }
    }

    /**
     * Create sidebar
     */
    createSidebar() {
        const sidebar = document.createElement('div');
        sidebar.id = 'widgetdc-sidebar';
        sidebar.className = 'widgetdc-sidebar';
        sidebar.innerHTML = `
      <div class="widgetdc-sidebar-header">
        <h3>WidgeTDC Assistant</h3>
        <button class="widgetdc-close">×</button>
      </div>
      <div class="widgetdc-sidebar-content">
        <p>Loading...</p>
      </div>
    `;

        sidebar.querySelector('.widgetdc-close')?.addEventListener('click', () => {
            this.toggleSidebar();
        });

        document.body.appendChild(sidebar);
        this.sidebar = sidebar;
    }

    /**
     * Show sidebar with search results
     */
    showSidebarWithResults(results) {
        this.createSidebar();
        const content = this.sidebar?.querySelector('.widgetdc-sidebar-content');
        if (content) {
            content.innerHTML = `
        <h4>Similar Content</h4>
        ${results.map(r => `
          <div class="widgetdc-result">
            <h5>${r.title || 'Untitled'}</h5>
            <p>${r.content?.substring(0, 200)}...</p>
            <small>${r.source || 'Unknown source'}</small>
          </div>
        `).join('')}
      `;
        }
    }

    /**
     * Show sidebar with AI answer
     */
    showSidebarWithAnswer(answer) {
        this.createSidebar();
        const content = this.sidebar?.querySelector('.widgetdc-sidebar-content');
        if (content) {
            content.innerHTML = `
        <h4>AI Answer</h4>
        <div class="widgetdc-answer">${answer}</div>
      `;
        }
    }

    /**
     * Show notification
     */
    showNotification(message) {
        const notification = document.createElement('div');
        notification.className = 'widgetdc-notification';
        notification.textContent = message;
        document.body.appendChild(notification);

        setTimeout(() => notification.remove(), 3000);
    }
}

// Initialize assistant
new WidgeTDCAssistant();