-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.js
More file actions
342 lines (292 loc) · 10.8 KB
/
Copy pathloader.js
File metadata and controls
342 lines (292 loc) · 10.8 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
/**
* Contextual Icon Loader
* A lightweight, client-side icon visualizer that uses LLM to generate
* contextual abstract icons based on page content.
*
* Author: AI Preloaders
* License: MIT
*/
import { LLMAnalyzer } from './src/llm-analyzer.js';
import { IconMapper } from './src/icon-mapper.js';
import { IconAnimator } from './src/icon-animator.js';
import { ContentExtractor } from './src/content-extractor.js';
class ContextualIconLoader {
constructor(options = {}) {
// Configuration
this.config = {
container: options.container || document.body,
canvasId: options.canvasId || 'iconCanvas',
position: options.position || 'bottom-right',
animationMode: options.animationMode || 'loop',
updateInterval: options.updateInterval || 5000,
useFallback: options.useFallback !== false,
fallbackIcons: options.fallbackIcons || ['stars', 'circle', 'auto_awesome'],
...options
};
// State
this.isInitialized = false;
this.currentIcons = [];
this.animationId = null;
this.positionIndex = 0;
this.isPaused = false;
// Components
this.llmAnalyzer = new LLMAnalyzer((status, progress) => this.onLLMProgress(status, progress));
this.iconMapper = new IconMapper();
this.animator = null;
this.contentExtractor = new ContentExtractor();
// Bind methods
this.init = this.init.bind(this);
this.updateIcons = this.updateIcons.bind(this);
this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
}
async init() {
try {
console.log('[IconLoader] Initializing...');
// Initialize canvas and animator
const canvas = document.getElementById(this.config.canvasId);
if (!canvas) {
throw new Error(`Canvas with id "${this.config.canvasId}" not found`);
}
this.animator = new IconAnimator(canvas);
this.animator.start();
// Try to initialize LLM
const llmReady = await this.llmAnalyzer.init();
if (llmReady) {
this.updateStatus('ready', 'LLM Ready - Analyzing content...');
console.log('[IconLoader] LLM initialized successfully');
// Initial content analysis
await this.updateIcons();
// Set up periodic updates
this.setupAutoUpdate();
// Set up content observer for dynamic changes
this.setupContentObserver();
} else {
// Use fallback mode
this.updateStatus('fallback', 'Using fallback mode');
console.log('[IconLoader] Using fallback mode');
this.startFallbackMode();
}
// Handle visibility changes
document.addEventListener('visibilitychange', this.handleVisibilityChange);
this.isInitialized = true;
console.log('[IconLoader] Initialization complete');
return true;
} catch (error) {
console.error('[IconLoader] Initialization failed:', error);
this.updateStatus('fallback', 'Error - Using fallback');
this.startFallbackMode();
return false;
}
}
/**
* Extract visible content and update icons
*/
async updateIcons() {
if (!this.isInitialized || this.isPaused) return;
try {
// Extract visible text content
const content = this.contentExtractor.getVisibleContent();
if (!content || content.trim().length < 50) {
console.log('[IconLoader] Not enough content to analyze');
return;
}
console.log('[IconLoader] Analyzing content:', content.substring(0, 100) + '...');
// Get contextual nouns from LLM
let nouns = [];
if (this.llmAnalyzer.isReady()) {
nouns = await this.llmAnalyzer.extractContextualNouns(content);
}
// If LLM fails or returns empty, use keyword extraction
if (!nouns || nouns.length === 0) {
nouns = this.contentExtractor.extractKeywords(content);
}
console.log('[IconLoader] Extracted concepts:', nouns);
// Convert nouns to icon format (if they're already icon names, use them directly)
this.currentIcons = nouns.map(noun => {
// Check if it's already an icon name from our enhanced extractor
if (this.contentExtractor.keywordIconMap?.[noun]) {
return { name: this.contentExtractor.keywordIconMap[noun], category: 'keyword' };
}
// Otherwise use the icon mapper
const mapped = this.iconMapper.mapToIcon(noun);
return mapped || { name: 'auto_awesome', category: 'fallback' };
}).filter(icon => icon !== null);
// Ensure we have at least some icons
if (this.currentIcons.length === 0) {
this.currentIcons = this.config.fallbackIcons.map(name => ({ name, category: 'fallback' }));
}
// Update animator with new icons
this.animator.updateIcons(this.currentIcons);
// Update icon label
this.updateIconLabel(this.currentIcons);
} catch (error) {
console.error('[IconLoader] Error updating icons:', error);
}
}
/**
* Update the icon label to show current icon name
*/
updateIconLabel(icons) {
const label = document.getElementById('iconLabel');
if (label && icons.length > 0) {
const mainIcon = icons[0].name.replace(/_/g, ' ');
label.textContent = mainIcon.charAt(0).toUpperCase() + mainIcon.slice(1);
}
}
/**
* Set up automatic content updates
*/
setupAutoUpdate() {
// Update periodically
setInterval(() => {
if (!document.hidden) {
this.updateIcons();
}
}, this.config.updateInterval);
// Update on scroll (debounced)
let scrollTimeout;
window.addEventListener('scroll', () => {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
if (!document.hidden) {
this.updateIcons();
}
}, 500);
});
}
/**
* Set up MutationObserver for dynamic content changes
*/
setupContentObserver() {
const observer = new MutationObserver((mutations) => {
// Only react to significant content changes
const hasContentChange = mutations.some(mutation =>
mutation.type === 'childList' &&
mutation.addedNodes.length > 0
);
if (hasContentChange && !document.hidden) {
// Debounce the update
clearTimeout(this._observerTimeout);
this._observerTimeout = setTimeout(() => this.updateIcons(), 1000);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
/**
* Start fallback mode with random icons
*/
startFallbackMode() {
this.currentIcons = this.config.fallbackIcons.map(name => ({ name, category: 'fallback' }));
if (this.animator) {
this.animator.updateIcons(this.currentIcons);
}
this.updateIconLabel(this.currentIcons);
// Cycle through fallback icons
setInterval(() => {
if (!this.isPaused && !document.hidden) {
const randomIcon = this.config.fallbackIcons[
Math.floor(Math.random() * this.config.fallbackIcons.length)
];
this.currentIcons = [{ name: randomIcon, category: 'fallback' }];
if (this.animator) {
this.animator.updateIcons(this.currentIcons);
}
this.updateIconLabel(this.currentIcons);
}
}, 3000);
}
/**
* Update status badge
*/
updateStatus(state, text) {
const badge = document.getElementById('statusBadge');
const statusText = document.getElementById('statusText');
if (badge && statusText) {
badge.className = `status-badge ${state}`;
statusText.textContent = text;
}
}
/**
* Handle LLM loading progress
*/
onLLMProgress(status, progress) {
if (status === 'downloading') {
this.updateStatus('loading', `Downloading AI model: ${progress}%`);
} else if (status === 'loading') {
this.updateStatus('loading', `Loading AI model: ${progress}%`);
}
}
/**
* Handle visibility changes
*/
handleVisibilityChange() {
if (document.hidden) {
this.isPaused = true;
if (this.animator) this.animator.pause();
} else {
this.isPaused = false;
if (this.animator) this.animator.resume();
this.updateIcons();
}
}
/**
* Public: Trigger manual analysis
*/
async triggerAnalysis() {
console.log('[IconLoader] Manual analysis triggered');
await this.updateIcons();
}
/**
* Public: Toggle container position
*/
togglePosition() {
const positions = ['right', 'left', 'center'];
this.positionIndex = (this.positionIndex + 1) % positions.length;
const position = positions[this.positionIndex];
const container = document.getElementById('loaderContainer');
if (container) {
container.className = 'icon-loader-container';
if (position === 'left') {
container.classList.add('position-left');
} else if (position === 'center') {
container.classList.add('position-center');
}
}
}
/**
* Public: Toggle animation mode
*/
toggleMode() {
if (this.animator) {
this.animator.toggleMode();
}
}
/**
* Clean up
*/
destroy() {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
}
document.removeEventListener('visibilitychange', this.handleVisibilityChange);
if (this.animator) {
this.animator.destroy();
}
}
}
// Export for global access
window.ContextualIconLoader = ContextualIconLoader;
// Auto-initialize with default settings
const loaders = new ContextualIconLoader();
// Wait for DOM to be ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => loaders.init());
} else {
loaders.init();
}
// Export for demo controls
window.loaders = loaders;
export default ContextualIconLoader;