-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathORIG-tampermonkey-cursor-control.js
More file actions
447 lines (397 loc) · 15.8 KB
/
ORIG-tampermonkey-cursor-control.js
File metadata and controls
447 lines (397 loc) · 15.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// ==UserScript==
// @name Google Docs High-Contrast Red Caret + Red Pointer (overlay, v1.9 HOTKEY toggle)
// @namespace https://carethelp.example
// @version 1.9
// @description Bright red overlay caret + optional red mouse pointer in Google Docs. Skips bogus about:blank frames, ignores zero rects, and includes deep debug logging. HOTKEYS master toggle included.
// @author https://github.com/IanWardell/
// @match https://docs.google.com/document/*
// @run-at document-start
// @grant none
// ==/UserScript==
//Original Script I based the loader off of
(function () {
'use strict';
// =========================
// ======= CONFIG ==========
// =========================
var CARET_COLOR = '#ff0000'; // Overlay caret color
var CARET_WIDTH = 1; // Overlay caret width, px
var CARET_BLINKMS = 500; // Overlay caret blink period
var HOLD_LAST_MS = 650; // Keep last caret briefly when selection disappears (ms)
var DEBUG = false; // Global debug logs for this script to console (toggle with Ctrl+Alt+D if hotkeys enabled)
// Red pointer options (toggle with Ctrl+Alt+P if hotkeys enabled)
var RED_POINTER_ENABLED = true; // default ON
var RED_POINTER_FORCE_EVERYWHERE = false; // false = keep I-beam in editable text, true = arrow everywhere
var RED_POINTER_PIXEL_SIZE = 12; // pointer SVG nominal size (small default)
// Hotkeys master toggle. If false, NO hotkeys are registered.
var HOTKEYS = false;
// =========================
// ===== UTIL / LOGS =======
// =========================
function log(){ if(DEBUG) console.log.apply(console, ['[DocsCaret]'].concat([].slice.call(arguments))); }
function warn(){ if(DEBUG) console.warn.apply(console, ['[DocsCaret]'].concat([].slice.call(arguments))); }
function err(){ if(DEBUG) console.error.apply(console, ['[DocsCaret]'].concat([].slice.call(arguments))); }
// "Zero-ish" rect filter. A real caret should have some height and near-zero width.
function isZeroishRect(r){
if(!r) return true;
var h = Math.max(0, r.height || 0);
// Reject tiny heights and the common bogus (0,0,16) fallback we observed
return (h < 8) || (r.left === 0 && r.top === 0 && h === 16);
}
// =========================
// ======= DEBUG UI ========
// =========================
function ensureDebugBadge(doc){
try{
var id='__docsCaretDebugBadge';
var el=doc.getElementById(id);
if(!DEBUG){ if(el) el.remove(); return; }
if(el) return;
var b=doc.createElement('div');
b.id=id; b.textContent='DocsCaret DEBUG';
Object.assign(b.style,{
position:'fixed', right:'6px', bottom:'6px', zIndex:'2147483647',
font:'12px/1.4 system-ui, Arial, sans-serif', padding:'4px 6px',
background:'rgba(255,0,0,0.12)', border:'1px solid rgba(255,0,0,0.35)',
borderRadius:'6px', color:'#900', userSelect:'none', pointerEvents:'none'
});
(doc.body||doc.documentElement).appendChild(b);
}catch(e){/* ignore */}
}
// =========================
// ===== CARET OVERLAY =====
// =========================
function ensureCaretForDoc(doc){
try{
if(!doc || !doc.documentElement) return null;
if(!doc.__overlayCaret){
var c=doc.createElement('div');
c.id='__overlayRedCaret';
c.style.position='fixed';
c.style.left='0'; c.style.top='0';
c.style.width=CARET_WIDTH+'px';
c.style.height='16px';
c.style.background=CARET_COLOR;
c.style.pointerEvents='none';
c.style.zIndex='2147483647';
c.style.visibility='hidden';
c.style.willChange='transform,opacity';
c.style.opacity='1';
(doc.body||doc.documentElement).appendChild(c);
doc.__overlayCaret=c;
doc.__overlayCaretVisible=false;
doc.__overlayCaretEnabled=true;
doc.__overlayLastShowTs=0;
// Blink
var blink=true;
setInterval(function(){
if(!doc.__overlayCaretEnabled){ c.style.opacity='0'; return; }
if(doc.__overlayCaretVisible){ blink=!blink; c.style.opacity=blink?'1':'0'; }
else { c.style.opacity='0'; }
}, CARET_BLINKMS);
attachDocListeners(doc);
// Best-effort native caret-color for editable areas
try{
var s=doc.createElement('style');
s.textContent='textarea, input, [contenteditable="true"], [role="textbox"], .kix-appview-editor * { caret-color: '+CARET_COLOR+' !important; }';
(doc.head||doc.documentElement).appendChild(s);
}catch(_){}
}
ensureDebugBadge(doc);
return doc.__overlayCaret;
}catch(e){ warn('ensureCaretForDoc failed', e); return null; }
}
function getAllDocs(rootDoc){
var out=[];
function walk(d){
if(!d||!d.documentElement) return;
out.push(d);
var ifr=d.getElementsByTagName('iframe');
for(var i=0;i<ifr.length;i++){
try{ if(ifr[i].contentDocument) walk(ifr[i].contentDocument); }catch(e){}
}
}
walk(rootDoc||document);
return out;
}
function looksLikeDocsEditor(doc){
try{
if (doc.querySelector('.kix-appview-editor, .kix-page, .kix-canvas-tile-content, .kix-lineview, .kix-contentarea')) return true;
var u = (doc.URL||'') + '';
if (u.startsWith('https://docs.google.com/')) return true;
}catch(_){}
return false;
}
function collapsedSelectionRect(d){
try{
var sel=d.getSelection && d.getSelection();
if(!sel || sel.rangeCount===0 || !sel.isCollapsed) return null;
var range=sel.getRangeAt(0);
var rects=range.getClientRects&&range.getClientRects();
if(rects && rects.length){
var r=rects[rects.length-1];
if(r && (r.width || r.height)) return r;
}
var br=range.getBoundingClientRect&&range.getBoundingClientRect();
if(br && (br.width||br.height)) return br;
// Zero-width span fallback
var span=d.createElement('span');
span.style.display='inline-block'; span.style.width='0'; span.style.height='1em';
span.appendChild(d.createTextNode('\u200B'));
var r2=range.cloneRange(); r2.collapse(true); r2.insertNode(span);
var srect=span.getBoundingClientRect(); if(span.parentNode) span.parentNode.removeChild(span);
if(srect && (srect.width||srect.height)) return srect;
}catch(_){}
return null;
}
function docsDOMCaretRect(d){
try{
var candidates = d.querySelectorAll([
'.kix-cursor-caret',
'.kix-cursor',
'[class*="cursor-caret"]',
'.kix-lineview-cursor',
'.kix-contentarea *[style*="cursor-color"]'
].join(','));
for(var i=0;i<candidates.length;i++){
var el=candidates[i];
var st=d.defaultView.getComputedStyle(el);
if(st && st.display==='none') continue;
var r=el.getBoundingClientRect();
if(r && r.height>8 && r.width<=6) return r;
}
}catch(_){}
return null;
}
function findActiveSelectionRect(){
var docs=getAllDocs(document);
// Prefer likely editor docs
var pri=[], sec=[];
for (var i=0;i<docs.length;i++){
var d=docs[i];
(looksLikeDocsEditor(d) ? pri : sec).push(d);
}
var ordered = pri.concat(sec);
for (var j=0;j<ordered.length;j++){
var d=ordered[j];
// @author https://github.com/IanWardell/
// 1) Selection API
var r = collapsedSelectionRect(d);
if(r && !isZeroishRect(r)){
return {doc:d, rect:r, src:'selection'};
}
// 2) DOM caret heuristic
var r2 = docsDOMCaretRect(d);
if(r2 && !isZeroishRect(r2)){
return {doc:d, rect:r2, src:'dom-caret'};
}
}
return null;
}
function hideAllExcept(targetDoc){
var docs=getAllDocs(document);
for(var i=0;i<docs.length;i++){
var d=docs[i], c=d.__overlayCaret;
if(!c) continue;
if(d!==targetDoc){ c.style.visibility='hidden'; d.__overlayCaretVisible=false; }
}
}
function updateCaretPositionGlobal(reason){
var found=findActiveSelectionRect();
if(!found){
var now=Date.now(), docs=getAllDocs(document), anyVisible=false;
for(var i=0;i<docs.length;i++){
var d=docs[i], c=d.__overlayCaret;
if(!c) continue;
var keep=(now-(d.__overlayLastShowTs||0))<HOLD_LAST_MS && d.__overlayCaretEnabled;
if(!keep){ c.style.visibility='hidden'; d.__overlayCaretVisible=false; }
else anyVisible=true;
}
if(DEBUG) log('Caret hidden (no collapsed selection)', reason, {kept:anyVisible});
return;
}
var d=found.doc, rect=found.rect;
var caret=ensureCaretForDoc(d);
if(!caret || !d.__overlayCaretEnabled) return;
var left=rect.left, top=rect.top, h=Math.max(rect.height||16,12);
//iaw
caret.style.transform='translate('+Math.round(left)+'px,'+Math.round(top)+'px)';
caret.style.height=Math.round(h)+'px';
caret.style.visibility='visible';
d.__overlayCaretVisible=true;
d.__overlayLastShowTs=Date.now();
hideAllExcept(d);
if(DEBUG) log('Caret updated', {url:(d.URL||'???'), left:left, top:top, height:h, source:found.src, reason:reason});
}
function attachDocListeners(doc){
var scheduled=false;
function schedule(reason){
if(scheduled) return; scheduled=true;
setTimeout(function(){ scheduled=false; updateCaretPositionGlobal(reason); }, 16);
}
['selectionchange','keyup','keydown','input','mouseup','mousedown','touchend','touchstart']
.forEach(function(ev){ doc.addEventListener(ev, function(){ if(DEBUG) log('Event',ev,'-> update'); schedule(ev); }, true); });
(doc.defaultView||window).addEventListener('scroll', function(){ schedule('scroll'); }, true);
(doc.defaultView||window).addEventListener('resize', function(){ schedule('resize'); }, true);
// Boot polling to catch editor swaps
var tries=0, max=120;
var boot=setInterval(function(){ updateCaretPositionGlobal('boot#'+tries); tries++; if(tries>=max) clearInterval(boot); }, 250);
}
// =========================
// ===== RED POINTER =======
// =========================
function buildRedCursorDataURL(pixelSize){
var w = Math.max(12, Math.min(48, pixelSize||12)); // clamp to keep it small
var h = Math.round(w*1.5);
// Keep path constant (viewBox 32x48) so hotspot stays consistent; size is controlled by width/height.
var svg =
"<svg xmlns='http://www.w3.org/2000/svg' width='"+w+"' height='"+h+"' viewBox='0 0 32 48'>"+
" <path d='M1,1 L1,35 L10,28 L14,46 L20,44 L16,26 L31,26 Z' fill='#ff0000' stroke='white' stroke-width='2'/>"+
"</svg>";
return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
}
function applyRedPointerToDoc(doc){
try{
if(!doc || !doc.documentElement) return;
if (!doc.__redPointerStyle) {
var css = doc.createElement('style');
css.id = '__docsRedPointerStyle';
doc.__redPointerStyle = css;
(doc.head||doc.documentElement).appendChild(css);
}
var url = buildRedCursorDataURL(RED_POINTER_PIXEL_SIZE);
// Mode A: everywhere (strongest)
var ruleEverywhere = [
'* { cursor: url("'+url+'") 2 2, auto !important; }'
].join('\n');
// Mode B: non-text areas – try to keep the I-beam in the content editor
var ruleNonText = [
// Editor chrome and panels
'html, body, .kix-appview-editor, .kix-appview-editor *:not([contenteditable="true"]) {',
' cursor: url("'+url+'") 2 2, auto !important;',
'}',
// Do NOT override common text inputs / contenteditable
'[contenteditable="true"], textarea, input[type="text"], input:not([type]) {',
' cursor: auto !important;',
'}'
].join('\n');
doc.__redPointerStyle.textContent = RED_POINTER_ENABLED
? (RED_POINTER_FORCE_EVERYWHERE ? ruleEverywhere : ruleNonText)
: '';
} catch(e){ if(DEBUG) warn('Red pointer apply failed', e); }
}
function applyRedPointerAllDocs(){
(function walk(d){
if(!d) return;
applyRedPointerToDoc(d);
var ifr = d.getElementsByTagName('iframe');
for (var i=0;i<ifr.length;i++){
try { if (ifr[i].contentDocument) walk(ifr[i].contentDocument); } catch(_) {}
}
})(document);
}
// =========================
// ======= HOTKEYS =========
// =========================
if (HOTKEYS) {
document.addEventListener('keydown', function(e){
if(!(e.ctrlKey&&e.altKey)) return;
// Toggle caret overlay on/off
if(e.code==='KeyC'){
var docs=getAllDocs(document);
var state;
for(var i=0;i<docs.length;i++){
var d=docs[i]; ensureCaretForDoc(d);
d.__overlayCaretEnabled=!d.__overlayCaretEnabled;
if(!d.__overlayCaretEnabled && d.__overlayCaret){ d.__overlayCaret.style.visibility='hidden'; d.__overlayCaretVisible=false; }
state=d.__overlayCaretEnabled; ensureDebugBadge(d);
}
log('Toggle caret enabled ->', state); e.preventDefault();
return;
}
// Toggle DEBUG logs + badge
if(e.code==='KeyD'){
DEBUG=!DEBUG;
var d2=getAllDocs(document);
for(var j=0;j<d2.length;j++) ensureDebugBadge(d2[j]);
console.log('[DocsCaret] DEBUG ->', DEBUG); e.preventDefault();
return;
}
// Toggle red pointer
if(e.code==='KeyP'){
RED_POINTER_ENABLED = !RED_POINTER_ENABLED;
console.log('[DocsCaret] Red Pointer ->', RED_POINTER_ENABLED);
applyRedPointerAllDocs();
e.preventDefault();
return;
}
// Shrink pointer size
if(e.code==='Minus' || e.code==='NumpadSubtract'){
RED_POINTER_PIXEL_SIZE = Math.max(10, RED_POINTER_PIXEL_SIZE - 2);
console.log('[DocsCaret] Pointer size ->', RED_POINTER_PIXEL_SIZE);
applyRedPointerAllDocs();
e.preventDefault();
return;
}
// Grow pointer size
if(e.code==='Equal' || e.code==='NumpadAdd'){
RED_POINTER_PIXEL_SIZE = Math.min(48, RED_POINTER_PIXEL_SIZE + 2);
console.log('[DocsCaret] Pointer size ->', RED_POINTER_PIXEL_SIZE);
applyRedPointerAllDocs();
e.preventDefault();
return;
}
// Quick preset tiny pointer
if(e.code==='Digit9'){
RED_POINTER_PIXEL_SIZE = 10;
console.log('[DocsCaret] Pointer size ->', RED_POINTER_PIXEL_SIZE);
applyRedPointerAllDocs();
e.preventDefault();
return;
}
}, true);
}
// =========================
// ========= INIT ==========
// =========================
(function initAll(){
// Prepare caret + pointer on all reachable docs
var docs=getAllDocs(document);
for(var i=0;i<docs.length;i++){
ensureCaretForDoc(docs[i]);
applyRedPointerToDoc(docs[i]);
}
// Observe new iframes and apply both features
var mo=new MutationObserver(function(muts){
for(var i=0;i<muts.length;i++){
var m=muts[i];
for(var j=0;j<m.addedNodes.length;j++){
var n=m.addedNodes[j];
if(n && n.tagName==='IFRAME'){
try{
if(n.contentDocument){
ensureCaretForDoc(n.contentDocument);
applyRedPointerToDoc(n.contentDocument);
}
}catch(e){}
} else if(n && n.querySelectorAll){
var nested=n.querySelectorAll('iframe');
for(var k=0;k<nested.length;k++){
try{
if(nested[k].contentDocument){
ensureCaretForDoc(nested[k].contentDocument);
applyRedPointerToDoc(nested[k].contentDocument);
}
}catch(e){}
}
}
}
}
});
try{ mo.observe(document.documentElement,{childList:true,subtree:true}); }catch(e){}
// Kick the first update cycle
updateCaretPositionGlobal('init');
// Periodic safety reapply for pointer (Docs chrome can swap)
setInterval(applyRedPointerAllDocs, 2000);
})();
})();