[Utils] Merge from pre-rewrite

This commit is contained in:
Beef 2022-10-18 23:21:58 +01:00
parent ae616da565
commit 110181b6fd
5 changed files with 68 additions and 1 deletions

7
src/def.d.ts vendored
View file

@ -18,6 +18,13 @@ interface Logger {
verbose: LoggerFunction, verbose: LoggerFunction,
} }
type SearchFilter = (tree: any) => boolean;
interface FindInTreeOptions {
walkable?: string[];
ignore?: string[];
maxDepth?: number;
}
interface VendettaObject { interface VendettaObject {
patcher: { patcher: {
after: typeof _spitroast.after; after: typeof _spitroast.after;

11
src/lib/utils/copyText.ts Normal file
View file

@ -0,0 +1,11 @@
import { findByProps } from "@metro/filters";
const clipboard = findByProps("setString", "getString");
export default function copyText(content: string) {
try {
clipboard.setString(content);
} catch (e) {
throw new Error("Failed to set clipboard content.")
}
}

View file

@ -0,0 +1,8 @@
import { SearchFilter } from "@types";
import findInTree from "@utils/findInTree";
export default function findInReactTree(tree: { [key: string]: any }, filter: SearchFilter): any {
return findInTree(tree, filter, {
walkable: ["props", "children", "child", "sibling"],
});
}

View file

@ -0,0 +1,40 @@
/*
Disclaimer: https://github.com/Cordwood/Cordwood/blob/91c0b971bbf05e112927df75415df99fa105e1e7/src/lib/utils/findInTree.ts
*/
import { FindInTreeOptions, SearchFilter } from "@types";
export default function findInTree(tree: { [key: string]: any }, filter: SearchFilter, { walkable = [], ignore = [], maxDepth = 100 }: FindInTreeOptions = {}): any {
let iteration = 0;
function doSearch(tree: { [key: string]: any }, filter: SearchFilter, { walkable = [], ignore = [] }: FindInTreeOptions = {}): any {
iteration += 1;
if (iteration > maxDepth) return;
if (typeof filter === "string") {
if (tree.hasOwnProperty(filter)) return tree[filter];
} else if (filter(tree)) return tree;
if (!tree) return;
if (Array.isArray(tree)) {
for (const item of tree) {
const found = doSearch(item, filter, { walkable, ignore });
if (found) return found;
}
} else if (typeof tree === "object") {
for (const key of Object.keys(tree)) {
if (walkable != null && walkable.includes(key)) continue;
if (ignore.includes(key)) continue;
try {
const found = doSearch(tree[key], filter, { walkable, ignore });
if (found) return found;
} catch {}
}
}
}
return doSearch(tree, filter, { walkable, ignore });
}

View file

@ -16,7 +16,8 @@
"@/*": ["src/*"], "@/*": ["src/*"],
"@types": ["src/def.d.ts"], "@types": ["src/def.d.ts"],
"@lib/*": ["src/lib/*"], "@lib/*": ["src/lib/*"],
"@metro/*": ["src/lib/metro/*"] "@metro/*": ["src/lib/metro/*"],
"@utils/*": ["src/lib/utils/*"]
} }
} }
} }