XeNote/lib/transformer.js

189 lines
6.5 KiB
JavaScript
Raw Normal View History

// import matter from 'gray-matter'
import { unified } from 'unified'
import markdown from 'remark-parse'
import { wikiLinkPlugin } from 'remark-wiki-link'
import html from 'remark-html'
// import frontmatter from "remark-frontmatter";
import externalLinks from 'remark-external-links'
import highlight from 'remark-highlight.js'
import { Node } from './node'
import rehypePrism from 'rehype-prism-plus'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
2022-04-28 09:44:59 +00:00
import obsidianImage from './obsidian-image.js'
import Utils from '../lib/utils.js'
export class Transformer {
2023-12-26 03:40:06 +00:00
static haveFrontMatter = (content) => {
// console.log("\t Front matter data content", content)
if (content === (null | undefined | '')) return false
const indexOfFirst = content.indexOf('---')
// console.log("\t Front matter data firstIndex ", indexOfFirst)
// console.log("index first", indexOfFirst)
if (indexOfFirst === -1) {
return false
}
const indexOfSecond = content.indexOf('---', (indexOfFirst + 1))
return indexOfSecond !== -1
}
2023-12-26 03:40:06 +00:00
static getFrontMatterData = (filecontent) => {
// if (Transformer.haveFrontMatter(filecontent)) {
2023-12-26 04:38:56 +00:00
// return matter(filecontent).data
// }
return {}
}
2020-11-30 11:29:34 +00:00
2023-12-26 03:40:06 +00:00
static pageResolver = (pageName) => {
const allFileNames = Utils.getAllMarkdownFiles()
const result = allFileNames.find(aFile => {
const parseFileNameFromPath = Transformer.parseFileNameFromPath(aFile)
2023-12-26 03:40:06 +00:00
return Transformer.normalizeFileName(parseFileNameFromPath) === Transformer.normalizeFileName(pageName)
}
)
// permalink = permalink.replace("ç", "c").replace("ı", "i").replace("ş", "s")
// console.log(`/note/${toSlug(result)}`)
if (result === undefined || result.length === 0) {
// console.log("Cannot resolve file path " + pageName)
}
// console.log("Internal Link resolved: [" + pageName + "] ==> [" + temp[0] +"]")
return (result !== undefined && result.length > 0) ? [Utils.toSlug(result)] : ['/']
}
2023-12-26 03:40:06 +00:00
static hrefTemplate = (permalink) => {
// permalink = Transformer.normalizeFileName(permalink)
permalink = permalink.replace('ç', 'c').replace('ı', 'i').replace('ş', 's')
2023-12-31 17:56:14 +00:00
return `/notes/${permalink}`
}
2023-12-26 03:40:06 +00:00
static getHtmlContent = (content) => {
let htmlContent = []
2023-12-26 03:40:06 +00:00
const sanitizedContent = Transformer.preprocessThreeDashes(content)
unified()
.use(markdown, { gfm: true })
.use(obsidianImage)
.use(highlight)
.use(externalLinks, { target: '_blank', rel: ['noopener'] })
// .use(frontmatter, ['yaml', 'toml'])
.use(wikiLinkPlugin, {
permalinks: null,
pageResolver: (pageName) => {
2023-12-26 03:40:06 +00:00
return Transformer.pageResolver(pageName)
},
hrefTemplate: (permalink) => {
return Transformer.hrefTemplate(permalink)
},
aliasDivider: '|'
})
.use(remarkRehype)
.use(rehypePrism)
.use(rehypeStringify)
.process(sanitizedContent,
function(err, file) {
htmlContent.push(String(file).replace('\n', ''))
if (err !== (null | undefined)) {
console.log('ERRROR:' + err)
}
2020-11-30 11:29:34 +00:00
}
)
htmlContent = htmlContent.join('')
htmlContent = htmlContent.split('---')
return [htmlContent]
}
/* SANITIZE MARKDOWN FOR --- */
2023-12-26 03:40:06 +00:00
static preprocessThreeDashes = (content) => {
const indexOfFirst = content.indexOf('---')
if (indexOfFirst === -1) {
return content
}
const indexOfSecond = content.indexOf('---', (indexOfFirst + 1))
content.slice(0, indexOfSecond)
const contentPart = content.slice(indexOfSecond)
return contentPart.split('---').join('')
}
/* Normalize File Names */
2023-12-26 03:40:06 +00:00
static normalizeFileName = (filename) => {
let processedFileName = filename.replace('.md', '')
processedFileName = processedFileName.replace('(', '').replace(')', '')
processedFileName = processedFileName.split(' ').join('-')
processedFileName = processedFileName.toLowerCase()
const conversionLetters = [
['ç', 'c'], ['ş', 's'], ['ı', 'i'], ['ü', 'u'], ['ö', 'o'], ['ğ', 'g'],
['Ç', 'C'], ['Ş', 'S'], ['İ', 'I'], ['Ü', 'U'], ['Ö', 'O'], ['Ğ', 'G']
]
conversionLetters.forEach(letterPair => {
processedFileName = processedFileName.split(letterPair[0]).join(letterPair[1])
// processedFileName = processedFileName.replace(letterPair[0], letterPair[1])
}
)
// console.log("filename", processedFileName)
return processedFileName
}
/* Parse file name from path then sanitize it */
2023-12-26 03:40:06 +00:00
static parseFileNameFromPath = (filepath) => {
if (typeof filepath === 'string' && filepath.includes('/')) {
const parsedFileFromPath = filepath.split('/')[filepath.split('/').length - 1]
return parsedFileFromPath.replace('.md', '')
} else {
console.log('Failed: CANNOT Parse' + filepath)
return null
}
}
/* Pair provided and existing Filenames */
2023-12-26 03:40:06 +00:00
static getInternalLinks = (aFilePath) => {
const fileContent = Node.readFileSync(aFilePath)
const internalLinks = []
2023-12-26 03:40:06 +00:00
const sanitizedContent = Transformer.preprocessThreeDashes(fileContent)
unified()
.use(markdown, { gfm: true })
.use(wikiLinkPlugin, {
pageResolver: function(pageName) {
2023-12-26 03:40:06 +00:00
// let name = [Transformer.parseFileNameFromPath(pageName)];
let canonicalSlug
if (pageName.includes('#') !== (false, null, undefined)) {
// console.log(pageName)
const tempSlug = pageName.split('#')[0]
if (tempSlug.length === 0) {
// Meaning it in form of #Heading1 --> slug will be this file slug
canonicalSlug = Utils.toSlug(aFilePath)
} else {
2023-12-26 03:40:06 +00:00
canonicalSlug = Transformer.pageResolver(tempSlug)[0].split('#')[0]
2020-11-30 11:29:34 +00:00
}
} else {
2023-12-26 03:40:06 +00:00
canonicalSlug = Transformer.pageResolver(pageName)[0].split('#')[0]
}
const backLink = {
title: Transformer.parseFileNameFromPath(Utils.toFilePath(canonicalSlug)),
slug: canonicalSlug,
shortSummary: canonicalSlug
}
if (canonicalSlug != null && !internalLinks.includes(canonicalSlug)) {
internalLinks.push(backLink)
}
return [canonicalSlug]
},
hrefTemplate: (permalink) => {
2023-12-26 03:40:06 +00:00
return Transformer.hrefTemplate(permalink)
},
aliasDivider: '|'
})
.use(html)
.processSync(sanitizedContent)
return internalLinks
}
2020-11-30 11:29:34 +00:00
}