-
Notifications
You must be signed in to change notification settings - Fork 5
/
copyAsMDLink.js
372 lines (322 loc) · 11.1 KB
/
copyAsMDLink.js
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
(() => {
"use strict";
// Rob Trew @ 2020
// Copy Markdown Link to front document, URL, or resource.
// Ver 0.33
// Switched to running app-specific macros by UUID
// fetched from a JSON dictionary stored in a
// uuidsForMDLink KM variable.
// If this variable is not found, or a UUID retrieved
// from it is not found, then the dictionary is regenerated.
// The regeneration, which will happen on the first
// run, but should only be needed thereafter when
// new sub-macros are added, will activate Keyboard Maestro.app
// Normally use of the macro will, however, normally
// bypass Keyboard Maestro.app and run through
// Keyboard Maestro Engine instead.
ObjC.import("AppKit");
const kmGroupName = "MD link tools";
// ---------------------- MAIN -----------------------
// main :: IO ()
// eslint-disable-next-line max-lines-per-function
const main = () => {
const bundleID = frontAppBundleId();
return either(
msg => (
alert("Copy as Markdown link")(msg),
msg
)
)(
mdLink => mdLink
)(
bindLR(
void 0 !== bundleID
? Right(bundleID)
: Left(
"No active application detected"
)
)(linkForBundleLR)
);
};
// linkForBundleLR :: String -> Either String String
const linkForBundleLR = bundleID =>
// ------------ BROWSER ? ------------
[
"com.apple.Safari",
"com.google.Chrome",
"com.microsoft.edgemac",
"com.vivaldi.Vivaldi",
"com.kagi.kagimacOS",
"com.operasoftware.Opera",
"company.thebrowser.Browser"
].includes(bundleID)
? browserLinkLR(bundleID)
: (() => {
// ---- APP-SPECIFIC MACRO ? -----
const
kme = Application("Keyboard Maestro Engine"),
dctUUID = either(
msg => (
// eslint-disable-next-line no-console
console.log(
"BundleID map had to be regenerated",
msg
),
// Regenerated UUID dictionary
updatedUUIDMap()
)
)(
// UUID dictionary from existing
// KM Variable
dct => dct
)(
jsonParseLR(
kme.getvariable("uuidsForMDLink")
)
);
return linkFromUUID(kme)(bundleID)(
dctUUID[bundleID]
);
})();
// linkFromUUID :: Application ->
// String -> String -> String
const linkFromUUID = kme =>
bundleID => maybeUUID => Boolean(maybeUUID)
? either(
// If the UUID wasn"t found,
// then run a new one from an
// updated dictionary.
() => (
bindLR(
doScriptLR(kme)(
updatedUUIDMap()[bundleID]
)
)(
// Link after use of alternate UUID
() => Right(
kme.getvariable("mdLink")
)
)
)
)(
// Link read after with UUID
() => Right(kme.getvariable("mdLink"))
)(
// Run macro with this UUID if possible.
doScriptLR(kme)(maybeUUID)
)
: appFrontWindowMDLinkLR(bundleID);
// doScriptLR :: UUID -> Either String String
const doScriptLR = kme =>
uuid => {
try {
return (
kme.doScript(uuid),
Right(uuid)
);
} catch (e) {
return Left(
`Macro UUID :: ${uuid}\n\n${e.message}`
);
}
};
// -------------- BUNDLEID -> UUID MAP ---------------
// updatedUUIDMap :: IO () -> { bundleID :: UUID }
const updatedUUIDMap = () => {
const
macroGroupName = "MD Link tools",
mdLinkToolsGroups = Application(
"Keyboard Maestro"
).macroGroups.where({
name: macroGroupName
});
return either(
alert("Copy as MD Link - Map bundle to UUID")
)(
dictUUIDs => (
Application("Keyboard Maestro Engine")
.setvariable("uuidsForMDLink", {
to: JSON.stringify(
dictUUIDs, null, 2
)
}),
dictUUIDs
)
)(
0 < mdLinkToolsGroups.length
? (() => {
const
instances = mdLinkToolsGroups.at(0)
.macros()
.flatMap(macro => {
const k = macro.name();
return k.includes(".")
? [[k, macro.id()]]
: [];
});
return Right(
instances.reduce(
(a, [bundle, uuid]) => Object.assign(
a, {
[bundle]: uuid
}
), {}
)
);
})()
: Left(
`Macro group not found:\n\n\t${macroGroupName}`
)
);
};
// --------------------- BROWSERS ----------------------
// browserLinkLR :: String -> Either String IO String
const browserLinkLR = bundleID => {
const w = Application(bundleID).windows.at(0);
return "company.thebrowser.Browser" !== bundleID
? w.exists()
? w.tabs.at(0).exists()
? (() => {
const
tab = w[
[
"com.apple.Safari",
"com.kagi.kagimacOS"
]
.includes(bundleID)
? "currentTab"
: "activeTab"
]();
return Right(
`[${tab.name()}](${tab.url()})`
);
})()
: Left(
`No open tabs in front window of ${bundleID}`
)
: Left(`No windows open in ${bundleID}`)
: Right(
(() => {
const tab = w.activeTab;
return `[${tab.title()}](${tab.url()})`;
})()
);
};
// ----------------------- JXA -----------------------
// frontAppBundleId :: () -> String
const frontAppBundleId = () => {
const uw = ObjC.unwrap;
return uw(uw(
$.NSWorkspace.sharedWorkspace.activeApplication
).NSApplicationBundleIdentifier);
};
// ------- DEFAULT - DOCUMENT OF FRONT WINDOW --------
// appFrontWindowMDLinkLR :: String -> Either String String
const appFrontWindowMDLinkLR = bundleID => {
const
procs = Object.assign(
Application("System Events"), {
includeStandardAdditions: true
})
.applicationProcesses.where({
bundleIdentifier: bundleID
});
return bindLR(
bindLR(
procs.length > 0
? Right(procs.at(0).windows)
: Left(`Application not found: ${bundleID}`)
)(ws => ws.length > 0
? Right(ws.at(0))
: Left(`No windows found for ${bundleID}`))
)(w => {
const
uw = ObjC.unwrap,
[winTitle, maybeDocURL] = [
"AXTitle", "AXDocument"
]
.map(appID => uw(
w.attributes.byName(appID).value()
));
return Boolean(maybeDocURL)
? Right(`[${winTitle}](${maybeDocURL})`)
: Left(
[
`Window "${winTitle}" of:\n\n\t${bundleID}`,
"\nmay not be a document window.",
`\nConsider adding a macro named "${bundleID}"`,
`to the KM Group "${kmGroupName}".`,
"\n(Or request such a macro, which should",
"save a [label](url) string) in the",
"KM variable \"mdLink\")",
"on the Keyboard Maestro forum)."
].join("\n")
);
});
};
// alert :: String => String -> IO String
const alert = title =>
s => {
const sa = Object.assign(
Application("System Events"), {
includeStandardAdditions: true
});
return (
sa.activate(),
sa.displayDialog(s, {
withTitle: title,
buttons: ["OK"],
defaultButton: "OK"
}),
s
);
};
// ----------------- GENERIC FUNCTIONS -----------------
// https://github.com/RobTrew/prelude-jxa
// Left :: a -> Either a b
const Left = x => ({
type: "Either",
Left: x
});
// Right :: b -> Either a b
const Right = x => ({
type: "Either",
Right: x
});
// bindLR (>>=) :: Either a ->
// (a -> Either b) -> Either b
const bindLR = m =>
mf => undefined !== m.Left
? m
: mf(m.Right);
// either :: (a -> c) -> (b -> c) -> Either a b -> c
const either = fl =>
// Application of the function fl to the
// contents of any Left value in e, or
// the application of fr to its Right value.
fr => e => "Left" in e
? fl(e.Left)
: fr(e.Right);
// jsonParseLR :: String -> Either String a
const jsonParseLR = s => {
// Either a message, or a JS value obtained
// from a successful parse of s.
try {
return Right(JSON.parse(s));
} catch (e) {
return Left(
`${e.message} (line:${e.line} col:${e.column})`
);
}
};
// showLog :: a -> IO ()
const showLog = (...args) =>
// eslint-disable-next-line no-console
console.log(
args
.map(JSON.stringify)
.join(" -> ")
);
// MAIN ---
return main();
})();