100+ copy-paste UI components in plain HTML and CSS: no dependencies, no build step.

0 downloads

dbbasic-web-native/context-detection.js
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web-native.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web-native.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web-native.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add canonical.html v1.0 - The single source of truth for usability standards fb6e650 1 year ago History
context-detection.js · 16.0 KB · 440 lines
1/**
2 * Context Detection System
3 * Automatically detects environmental context using device sensors and APIs
4 * - Ambient noise level
5 * - Number of viewers (via camera/proximity)
6 * - Lighting conditions
7 * - Device orientation
8 * - User activity/idle state
9 * - Network conditions
10 */
11
12class ContextDetectionSystem {
13 constructor(contextManager) {
14 this.context = contextManager;
15 this.sensors = {};
16 this.detectionInterval = null;
17 this.isRunning = false;
18
19 this.init();
20 }
21
22 async init() {
23 await this.setupAudioDetection();
24 await this.setupVideoDetection();
25 await this.setupLightDetection();
26 await this.setupMotionDetection();
27 await this.setupIdleDetection();
28 await this.setupNetworkDetection();
29
30 console.log('Context detection initialized');
31 }
32
33 // ========================================================================
34 // AUDIO DETECTION - Ambient noise level
35 // ========================================================================
36
37 async setupAudioDetection() {
38 try {
39 const stream = await navigator.mediaDevices.getUserMedia({
40 audio: {
41 echoCancellation: true,
42 noiseSuppression: false,
43 autoGainControl: false
44 }
45 });
46
47 const audioContext = new (window.AudioContext || window.webkitAudioContext)();
48 const analyser = audioContext.createAnalyser();
49 const microphone = audioContext.createMediaStreamSource(stream);
50 const dataArray = new Uint8Array(analyser.frequencyBinCount);
51
52 analyser.smoothingTimeConstant = 0.8;
53 analyser.fftSize = 1024;
54
55 microphone.connect(analyser);
56
57 this.sensors.audio = {
58 analyser,
59 dataArray,
60 stream,
61 detectNoise: () => {
62 analyser.getByteFrequencyData(dataArray);
63
64 // Calculate average volume
65 let sum = 0;
66 for (let i = 0; i < dataArray.length; i++) {
67 sum += dataArray[i];
68 }
69 const average = sum / dataArray.length;
70
71 // Convert to 0-100 scale
72 const noiseLevel = Math.min(100, (average / 255) * 100);
73
74 return Math.round(noiseLevel);
75 }
76 };
77
78 console.log('Audio detection enabled');
79 } catch (error) {
80 console.warn('Audio detection not available:', error.message);
81 this.sensors.audio = { detectNoise: () => 0 };
82 }
83 }
84
85 // ========================================================================
86 // VIDEO DETECTION - Number of faces/viewers
87 // ========================================================================
88
89 async setupVideoDetection() {
90 try {
91 const stream = await navigator.mediaDevices.getUserMedia({
92 video: {
93 width: { ideal: 640 },
94 height: { ideal: 480 },
95 facingMode: 'user'
96 }
97 });
98
99 // Create hidden video element for face detection
100 const video = document.createElement('video');
101 video.srcObject = stream;
102 video.autoplay = true;
103 video.style.display = 'none';
104 document.body.appendChild(video);
105
106 // Simple face detection using canvas analysis
107 // In production, use Face-API.js or TensorFlow.js
108 const canvas = document.createElement('canvas');
109 const ctx = canvas.getContext('2d');
110
111 this.sensors.video = {
112 video,
113 stream,
114 canvas,
115 ctx,
116 detectViewers: () => {
117 // This is a simplified version
118 // In production, use proper face detection library
119 canvas.width = video.videoWidth;
120 canvas.height = video.videoHeight;
121
122 if (canvas.width === 0) return 1; // Default to 1 viewer
123
124 ctx.drawImage(video, 0, 0);
125
126 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
127 const data = imageData.data;
128
129 // Simple motion/presence detection
130 let movement = 0;
131 for (let i = 0; i < data.length; i += 4) {
132 const brightness = (data[i] + data[i + 1] + data[i + 2]) / 3;
133 if (brightness > 50) movement++;
134 }
135
136 const presenceRatio = movement / (data.length / 4);
137
138 // Rough estimate: more presence = more viewers
139 if (presenceRatio > 0.3) return Math.min(5, Math.ceil(presenceRatio * 3));
140 return 1;
141 }
142 };
143
144 console.log('Video detection enabled');
145 } catch (error) {
146 console.warn('Video detection not available:', error.message);
147 this.sensors.video = { detectViewers: () => 1 };
148 }
149 }
150
151 // ========================================================================
152 // LIGHT DETECTION - Ambient lighting
153 // ========================================================================
154
155 async setupLightDetection() {
156 try {
157 // Try AmbientLightSensor API (limited browser support)
158 if ('AmbientLightSensor' in window) {
159 const sensor = new AmbientLightSensor();
160 sensor.start();
161
162 this.sensors.light = {
163 sensor,
164 detectLighting: () => {
165 const lux = sensor.illuminance || 500;
166
167 if (lux < 50) return 'dark';
168 if (lux < 200) return 'dim';
169 if (lux < 1000) return 'normal';
170 return 'bright';
171 }
172 };
173
174 console.log('Light sensor enabled');
175 } else {
176 // Fallback: Use time of day
177 this.sensors.light = {
178 detectLighting: () => {
179 const hour = new Date().getHours();
180
181 if (hour < 6 || hour > 20) return 'dark';
182 if (hour < 8 || hour > 18) return 'dim';
183 return 'normal';
184 }
185 };
186
187 console.log('Light detection using time-based fallback');
188 }
189 } catch (error) {
190 console.warn('Light detection not available:', error.message);
191 this.sensors.light = { detectLighting: () => 'normal' };
192 }
193 }
194
195 // ========================================================================
196 // MOTION DETECTION - Device orientation and movement
197 // ========================================================================
198
199 async setupMotionDetection() {
200 try {
201 if ('DeviceOrientationEvent' in window) {
202 let orientation = { alpha: 0, beta: 0, gamma: 0 };
203
204 window.addEventListener('deviceorientation', (event) => {
205 orientation = {
206 alpha: event.alpha || 0,
207 beta: event.beta || 0,
208 gamma: event.gamma || 0
209 };
210 });
211
212 this.sensors.motion = {
213 orientation,
214 detectOrientation: () => {
215 // Detect if device is portrait or landscape
216 // Detect if device is flat (on table) vs held
217 const beta = Math.abs(orientation.beta);
218
219 if (beta < 30) return 'flat'; // On table/desk
220 if (beta < 60) return 'tilted'; // Partially held
221 return 'held'; // Actively held
222 }
223 };
224
225 console.log('Motion detection enabled');
226 } else {
227 this.sensors.motion = { detectOrientation: () => 'unknown' };
228 }
229 } catch (error) {
230 console.warn('Motion detection not available:', error.message);
231 this.sensors.motion = { detectOrientation: () => 'unknown' };
232 }
233 }
234
235 // ========================================================================
236 // IDLE DETECTION - User activity state
237 // ========================================================================
238
239 async setupIdleDetection() {
240 let lastActivity = Date.now();
241 let idleTimeout = null;
242
243 const resetIdleTimer = () => {
244 lastActivity = Date.now();
245 if (idleTimeout) {
246 clearTimeout(idleTimeout);
247 }
248 };
249
250 // Track user activity
251 ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'].forEach(event => {
252 document.addEventListener(event, resetIdleTimer, true);
253 });
254
255 this.sensors.idle = {
256 lastActivity,
257 detectIdleState: () => {
258 const idleTime = Date.now() - lastActivity;
259
260 if (idleTime < 5000) return 'active'; // Active in last 5 seconds
261 if (idleTime < 30000) return 'idle'; // Idle for 5-30 seconds
262 return 'away'; // Away for more than 30 seconds
263 }
264 };
265
266 // Try to use official Idle Detection API if available
267 if ('IdleDetector' in window) {
268 try {
269 const idleDetector = new IdleDetector();
270 idleDetector.addEventListener('change', () => {
271 const userState = idleDetector.userState; // 'active' or 'idle'
272 const screenState = idleDetector.screenState; // 'locked' or 'unlocked'
273
274 console.log(`Idle state: ${userState}, Screen: ${screenState}`);
275 });
276
277 await idleDetector.start({ threshold: 60000 });
278 console.log('Idle detection API enabled');
279 } catch (error) {
280 console.warn('Idle detection API error:', error.message);
281 }
282 }
283
284 console.log('Idle detection enabled');
285 }
286
287 // ========================================================================
288 // NETWORK DETECTION - Connection quality
289 // ========================================================================
290
291 async setupNetworkDetection() {
292 try {
293 const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
294
295 if (connection) {
296 this.sensors.network = {
297 connection,
298 detectQuality: () => {
299 const effectiveType = connection.effectiveType; // '4g', '3g', '2g', 'slow-2g'
300 const downlink = connection.downlink; // Mbps
301 const rtt = connection.rtt; // Round-trip time in ms
302
303 if (effectiveType === '4g' && downlink > 10) return 'excellent';
304 if (effectiveType === '4g' || downlink > 5) return 'good';
305 if (effectiveType === '3g') return 'fair';
306 return 'poor';
307 }
308 };
309
310 connection.addEventListener('change', () => {
311 console.log('Network conditions changed:', this.sensors.network.detectQuality());
312 this.updateContext();
313 });
314
315 console.log('Network detection enabled');
316 } else {
317 this.sensors.network = { detectQuality: () => 'unknown' };
318 }
319 } catch (error) {
320 console.warn('Network detection not available:', error.message);
321 this.sensors.network = { detectQuality: () => 'unknown' };
322 }
323 }
324
325 // ========================================================================
326 // CONTINUOUS DETECTION
327 // ========================================================================
328
329 start() {
330 if (this.isRunning) return;
331
332 this.isRunning = true;
333
334 // Update context every second
335 this.detectionInterval = setInterval(() => {
336 this.updateContext();
337 }, 1000);
338
339 // Initial update
340 this.updateContext();
341
342 console.log('Context detection started');
343 }
344
345 stop() {
346 if (!this.isRunning) return;
347
348 this.isRunning = false;
349
350 if (this.detectionInterval) {
351 clearInterval(this.detectionInterval);
352 this.detectionInterval = null;
353 }
354
355 // Stop all sensors
356 if (this.sensors.audio?.stream) {
357 this.sensors.audio.stream.getTracks().forEach(track => track.stop());
358 }
359 if (this.sensors.video?.stream) {
360 this.sensors.video.stream.getTracks().forEach(track => track.stop());
361 }
362 if (this.sensors.light?.sensor) {
363 this.sensors.light.sensor.stop();
364 }
365
366 console.log('Context detection stopped');
367 }
368
369 updateContext() {
370 const updates = {
371 environment: {
372 noiseLevel: this.sensors.audio?.detectNoise() || 0,
373 viewerCount: this.sensors.video?.detectViewers() || 1,
374 lighting: this.sensors.light?.detectLighting() || 'normal',
375 orientation: this.sensors.motion?.detectOrientation() || 'unknown'
376 },
377 user: {
378 idleState: this.sensors.idle?.detectIdleState() || 'active',
379 isBusy: this.sensors.idle?.detectIdleState() === 'active',
380 networkQuality: this.sensors.network?.detectQuality() || 'unknown'
381 }
382 };
383
384 // Update context manager
385 this.context.updateContext(updates);
386 }
387
388 // ========================================================================
389 // MANUAL SIMULATION (for testing without permissions)
390 // ========================================================================
391
392 simulate(config) {
393 // Allow manual simulation for testing
394 console.log('Simulating context:', config);
395
396 this.context.updateContext({
397 environment: {
398 noiseLevel: config.noiseLevel !== undefined ? config.noiseLevel : this.context.context.environment.noiseLevel,
399 viewerCount: config.viewerCount !== undefined ? config.viewerCount : this.context.context.environment.viewerCount,
400 lighting: config.lighting || this.context.context.environment.lighting,
401 isPublic: config.isPublic !== undefined ? config.isPublic : this.context.context.environment.isPublic
402 },
403 user: {
404 isBusy: config.isBusy !== undefined ? config.isBusy : this.context.context.user.isBusy,
405 inFocusMode: config.inFocusMode !== undefined ? config.inFocusMode : this.context.context.user.inFocusMode
406 }
407 });
408 }
409}
410
411// Initialize context detection when ready
412if (typeof window !== 'undefined') {
413 window.addEventListener('DOMContentLoaded', async () => {
414 if (window.semanticContext) {
415 window.contextDetection = new ContextDetectionSystem(window.semanticContext);
416
417 // Don't auto-start (requires permissions)
418 // User can manually start via window.contextDetection.start()
419
420 console.log('Context detection system ready. Call window.contextDetection.start() to begin.');
421
422 // Add keyboard shortcut to toggle (Ctrl+Shift+C)
423 document.addEventListener('keydown', (e) => {
424 if (e.ctrlKey && e.shiftKey && e.key === 'C') {
425 e.preventDefault();
426 if (window.contextDetection.isRunning) {
427 window.contextDetection.stop();
428 } else {
429 window.contextDetection.start();
430 }
431 }
432 });
433 }
434 });
435}
436
437// Export
438if (typeof module !== 'undefined' && module.exports) {
439 module.exports = ContextDetectionSystem;
440}