convert transformer to a class

NOTE - all of these methods can be static i believe. no need to use this and instantiate new instances every time.. i dont think atm anyway
This commit is contained in:
Triston Armstrong 2023-12-25 20:48:51 -06:00
parent 1adbbe2f54
commit f56e07b94e
2 changed files with 54 additions and 44 deletions

View File

@ -13,8 +13,11 @@ import rehypeStringify from 'rehype-stringify'
import obsidianImage from './obsidian-image.js' import obsidianImage from './obsidian-image.js'
import { getAllMarkdownFiles, toFilePath, toSlug } from "./utils"; import { getAllMarkdownFiles, toFilePath, toSlug } from "./utils";
export const Transformer = {
haveFrontMatter: function(content) { export class Transformer {
constructor() { }
haveFrontMatter = (content) => {
//console.log("\t Front matter data content", content) //console.log("\t Front matter data content", content)
if (!content) return false if (!content) return false
const indexOfFirst = content.indexOf("---"); const indexOfFirst = content.indexOf("---");
@ -25,21 +28,21 @@ export const Transformer = {
} }
let indexOfSecond = content.indexOf("---", (indexOfFirst + 1)); let indexOfSecond = content.indexOf("---", (indexOfFirst + 1));
return indexOfSecond !== -1; return indexOfSecond !== -1;
}
}, getFrontMatterData = (filecontent) => {
getFrontMatterData: function(filecontent) { if (this.haveFrontMatter(filecontent)) {
if (Transformer.haveFrontMatter(filecontent)) {
return matter(filecontent).data return matter(filecontent).data
} }
return {} return {}
}, }
pageResolver: function(pageName) { pageResolver = (pageName) => {
const allFileNames = getAllMarkdownFiles() const allFileNames = getAllMarkdownFiles()
const result = allFileNames.find(aFile => { const result = allFileNames.find(aFile => {
let parseFileNameFromPath = Transformer.parseFileNameFromPath(aFile); let parseFileNameFromPath = this.parseFileNameFromPath(aFile);
return Transformer.normalizeFileName(parseFileNameFromPath) === Transformer.normalizeFileName(pageName) return this.normalizeFileName(parseFileNameFromPath) === this.normalizeFileName(pageName)
} }
) )
@ -51,14 +54,17 @@ export const Transformer = {
// console.log("Internal Link resolved: [" + pageName + "] ==> [" + temp[0] +"]") // console.log("Internal Link resolved: [" + pageName + "] ==> [" + temp[0] +"]")
return (result !== undefined && result.length > 0) ? [toSlug(result)] : ["/"] return (result !== undefined && result.length > 0) ? [toSlug(result)] : ["/"]
}, }
hrefTemplate: function(permalink) {
// permalink = Transformer.normalizeFileName(permalink) hrefTemplate = (permalink) => {
// permalink = this.normalizeFileName(permalink)
permalink = permalink.replace("ç", "c").replace("ı", "i").replace("ş", "s") permalink = permalink.replace("ç", "c").replace("ı", "i").replace("ş", "s")
return `/note/${permalink}`; return `/note/${permalink}`
}, getHtmlContent: function(content) { }
getHtmlContent = (content) => {
let htmlContent = [] let htmlContent = []
const sanitizedContent = Transformer.preprocessThreeDashes(content) const sanitizedContent = this.preprocessThreeDashes(content)
unified() unified()
.use(markdown, { gfm: true }) .use(markdown, { gfm: true })
@ -68,11 +74,11 @@ export const Transformer = {
// .use(frontmatter, ['yaml', 'toml']) // .use(frontmatter, ['yaml', 'toml'])
.use(wikiLinkPlugin, { .use(wikiLinkPlugin, {
permalinks: null, permalinks: null,
pageResolver: function(pageName) { pageResolver: (pageName) => {
return Transformer.pageResolver(pageName) return this.pageResolver(pageName)
}, },
hrefTemplate: function(permalink) { hrefTemplate: (permalink) => {
return Transformer.hrefTemplate(permalink); return this.hrefTemplate(permalink);
}, },
aliasDivider: "|" aliasDivider: "|"
@ -91,10 +97,10 @@ export const Transformer = {
htmlContent = htmlContent.join("") htmlContent = htmlContent.join("")
htmlContent = htmlContent.split("---") htmlContent = htmlContent.split("---")
return [htmlContent] return [htmlContent]
}, }
/* SANITIZE MARKDOWN FOR --- */ /* SANITIZE MARKDOWN FOR --- */
preprocessThreeDashes: function(content) { preprocessThreeDashes = (content) => {
const indexOfFirst = content.indexOf("---"); const indexOfFirst = content.indexOf("---");
if (indexOfFirst === -1) { if (indexOfFirst === -1) {
return content return content
@ -103,10 +109,10 @@ export const Transformer = {
content.slice(0, indexOfSecond); content.slice(0, indexOfSecond);
const contentPart = content.slice(indexOfSecond); const contentPart = content.slice(indexOfSecond);
return contentPart.split("---").join("") return contentPart.split("---").join("")
}, }
/* Normalize File Names */ /* Normalize File Names */
normalizeFileName: function(filename) { normalizeFileName = (filename) => {
let processedFileName = filename.replace(".md", ""); let processedFileName = filename.replace(".md", "");
processedFileName = processedFileName.replace('(', '').replace(')', '') processedFileName = processedFileName.replace('(', '').replace(')', '')
processedFileName = processedFileName.split(" ").join("-") processedFileName = processedFileName.split(" ").join("-")
@ -123,9 +129,10 @@ export const Transformer = {
) )
//console.log("filename", processedFileName) //console.log("filename", processedFileName)
return processedFileName return processedFileName
}, }
/* Parse file name from path then sanitize it */ /* Parse file name from path then sanitize it */
parseFileNameFromPath: function(filepath) { parseFileNameFromPath = (filepath) => {
if (typeof filepath === 'string' && filepath.includes("/")) { if (typeof filepath === 'string' && filepath.includes("/")) {
const parsedFileFromPath = filepath.split("/")[filepath.split("/").length - 1] const parsedFileFromPath = filepath.split("/")[filepath.split("/").length - 1]
return parsedFileFromPath.replace(".md", "") return parsedFileFromPath.replace(".md", "")
@ -133,18 +140,20 @@ export const Transformer = {
console.log("Failed: CANNOT Parse" + filepath) console.log("Failed: CANNOT Parse" + filepath)
return null return null
} }
}, }
/* Pair provided and existing Filenames*/ /* Pair provided and existing Filenames*/
getInternalLinks: function(aFilePath) { getInternalLinks = (aFilePath) => {
const fileContent = Node.readFileSync(aFilePath); const fileContent = Node.readFileSync(aFilePath);
const internalLinks = [] const internalLinks = []
const sanitizedContent = Transformer.preprocessThreeDashes(fileContent) const sanitizedContent = this.preprocessThreeDashes(fileContent)
const outer_this = this
unified() unified()
.use(markdown, { gfm: true }) .use(markdown, { gfm: true })
.use(wikiLinkPlugin, { .use(wikiLinkPlugin, {
pageResolver: function(pageName) { pageResolver: function(pageName) {
// let name = [Transformer.parseFileNameFromPath(pageName)]; // let name = [this.parseFileNameFromPath(pageName)];
let canonicalSlug; let canonicalSlug;
if (pageName.includes('#')) { if (pageName.includes('#')) {
@ -154,15 +163,14 @@ export const Transformer = {
// Meaning it in form of #Heading1 --> slug will be this file slug // Meaning it in form of #Heading1 --> slug will be this file slug
canonicalSlug = toSlug(aFilePath) canonicalSlug = toSlug(aFilePath)
} else { } else {
canonicalSlug = Transformer.pageResolver(tempSlug)[0].split('#')[0] canonicalSlug = outer_this.pageResolver(tempSlug)[0].split('#')[0]
} }
} else { } else {
canonicalSlug = Transformer.pageResolver(pageName)[0].split('#')[0] canonicalSlug = outer_this.pageResolver(pageName)[0].split('#')[0]
} }
const backLink = { const backLink = {
title: Transformer.parseFileNameFromPath(toFilePath(canonicalSlug)), title: outer_this.parseFileNameFromPath(toFilePath(canonicalSlug)),
slug: canonicalSlug, slug: canonicalSlug,
shortSummary: canonicalSlug shortSummary: canonicalSlug
} }
@ -174,8 +182,8 @@ export const Transformer = {
return [canonicalSlug] return [canonicalSlug]
} }
, ,
hrefTemplate: function(permalink) { hrefTemplate: (permalink) => {
return Transformer.hrefTemplate(permalink) return this.hrefTemplate(permalink)
}, },
aliasDivider: "|" aliasDivider: "|"

View File

@ -34,6 +34,7 @@ export function getAllMarkdownFiles() {
export function getSinglePost(slug) { export function getSinglePost(slug) {
const t = new Transformer()
// List of filenames that will provide existing links to wikilink // List of filenames that will provide existing links to wikilink
let currentFilePath = toFilePath(slug) let currentFilePath = toFilePath(slug)
@ -41,9 +42,9 @@ export function getSinglePost(slug) {
var fileContent = Node.readFileSync(currentFilePath) var fileContent = Node.readFileSync(currentFilePath)
//const currentFileFrontMatter = Transformer.getFrontMatterData(fileContent) //const currentFileFrontMatter = t.getFrontMatterData(fileContent)
// console.log("===============\n\nFile is scanning: ", slug) // console.log("===============\n\nFile is scanning: ", slug)
const [htmlContent] = Transformer.getHtmlContent(fileContent) const [htmlContent] = t.getHtmlContent(fileContent)
// console.log("==================================") // console.log("==================================")
//console.log("hrmlcontents and backlinks") //console.log("hrmlcontents and backlinks")
return { return {
@ -108,7 +109,7 @@ export function toSlug(filePath) {
export function constructGraphData() { export function constructGraphData() {
const t = new Transformer()
const filepath = path.join(process.cwd(), "graph-data.json"); const filepath = path.join(process.cwd(), "graph-data.json");
if (Node.isFile(filepath)) { if (Node.isFile(filepath)) {
const data = fs.readFileSync(filepath); const data = fs.readFileSync(filepath);
@ -121,14 +122,14 @@ export function constructGraphData() {
.forEach(aFilePath => { .forEach(aFilePath => {
// const {currentFilePath} = getFileNames(filename) // const {currentFilePath} = getFileNames(filename)
const aNode = { const aNode = {
title: Transformer.parseFileNameFromPath(aFilePath), title: t.parseFileNameFromPath(aFilePath),
slug: toSlug(aFilePath), slug: toSlug(aFilePath),
shortSummary: getShortSummary(toSlug(aFilePath)) shortSummary: getShortSummary(toSlug(aFilePath))
} }
nodes.push(aNode) nodes.push(aNode)
// console.log("Constructing graph for node: " + aFilePath ) // console.log("Constructing graph for node: " + aFilePath )
const internalLinks = Transformer.getInternalLinks(aFilePath) const internalLinks = t.getInternalLinks(aFilePath)
internalLinks.forEach(aLink => { internalLinks.forEach(aLink => {
if (aLink.slug === null || aLink.slug.length === 0) return if (aLink.slug === null || aLink.slug.length === 0) return
@ -152,14 +153,14 @@ export function constructGraphData() {
export function getLocalGraphData(currentNodeId) { export function getLocalGraphData(currentNodeId) {
const t = new Transformer()
const { nodes, edges } = constructGraphData() const { nodes, edges } = constructGraphData()
const newNodes = nodes.map(aNode => ( const newNodes = nodes.map(aNode => (
{ {
data: { data: {
id: aNode.slug.toString(), id: aNode.slug.toString(),
label: Transformer.parseFileNameFromPath(toFilePath(aNode.slug)), label: t.parseFileNameFromPath(toFilePath(aNode.slug)),
} }
} }
)) ))
@ -233,11 +234,12 @@ export function getDirectoryData() {
let _counter = 0; let _counter = 0;
export function convertObject(thisObject) { export function convertObject(thisObject) {
const t = new Transformer()
const children = [] const children = []
let routerPath = getAllSlugs().find(slug => { let routerPath = getAllSlugs().find(slug => {
const fileName = Transformer.parseFileNameFromPath(toFilePath(slug)) const fileName = t.parseFileNameFromPath(toFilePath(slug))
return Transformer.normalizeFileName(fileName) === Transformer.normalizeFileName(thisObject.name) return t.normalizeFileName(fileName) === t.normalizeFileName(thisObject.name)
}) || null }) || null
routerPath = routerPath ? '/note/' + routerPath : null routerPath = routerPath ? '/note/' + routerPath : null
const newObject = { const newObject = {