-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelementHTML.ts
69 lines (64 loc) · 2.59 KB
/
elementHTML.ts
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
import { getFrontmostApplication } from "@raycast/api";
import { Placeholder, PlaceholderCategory, PlaceholderType } from "../types";
import { runJSInActiveTab } from "../utils";
/**
* Placeholder for the raw HTML of the first element matching the given selector in the active tab of a supported browser.
*
* Syntax: `{{elementHTML:<selector>}}`, where `<selector>` is a valid CSS selector.
*/
const ElementHTMLPlaceholder: Placeholder = {
name: "elementHTML",
regex:
/{{(HTMLOfElement|element|elementHTML)( browser="(.*)")?:(([^{]|{(?!{)|{{[\s\S]*?}})*?)}}/g,
apply: async (str: string, context?: { [key: string]: unknown }) => {
try {
const specifier = str.match(
/{{(HTMLOfElement|element|elementHTML)( browser="(.*)")?:(([^{]|{(?!{)|{{[\s\S]*?}})*?)}}/
)?.[4];
if (!specifier) return { result: "" };
const browser = str.match(
/{{(HTMLOfElement|element|elementHTML)( browser="(.*)"):(([^{]|{(?!{)|{{[\s\S]*?}})*?)}}/
)?.[3];
const appName = browser
? browser
: context?.["currentAppName"]
? context["currentAppName"]
: (await getFrontmostApplication()).name;
let js = `document.getElementById('${specifier}')?.outerHTML`;
if (specifier.startsWith(".")) {
js = `document.getElementsByClassName('${specifier.slice(
1
)}')[0]?.outerHTML`;
} else if (specifier.startsWith("#")) {
js = `document.getElementById('${specifier.slice(1)}')?.outerHTML`;
} else if (specifier.startsWith("[")) {
js = `document.querySelector('${specifier}')?.outerHTML`;
} else if (specifier.startsWith("<") && specifier.endsWith(">")) {
js = `document.getElementsByTagName('${specifier.slice(
1,
-1
)}')[0]?.outerHTML`;
}
const elementHTML = await runJSInActiveTab(js, appName as string);
return { result: elementHTML };
} catch (e) {
return { result: "" };
}
},
dependencies: ["currentAppName"],
constant: false,
fn: async (specifier: string, browser?: string) =>
(
await ElementHTMLPlaceholder.apply(
`{{element${browser ? ` browser="${browser}"` : ``}:${specifier}}}`
)
).result,
example: "Summarize this: {{elementHTML:#article}}",
description:
"Replaced with the raw HTML source of an HTML element in the active tab of any supported browser.",
hintRepresentation: "{{elementHTML}}",
fullRepresentation: "HTML of Browser Element With Specifier",
type: PlaceholderType.InteractiveDirective,
categories: [PlaceholderCategory.Internet],
};
export default ElementHTMLPlaceholder;