Skip to content

Commit

Permalink
Merge pull request #2 from LuloDev/feat/templating
Browse files Browse the repository at this point in the history
Feat/templating
  • Loading branch information
LuloDev authored May 21, 2024
2 parents b058493 + 2b8e2f5 commit c3d1219
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 130 deletions.
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,72 @@ The plugin will fetch the book data and insert it into the current block.
| ISBN | The ISBN of the book. |
| Maturity Rating | The Maturity Rating of the book. |

## Template Configuration

The template is used to format the fetched book data that is inserted into the current block in Logseq. You can customize the template to fit your needs.

The template is a string that contains various keys enclosed in double curly braces (`{{key}}`). Each key is replaced by the corresponding value from the book data. The available keys are:

- `thumbnail`: The URL of the book's thumbnail image.
- `title`: The title of the book.
- `isbn`: The ISBN of the book.
- `authors`: The authors of the book, separated by commas.
- `publishedAt`: The publication date of the book.
- `categories`: The categories or genres of the book, separated by commas.
- `pages`: The total number of pages in the book.
- `language`: The language in which the book is written.
- `publisher`: The publisher of the book.
- `maturityRating`: The maturity rating of the book.
- `description`: A brief description of the book.

You can use `\n` to insert a line break in the template. For example, the following template:

## Examples

Here are some examples of how you can use the template configuration:

### Example 1: Simple Template

```json
{{title}} by {{authors}}
```

![Example 1](docs/images/output-1.gif)

### Example 2: Detailed Template with Line Breaks

```json
- Title: {{title}}\n- Authors: {{authors}}\n- ISBN: {{isbn}}\n- Published At: {{publishedAt}}\n- Categories: {{categories}}\n- Pages: {{pages}}\n- Language: {{language}}\n- Publisher: {{publisher}}\n- Maturity Rating: {{maturityRating}}\n- Description: {{description}}
```

![Example 2](docs/images/output-2.gif)

### Example 3: Detailed Template table row

```json
| ![Book Cover]({{thumbnail}}) | {{title}} | {{isbn}} | {{authors}} | {{publishedAt}} | {{categories}} | {{pages}} |
```

![Example 3](docs/images/output-3.gif)

<p align="right">(<a href="#readme-top">Go Top</a>)</p>

## Development

To build the project, run

```
pnpm run build
```

To start the development, run

```
pnpm run dev
```

<p align="right">(<a href="#readme-top">Go Top</a>)</p>
Expand Down Expand Up @@ -93,3 +145,7 @@ LuloDev
[stars-url]: https://github.com/LuloDev/logseq-book-fetch/stargazers
[issues-shield]: https://img.shields.io/github/issues/LuloDev/logseq-book-fetch.svg?style=for-the-badge
[issues-url]: https://github.com/LuloDev/l`ogseq-book-fetch/issues

```
```
Binary file added docs/images/output-1.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/output-2.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/output-3.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
167 changes: 112 additions & 55 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,33 @@ import '@logseq/libs';
import { settings } from './settings';
import { GoogleBookService } from './services/GoogleBookService';

function proccessTemplate(
template: string,
data: { key: string; value: string }[],
): { content: string }[] {
const blocks = template
.replace(/^[\t\s]*-[\t\s]*/, '')
.split(/\\n[\t\s]*-[\t\s]*/);
return blocks.map((block) => {
for (const item of data) {
block = block
.replaceAll(`{{${item.key}}}`, item.value)
.replace(/\\n/g, '\n');
}
return {
content: block,
};
});
}

