Last active
October 12, 2022 16:52
-
-
Save ubershmekel/dfb4ed1a15859d858f6e9c2d36185735 to your computer and use it in GitHub Desktop.
This is slow, but it works, to find the text that's highlighted by a monaco editor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Paste this into JS to find an ACE editor in your browser window | |
// Based off of https://stackoverflow.com/questions/12102425/recursively-search-for-a-value-in-global-variables-and-its-properties/12103127#12103127 | |
function isTarget(obj) { | |
// return typeof obj == typeof value && obj == value | |
if (obj && obj['getModel'] && obj.getModel() && obj.getModel().getValueInRange) { | |
const highlight = obj.getModel().getValueInRange(obj.getSelection()) | |
if (highlight) { | |
console.log('highlight', highlight); | |
return true; | |
} | |
} | |
return false; | |
} | |
function globalSearch(startObject, isTargetFunc) { | |
var stack = [[startObject, '']]; | |
var searched = new Set(); | |
var found = false; | |
var isArray = function (test) { | |
return Object.prototype.toString.call(test) === '[object Array]'; | |
} | |
while (stack.length) { | |
var fromStack = stack.pop(); | |
var obj = fromStack[0]; | |
var address = fromStack[1]; | |
searched.add(obj); | |
try { | |
if (isTargetFunc(obj)) { | |
var found = address; | |
console.log(address); | |
return obj.getModel().getValueInRange(obj.getSelection()); | |
// break; | |
} | |
if (typeof obj == "object") { | |
// dive into the object | |
if (isArray(obj)) { | |
var prefix = '['; | |
var postfix = ']'; | |
} else { | |
var prefix = '.'; | |
var postfix = ''; | |
} | |
for (key in obj) { | |
if ([ | |
// comment out more of these to have a more thorough but redundant search | |
// '_rootLView', | |
// '_view', '_hostLView', '_cdRefInjectingView', | |
'_lView', '_declarationLView', '_lContainer', '_thenViewRef', | |
'next', 'prev', 'parent', '_parentOrParents', | |
'children', 'firstElementChild', 'lastElementChild', 'offsetParent', 'previousElementSibling', 'nextElementSibling', 'ownerDocument', | |
'styleSheets', 'parentNode', 'parentElement', 'childNodes', 'firstChild', 'nextSibling', 'previousSibling', 'lastChild', | |
].includes(key)) { | |
continue; | |
} | |
if (prefix === '.' && !key[0].match(/[_a-z]/i)) { | |
prefix = '["'; | |
postfix = '"]'; | |
} | |
if (searched.has(obj[key])) { | |
continue; | |
} | |
stack.push([obj[key], address + prefix + key + postfix]); | |
} | |
} | |
} catch (err) { | |
// console.log("error at", address, err); | |
} | |
} | |
// return found == '' ? true : found; | |
return false; | |
} | |
globalSearch(window, isTarget); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment