-
Notifications
You must be signed in to change notification settings - Fork 2
/
bionomia.js
235 lines (209 loc) · 6.27 KB
/
bionomia.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
const notice = (msg) => new Notice(msg, 5000);
const log = (msg) => console.log(msg);
const API_SEARCH_URL = "https://api.bionomia.net/user.json";
const USER_PROFILE_URL = "https://bionomia.net";
const TEMPLATE = "Template file:";
const DESTINATION_DIR = "Destination folder:";
const FILENAME_FORMAT = "Filename format:";
const FILENAME_FORMAT_DEFAULT = "{{~fullname~}} {{~fn_lifespan~}}";
const ILLEGAL_OBSIDIAN_FILE_NAME_PATTERN = /[\\,#%&\{\}\/*<>?$\'\":@]*/g;
module.exports = {
entry: start,
settings: {
name: "Bionomia",
// author: "",
options: {
[FILENAME_FORMAT]: {
type: "text",
defaultValue: FILENAME_FORMAT_DEFAULT,
},
[TEMPLATE]: {
type: "select",
options: app.vault.getAbstractFileByPath('templates').children.map((t) => t.path),
},
[DESTINATION_DIR]: {
type: "select",
options: Object.keys(app.vault.fileMap).filter(function (filemapentry){return Object.keys(app.vault.fileMap[filemapentry]).includes('children')}),
},
},
},
};
let QuickAdd;
let Settings;
function init(params, settings) {
QuickAdd = params;
Settings = settings;
}
async function start(params, settings) {
QuickAdd = params;
Settings = settings;
var query = activeDocument.getSelection().toString();
if (typeof query != "string"){
query = null;
}
if (!query){
query = await getQuery();
query = query.searchTerms;
}
if (!query) {
notice("No query entered.");
throw new Error("No query entered.");
}
let possibleProfiles = await getProfilesByQueryParams(query);
let selectedProfile = await promptUserForSelectingSuggestions(possibleProfiles);
if (selectedProfile){
selectedProfile = await augmentProfileData(selectedProfile, query);
// Read in template as defined in settings:
let template_file = app.vault.getAbstractFileByPath(Settings[TEMPLATE]);
let template = await app.vault.read(template_file);
// Apply template to profile:
let rendered = params.app.plugins.getPlugin('obsidian-handlebar-helper-plugin').compileAndRender(template,selectedProfile);
// Build filename and create file:
filename_template = Settings[FILENAME_FORMAT];
fileName = params.app.plugins.getPlugin('obsidian-handlebar-helper-plugin').compileAndRender(filename_template,selectedProfile);
fileName = Settings[DESTINATION_DIR] + '/' + fileName.replace(ILLEGAL_OBSIDIAN_FILE_NAME_PATTERN, "") + '.md';
console.log(fileName);
try{
createdFile = await params.app.vault.create(fileName, rendered);
if (createdFile){
// Open it:
leaf = params.app.workspace.getUnpinnedLeaf();
await leaf.openFile(createdFile)
}
}
catch(Error){
notice('Could not create file / already exists');
}
}
else{
notice("No profile selected");
throw new Error("No profile selected.");
}
}
async function augmentProfileData(selectedProfile, query){
selectedProfile.lifespan = cleanLifeSpan(selectedProfile.lifespan);
selectedProfile.query = query;
return selectedProfile;
}
function formatTitleForSuggestionList(resultItem) {
var suggestion = `${resultItem.fullname_reverse}`;
if (resultItem.lifespan){
suggestion = suggestion + ` (${resultItem.lifespan})`
}
if(resultItem.description){
suggestion = suggestion + ` (${resultItem.description})`
}
return decodeEntity(suggestion);
}
function decodeEntity(inputStr) {
var textarea = document.createElement("textarea");
textarea.innerHTML = inputStr;
return textarea.value;
}
async function getQuery(){
return Promise.all([promptUserForSearchTerms()]).then(
([searchTerms]) =>
new Promise((resolve, reject) => {
if (!searchTerms) {
notice("No query entered.");
reject(new Error("No query entered."));
}
resolve({ searchTerms });
})
);
}
function promptUserForSearchTerms(){
return QuickAdd.quickAddApi.inputPrompt("Bionomia search terms:");
}
function promptUserForSelectingSuggestions(suggestions) {
return new Promise((resolve, reject) => {
QuickAdd.quickAddApi
.suggester(suggestions.map(formatTitleForSuggestionList), suggestions)
.then(async (selectedProfile) => {
if (!selectedProfile) {
notice("No choice selected.");
reject(new Error("No choice selected."));
}
resolve(selectedProfile);
});
});
}
function cleanLifeSpan(str){
var clean = [];
var entityPatt = /^\&.*?$/;
if (str != null){
str.split(' ').forEach(function stripEntities(s){
if (entityPatt.test(s)){
if (s == '–'){
clean.push('-');
}
}
else{
clean.push(s);
}
});
}
return clean.join(' ');
}
/**
*
* @param {object} profile The profile data from searching Bionomia
* @returns {Profile}
*/
function buildProfileData(profile) {
return profile;
}
/**
*
* @param {object} queryParams
* @throws Will throw Error if no profiles are found
* @returns {Profile[]} The results from searching Bionomia for matching profiles
*/
async function getProfilesByQueryParams(queryParams) {
const searchResults = await fetchProfiles(
API_SEARCH_URL,
queryParams
);
console.log(searchResults);
if (!searchResults || !searchResults.length) {
notice("No results found.");
throw new Error("No results found.");
}
return searchResults.map(buildProfileData);
}
function buildQueryString(queryParam){
return queryParam;
}
/**
*
* @param {string} url
* @param {object} queryParams
* @returns {object[]}
*/
async function fetchProfiles(url, queryParam) {
let finalURL = new URL(url);
if (queryParam) {
finalURL.searchParams.append("q", buildQueryString(queryParam));
}
console.log(finalURL);
return JSON.parse(
await request({
url: finalURL.href,
method: "GET",
cache: "no-cache",
headers: {
"Content-Type": "application/json",
"User-Agent": "ObsidianQuickAddMacro ( [email protected] )",
},
})
);
}
///////////////////////////////////////////////////////////////////////////////
// Functions to test query format
///////////////////////////////////////////////////////////////////////////////
function isORCID(str) {
return /^\d{4}\-\d{4}\-\d{4}\-\d{4}$/.test(str);
}
function isWikidataQid(str) {
return /^Q\d+$/.test(str);
}