/**
* Retrieves book data based on the provided ISBN.
* @param isbn - The ISBN of the book.
* @returns An array of strings representing the book data.
*/
async function getDataBook(isbn: string): Promise<[string, string[]]> {
async function getDataBook(
isbn: string,
): Promise<[string, { key: string; value: string }[]]> {
const bookService = new GoogleBookService();
const book = await bookService.getBook(isbn);

Expand All @@ -18,7 +39,7 @@ async function getDataBook(isbn: string): Promise<[string, string[]]> {
[:h1 "Book not found!"]
]
`);
return [null, []];
return null;
}

logseq.UI.showMsg(`
Expand All @@ -27,60 +48,62 @@ async function getDataBook(isbn: string): Promise<[string, string[]]> {
]
`);

const {
enableTitle,
enableThumbnail,
enableISBN,
enableAuthors,
enablePublishedAt,
enablePages,
enableLanguage,
enablePublisher,
enableCategories,
enableMaturityRating,
enableDescription,
} = logseq.settings;
const result: string[] = [];
const result: { key: string; value: string }[] = [];

if (enableThumbnail && book.thumbnailUrl) {
result.push(`![${book.title}](${book.thumbnailUrl})`);
if (book.thumbnailUrl) {
result.push({
key: 'thumbnail',
value: book.thumbnailUrl,
});
} else {
result.push(`THUMBNAIL NOT FOUND!`);
result.push({
key: 'thumbnail',
value:
'https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/No-Image-Placeholder.svg/832px-No-Image-Placeholder.svg.png',
});
}

if (enableTitle) {
result.push(`**Title:** ${book.title ?? 'N/A'}`);
}
if (enableISBN) {
result.push(`**ISBN:** ${book.isbn ?? 'N/A'}`);
}
if (enableAuthors) {
result.push(`**Authors:** ${book.authors?.join(', ') ?? 'N/A'}`);
}
if (enablePublishedAt) {
result.push(
`**Published At:** ${book.publishedAt?.toLocaleDateString() ?? 'N/A'}`,
);
}
if (enableCategories) {
result.push(`**Categories:** ${book.categories?.join(', ') ?? 'N/A'}`);
}
if (enablePages) {
result.push(`**Pages:** ${book.pages ?? 'N/A'}`);
}
if (enableLanguage) {
result.push(`**Language:** ${book.language ?? 'N/A'}`);
}
if (enablePublisher) {
result.push(`**Publisher:** ${book.publisher ?? 'N/A'}`);
}
if (enableMaturityRating) {
result.push(`**Maturity Rating:** ${book.maturityRating ?? 'N/A'}`);
}
if (enableDescription) {
result.push(`**Description:** ${book.description ?? 'N/A'}`);
}
result.push({
key: 'title',
value: book.title,
});

result.push({
key: 'isbn',
value: book.isbn ?? 'N/A',
});
result.push({
key: 'authors',
value: book.authors?.join(', ') ?? 'N/A',
});
result.push({
key: 'publishedAt',
value: book.publishedAt?.toLocaleDateString() ?? 'N/A',
});
result.push({
key: 'categories',
value: book.categories?.join(', ') ?? 'N/A',
});
result.push({
key: 'pages',
value: book.pages?.toString() ?? 'N/A',
});
result.push({
key: 'language',
value: book.language ?? 'N/A',
});
result.push({
key: 'publisher',
value: book.publisher ?? 'N/A',
});
result.push({
key: 'maturityRating',
value: book.maturityRating ?? 'N/A',
});
result.push({
key: 'description',
value: book.description ?? 'N/A',
});
return [book.title, result];
}

Expand All @@ -91,12 +114,46 @@ function main() {

if (!content) return;

const isbn = content;
const isOnlyISBN = content.match(/^\d{10,13}\s*$/);
let isbn = content;
if (!isOnlyISBN) {
isbn = content.match(/\d{10,13}(?=\s*$)/)?.[0];
if (!isbn) {
logseq.UI.showMsg(`[:h1 "No ISBN found!"]`);
return;
}
}
const [title, data] = await getDataBook(isbn);
const blocks = data.map((it) => ({ content: it }));
let { template } = logseq.settings;
if (!template || typeof template !== 'string') {
template = settings.find((setting) => setting.key === 'template').default;
}
const blocks = proccessTemplate(template as string, data);
if (blocks.length === 0) {
logseq.UI.showMsg(`
[:div.p-2
[:h1 "No template found!"]
]
`);
return;
}
if (!isOnlyISBN) {
// concat all blocks
const textContent = blocks.map((block) => block.content).join('\n');
const position = content.lastIndexOf(isbn);
if (position !== -1) {
const start = content.substring(0, position);
const end = content.substring(position + isbn.length);
const newContent = start + textContent + end;
await logseq.Editor.updateBlock(uuid, newContent);
} else {
const newContent = content + '\n' + textContent;
await logseq.Editor.updateBlock(uuid, newContent);
}
return;
}
if (!title) return;
await logseq.Editor.updateBlock(uuid, title);

await logseq.Editor.updateBlock(uuid, blocks.shift()?.content);
await logseq.Editor.insertBatchBlock(uuid, blocks, {
sibling: false,
});
Expand Down
82 changes: 7 additions & 75 deletions src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,80 +2,12 @@ import { SettingSchemaDesc } from '@logseq/libs/dist/LSPlugin.user';

export const settings: SettingSchemaDesc[] = [
{
key: 'enableTitle',
description: 'Enable this to add the title of the book',
type: 'boolean',
default: true,
title: 'Add the title of the book',
},
{
key: 'enableThumbnail',
description: 'Enable this to add the thumbnail of the book',
type: 'boolean',
default: true,
title: 'Add the thumbnail of the book',
},
{
key: 'enableISBN',
description: 'Enable this to add the ISBN of the book',
type: 'boolean',
default: true,
title: 'Add the ISBN of the book',
},
{
key: 'enableAuthors',
description: 'Enable this to add the authors of the book',
type: 'boolean',
default: true,
title: 'Add the authors of the book',
},
{
key: 'enablePublishedAt',
description: 'Enable this to add the published date of the book',
type: 'boolean',
default: true,
title: 'Add the published date of the book',
},
{
key: 'enablePages',
description: 'Enable this to add the number of pages of the book',
type: 'boolean',
default: true,
title: 'Add the number of pages of the book',
},
{
key: 'enableLanguage',
description: 'Enable this to add the language of the book',
type: 'boolean',
default: true,
title: 'Add the language of the book',
},
{
key: 'enablePublisher',
description: 'Enable this to add the publisher of the book',
type: 'boolean',
default: true,
title: 'Add the publisher of the book',
},
{
key: 'enableCategories',
description: 'Enable this to add the categories of the book',
type: 'boolean',
default: true,
title: 'Add the categories of the book',
},
{
key: 'enableMaturityRating',
description: 'Enable this to add the maturity rating of the book',
type: 'boolean',
default: true,
title: 'Add the maturity rating of the book',
},
{
key: 'enableDescription',
description: 'Enable this to add the description of the book',
type: 'boolean',
default: true,
title: 'Add the description of the book',
key: 'template',
description:
'The template to use when fetching a book. Use the following variables: title, isbn, authors, publishedAt, categories, pages, language, publisher, maturityRating, description',
type: 'string',
default:
'- Title: {{title}}\n- ISBN: {{isbn}}\n- Authors: {{authors}}\n- Published At: {{publishedAt}}\n- Categories: {{categories}}\n- Pages: {{pages}}\n- Language: {{language}}\n- Publisher: {{publisher}}\n- Maturity Rating: {{maturityRating}}\n- Description: {{description}}',
title: 'Template',
},
];

0 comments on commit c3d1219

Please sign in to comment.