Skip to content

Instantly share code, notes, and snippets.

@evantravers
Created April 25, 2022 18:25
Show Gist options
  • Save evantravers/417f8da01f96d62a8d367b19f6786b00 to your computer and use it in GitHub Desktop.
Save evantravers/417f8da01f96d62a8d367b19f6786b00 to your computer and use it in GitHub Desktop.
var Booknotes = {};
Booknotes.__mlaAuthors = function(authors) {
if (authors) {
switch (authors.length) {
case 1: return authors[0]; break;
case 2: return authors.join(", "); break;
case 3: return authors[0] + " et al."; break;
}
} else {
return "";
}
}
Booknotes.title = function(data) {
return `${data.title} by ${Booknotes.__mlaAuthors(data.authors)}`
}
// Takes a string, returns the year
Booknotes.__mlaDate = function(d) {
let date = new Date(d);
return date.getFullYear();
}
Booknotes.mla = function(data, link = false) {
let title = `_${data.title}_`;
if (link) {
title = `_[[${link}|${data.title}]]_`;
}
let publishedDate = 'Unknown Year';
if (data.year) {
publishedDate = data.year;
}
if (data.publishedDate) {
publishedDate = Booknotes.__mlaDate(data.publishedDate)
}
return `${Booknotes.__mlaAuthors(data.authors)}. ${title}. ${data.publisher}, ${publishedDate}.`
}
Booknotes.searchGoogleBooks = function(query) {
var url = "https://www.googleapis.com/books/v1/volumes?q=" + encodeURIComponent(query);
var http = HTTP.create(); //create HTTP object
var response = http.request({
"url": url,
"method": "GET"
});
if (response.success) {
var jsonObj = JSON.parse(response.responseText);
return jsonObj.items;
} else {
return null;
}
}
Booknotes.findBooks = function(reference) {
let items = Booknotes.searchGoogleBooks(reference);
if (items) {
if (items.length > 5) {
return items.slice(0, 5);
}
else {
return items
}
}
}
Booknotes.selectBook = function(str = null) {
let googleBooks = Prompt.create();
googleBooks.addLabel("title", "Search Google Books...");
googleBooks.addTextField("q", "🔎 ", "")
googleBooks.addButton("Confirm", 1, true);
googleBooks.show();
if (googleBooks.buttonPressed == 1) {
let search = Booknotes.findBooks(googleBooks.fieldValues["q"]);
let bookTitles = search.map((b) => Booknotes.mla(b.volumeInfo));
let bookSelect = Prompt.create();
bookSelect.addLabel("title", "Choose a match:");
bookSelect.addSelect(
"selectBook",
"Book:",
bookTitles,
[],
false);
bookSelect.addButton("Select Book", 1, true);
bookSelect.show();
if (bookSelect.buttonPressed == 1) {
let book =
search.find(b =>
Booknotes.mla(b.volumeInfo) == bookSelect.fieldValues["selectBook"]).volumeInfo;
if (book.industryIdentifiers) {
book.identifier = book.industryIdentifiers[0].identifier;
}
console.log(JSON.stringify(book));
return book;
}
else {
return false;
}
}
}
const yaml = {
extract: function(d = draft) {
if (d.lines[0] == "---") {
let start = 1;
let end = d.lines.indexOf("---", start)
return d.lines.slice(start, end).join("\n")
}
},
content: function(d = draft) {
return d.content.replace(`---\n${yaml.extract(d)}\n---\n\n`, "");
},
loadFrontmatter: function(d = Draft) {
return yaml.load(yaml.extract(d))
},
dumpFrontmatter: function(meta) {
if (yaml.dump(meta).length == 0) {
return '';
} else {
return `---\n${yaml.dump(meta)}\n---\n\n`;
}
},
load: function(str) {
return parser.parse(str)
},
q: function(str) {
if (str == null) { return "" }
if (str.match(/[':#]/)) {
return `"${str}"`;
}
if (str.match(/"/)) {
return `'${str}'`;
}
return str;
},
dump: function(obj) {
// for key in obj
let y = "";
for (key in obj) {
y += `${key}: `
if (Array.isArray(obj[key])) {
y += `\n${obj[key].map(v => "- " + yaml.q(v)).join("\n")}`
} else {
y += `${yaml.q(obj[key])}`;
}
y += "\n";
}
return y.trim();
}
};
// private ==========
const parser = {
parse: function(str) {
if (!str) {
return {};
}
let json =
str.split("\n").reduce(function(binding, line) {
line = line.trimEnd();
// start of a list
if (line.match(/^\w*:$/)) {
let token = line.match(/(\w.*):/)[1];
binding[token] = []
binding.tmpVar = token;
}
// start of a list item
else if (line.match(/^- .*$/)) {
let val = line.match(/^- (.*)$/)[1];
binding[binding.tmpVar].push(val)
}
// start an assignment
else if (line.match(/^\w.+: ?.*$/)) {
let token = line.match(/^(\w.+): ?.*$/)[1]
let val = line.match(/^\w.+: ?(.*)$/)[1]
binding[token] = val;
}
else {
console.error("Couln't match " + line);
}
return binding;
}, {});
// cleanup
delete json.tmpVar;
return json;
}
};
let book = Booknotes.selectBook();
if (book) {
let d = Draft.create();
let meta = {};
meta.started = strftime(Date.now(), "%F");
meta.title = book.title
meta.subtitle = book.subtitle
meta.authors = book.authors
meta.publisher = book.publisher
meta.year = strftime(new Date(book.publishedDate), "%Y")
meta.identifier = book.identifier
meta.started = strftime(new Date(), "%B %d, %Y")
meta.completed = "N/A"
d.content = `---\n${yaml.dump(meta)}\n---\n\n# ${Booknotes.title(meta)}`;
d.addTag("booknote")
d.update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment