Skip to content

Commit

Permalink
refactor: parse frontmatter
Browse files Browse the repository at this point in the history
  • Loading branch information
anpigon committed Aug 17, 2022
1 parent e391d7b commit a2bd894
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 44 deletions.
49 changes: 29 additions & 20 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { CursorJumper } from '@utils/cursor_jumper';
import { Book } from '@models/book.model';
import { BookSearchSettingTab, BookSearchPluginSettings, DEFAULT_SETTINGS } from '@settings/settings';
import { getTemplateContents, applyTemplateTransformations } from '@utils/template';
import { replaceVariableSyntax, makeFileName, applyDefaultFrontMatter } from '@utils/utils';
import { replaceVariableSyntax, makeFileName, applyDefaultFrontMatter, toStringFrontMatter } from '@utils/utils';

type MetadataWriter = (book: Book, metadata: string) => Promise<void>;

Expand Down Expand Up @@ -44,25 +44,7 @@ export default class BookSearchPlugin extends Plugin {
// open modal for book search
const searchedBooks = await this.openBookSearchModal(query);
const selectedBook = await this.openBookSuggestModal(searchedBooks);

let renderedContents = '';
const templateFile = this.settings.templateFile?.trim();
if (templateFile) {
const templateContents = await getTemplateContents(this.app, templateFile);
renderedContents = applyTemplateTransformations(templateContents);
renderedContents = replaceVariableSyntax(selectedBook, renderedContents);
} else {
// @deprecated
let frontmatter = this.settings.frontmatter
? replaceVariableSyntax(selectedBook, this.settings.frontmatter)
: '';
if (this.settings.useDefaultFrontmatter) {
frontmatter = applyDefaultFrontMatter(selectedBook, frontmatter, this.settings.defaultFrontmatterKeyType);
}
const content = this.settings.content ? replaceVariableSyntax(selectedBook, this.settings.content) : '';
renderedContents = frontmatter ? `---\n${frontmatter}\n---\n${content}` : content;
}

const renderedContents = await this.getRenderedContents(selectedBook);
await callback(selectedBook, renderedContents);

// cursor focus
Expand All @@ -77,6 +59,33 @@ export default class BookSearchPlugin extends Plugin {
}
}

async getRenderedContents(book: Book) {
const {
templateFile,
useDefaultFrontmatter,
defaultFrontmatterKeyType,
frontmatter, // @deprecated
content, // @deprecated
} = this.settings;

if (templateFile) {
const templateContents = await getTemplateContents(this.app, templateFile);
return replaceVariableSyntax(book, applyTemplateTransformations(templateContents));
}

let replacedVariableFrontmatter = replaceVariableSyntax(book, frontmatter); // @deprecated
if (useDefaultFrontmatter) {
replacedVariableFrontmatter = toStringFrontMatter(
applyDefaultFrontMatter(book, replacedVariableFrontmatter, defaultFrontmatterKeyType),
);
}
const replacedVariableContent = replaceVariableSyntax(book, content);

return replacedVariableFrontmatter
? `---\n${replacedVariableFrontmatter}\n---\n${replacedVariableContent}`
: replacedVariableContent;
}

async insertMetadata(): Promise<void> {
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!markdownView) {
Expand Down
58 changes: 34 additions & 24 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,38 +24,38 @@ export function makeFileName(book: Book, fileNameFormat?: string) {
return replaceIllegalFileNameCharactersInString(result);
}

export function changeSnakeCase(book: Book) {
return Object.entries(book).reduce((acc, [key, value]) => {
acc[camelToSnakeCase(key)] = value;
return acc;
}, {});
}

export function applyDefaultFrontMatter(
book: Book,
frontmatter: FrontMatter | string,
keyType: DefaultFrontmatterKeyType = DefaultFrontmatterKeyType.snakeCase,
): string {
const frontMater =
keyType === DefaultFrontmatterKeyType.camelCase
? book
: Object.entries(book).reduce((acc, [key, value]) => {
acc[camelToSnakeCase(key)] = value;
return acc;
}, {});

const addFrontMatter = typeof frontmatter === 'string' ? parseFrontMatter(frontmatter) : frontmatter;
for (const key in addFrontMatter) {
const addValue = addFrontMatter[key]?.toString().trim() ?? '';
if (frontMater[key] && frontMater[key] !== addValue) {
frontMater[key] = `${frontMater[key]} ${addValue}`;
) {
const frontMater = keyType === DefaultFrontmatterKeyType.camelCase ? book : changeSnakeCase(book);

const extraFrontMatter = typeof frontmatter === 'string' ? parseFrontMatter(frontmatter) : frontmatter;
for (const key in extraFrontMatter) {
const value = extraFrontMatter[key]?.toString().trim() ?? '';
if (frontMater[key] && frontMater[key] !== value) {
frontMater[key] = `${frontMater[key]}, ${value}`;
} else {
frontMater[key] = addValue;
frontMater[key] = value;
}
}

return Object.entries(frontMater)
.map(([key, val]) => {
return `${key}: ${val?.toString().trim() ?? ''}`;
})
.join('\n')
.trim();
return frontMater as object;
}

export function replaceVariableSyntax(book: Book, targetText: string): string {
if (!targetText?.trim()) {
return '';
}

const entries = Object.entries(book);
return entries
.reduce((text, [key, val = '']) => text.replace(new RegExp(`{{${key}}}`, 'ig'), val), targetText)
Expand Down Expand Up @@ -87,10 +87,20 @@ export function parseFrontMatter(frontMatterString: string) {
}, {});
}

export function toStringFrontMatter(frontMatter: FrontMatter): string {
export function toStringFrontMatter(frontMatter: object): string {
return Object.entries(frontMatter)
.map(([key, value]) => `${key}: ${value ?? ''}`)
.join('\n');
.map(([key, value]) => {
const newValue = value?.toString().trim() ?? '';
if (/\r|\n/.test(newValue)) {
return '';
}
if (/:\s/.test(newValue)) {
return `${key}: "${newValue.replace(/"/g, '&quot;')}"\n`;
}
return `${key}: ${newValue}\n`;
})
.join('')
.trim();
}

export function getDate(input?: { format?: string; offset?: number }) {
Expand Down

0 comments on commit a2bd894

Please sign in to comment.