Skip to content

Instantly share code, notes, and snippets.

@masakichi
Last active January 22, 2024 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masakichi/577f539b601434c61d3845a4ff2f87fd to your computer and use it in GitHub Desktop.
Save masakichi/577f539b601434c61d3845a4ff2f87fd to your computer and use it in GitHub Desktop.
const vault = "knowledge";
const folder = "references/kindle";
function generateQuoteCallout({ highlight, note, location }) {
const asin = document.querySelector(
"input#kp-notebook-annotations-asin",
)?.value;
let quote = `> [!quote]
> ${highlight}`;
if (asin) {
quote = `${quote} — location: [${location}](kindle://book?action=open&asin=${asin}&location=${location})`;
}
if (note) {
quote = `${quote}
${note}
`;
}
return quote;
}
const parseAnnotedDate = (dateStringJP) => {
const match = dateStringJP.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
if (!match) return "";
const year = match[1];
const month = match[2].padStart(2, "0");
const day = match[3].padStart(2, "0");
// Format the result as 'YYYY-MM-DD'
return `${year}-${month}-${day}`;
};
const parseBook = () => {
return {
title: document.querySelector("h3.kp-notebook-metadata")?.innerText,
author: document.querySelector(
"p.a-color-secondary.kp-notebook-selectable.kp-notebook-metadata",
)?.innerText,
cover: document.querySelector(
"#annotation-section img.kp-notebook-cover-image-border",
)?.src,
url: document.querySelector(
"a.a-link-normal.kp-notebook-printable.a-text-normal",
)?.href,
annotatedDate: parseAnnotedDate(
document.querySelector("span#kp-notebook-annotated-date")?.innerText,
),
};
};
const parseAnnotations = () => {
const annotations = [];
for (const annotationDom of document.querySelectorAll(
".a-row.a-spacing-base",
)) {
const highlight = annotationDom.querySelector("#highlight");
const note = annotationDom.querySelector("#note");
const location = annotationDom.querySelector("#kp-annotation-location");
if (!highlight) continue;
annotations.push({
highlight: highlight.innerText,
note: note.innerText,
location: location?.value,
});
}
return annotations;
};
const generateMarkdown = (book, annotations) => {
let markdown = `---
title: "${book.title}"
author: "${book.author}"
cover: ${book.cover}
source: ${book.url}
annotatedDate: ${book.annotatedDate}
---
## Highlights
${annotations.map((anno) => generateQuoteCallout(anno)).join("\n\n---\n\n")}
`;
return markdown;
};
const book = parseBook();
const annotations = parseAnnotations();
const md = generateMarkdown(book, annotations);
const filename = book.title.replace(/[/\\?%*:|"<>]/g, "-");
navigator.clipboard.writeText(md);
document.location.href =
"obsidian://advanced-uri?" +
"vault=" +
vault +
"&clipboard=true" +
"&mode=overwrite" +
"&filepath=" +
encodeURIComponent(`${folder}/${filename}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment