Skip to content

Commit

Permalink
refactor(redac): prettify
Browse files Browse the repository at this point in the history
  • Loading branch information
wdavidw committed Jun 16, 2024
1 parent e91339d commit e740963
Show file tree
Hide file tree
Showing 12 changed files with 106 additions and 95 deletions.
4 changes: 2 additions & 2 deletions packages/redac/lib/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ export default function collection(engine, collection) {
const stack = []
const promise = new Promise((resolve, reject) => {
setImmediate(async () => {
try{
try {
let documents = (await engine.db())[collection] ?? []
for (const fn of stack) {
documents = await fn(documents)
}
resolve(documents)
}catch(error){
} catch (error) {
reject(error)
}
})
Expand Down
20 changes: 10 additions & 10 deletions packages/redac/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import sort from './utils/sort.js'
export default function engine(plugins = []) {
// Configuration normalization
if (!Array.isArray(plugins)) plugins = [plugins]
plugins = plugins.map( (plugin) => {
if (typeof plugin === 'function' ) {
plugins = plugins.map((plugin) => {
if (typeof plugin === 'function') {
return plugin()
} else if (plugin !== null && typeof plugin === 'object') {
if(typeof plugin.plugin === 'function'){
if (typeof plugin.plugin === 'function') {
return plugin.plugin.call(null, plugin.config)
} else if (plugin.plugin !== null && typeof plugin.plugin === 'object') {
return plugin.plugin
} else {
`REDAC_INVALID_ARGUMENTS: plugin config must be an object or a function, got ${JSON.stringify(
;`REDAC_INVALID_ARGUMENTS: plugin config must be an object or a function, got ${JSON.stringify(
plugin
)}.`
}
Expand All @@ -29,7 +29,7 @@ export default function engine(plugins = []) {
// Load the engine
const engine = {
plugins: plugandplay({
plugins: plugins
plugins: plugins,
}),
db: async () => {
const documents = []
Expand All @@ -41,8 +41,8 @@ export default function engine(plugins = []) {
// Default implementation
handler: ({ documents }) => {
// Use the source hook to discover and return documents
}
});
},
})
const collections = {}
// Group by collection
documents.forEach((document) => {
Expand All @@ -65,9 +65,9 @@ export default function engine(plugins = []) {
// Expose arguments to plugins authors
args: { engine },
// Default implementation
handler: ({engine}) => {
handler: ({ engine }) => {
// Use the init hook to register properties to engine
}
});
},
})
return engine
}
6 changes: 5 additions & 1 deletion packages/redac/lib/plugin-mdx/4.parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ const imageSrc = ({ document, config }) => {
}
})
await each(nodes, async (node) => {
node.url = await config.image_src.call(null, {config: config, document: document, node: node})
node.url = await config.image_src.call(null, {
config: config,
document: document,
node: node,
})
})
}
}
Expand Down
17 changes: 10 additions & 7 deletions packages/redac/lib/plugin-mdx/5.overload.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@

export default function pluginMdxOverload (plugin) {
const {documents} = plugin
export default function pluginMdxOverload(plugin) {
const { documents } = plugin
// Index absolute slug found in filenames with metadata slug
const slugs = {}
documents.forEach( document => {
slugs[(document.lang ?? '')+'/'+document.slug.join('/')] = document.data?.slug
documents.forEach((document) => {
slugs[(document.lang ?? '') + '/' + document.slug.join('/')] =
document.data?.slug
})
// Reconstruct the slug with metadata slug if present
plugin.documents = documents.map((document) => {
const newSlug = []
for (let i = 0; i < document.slug.length; i++) {
const overloadedSlug = slugs[(document.lang ?? '')+'/'+document.slug.slice(0, i+1).join('/')]
if(overloadedSlug){
const overloadedSlug =
slugs[
(document.lang ?? '') + '/' + document.slug.slice(0, i + 1).join('/')
]
if (overloadedSlug) {
newSlug[i] = overloadedSlug
} else {
newSlug[i] = document.slug[i]
Expand Down
12 changes: 6 additions & 6 deletions packages/redac/lib/plugin-mdx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import step_4_parse from './4.parse.js'
import step_5_overload from './5.overload.js'

const getConfigs = (config) => {
if(config == null) return []
if(!Array.isArray(config)) config = [config]
return config.map( config => {
if (config == null) return []
if (!Array.isArray(config)) config = [config]
return config.map((config) => {
if (typeof config === 'string') {
return {
target: config,
Expand Down Expand Up @@ -37,7 +37,7 @@ export default (config) => {
return engine
}
},
'engine:source': async ({documents}) =>
'engine:source': async ({ documents }) =>
each(configs, true, async (config) => {
const docs = await step_1_normalize({ config })
.then(step_2_load)
Expand All @@ -46,8 +46,8 @@ export default (config) => {
.then(step_5_overload)
.then(({ documents }) => documents)
documents.push(...docs)
})
}
}),
},
}
}

Expand Down
4 changes: 0 additions & 4 deletions packages/redac/lib/plugin-yaml/3.enrich.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import fs from 'node:fs/promises'
import { parse } from 'yaml'
import path from 'path'
import { glob } from 'glob'
import each from 'each'

export default function pluginYamlEnrich(plugin) {
const { config, documents } = plugin
Expand Down
12 changes: 6 additions & 6 deletions packages/redac/lib/plugin-yaml/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import step_2_load from './2.load.js'
import step_3_enrich from './3.enrich.js'

const getConfigs = (config) => {
if(config == null) return []
if(!Array.isArray(config)) config = [config]
return config.map( config => {
if (config == null) return []
if (!Array.isArray(config)) config = [config]
return config.map((config) => {
if (typeof config === 'string') {
return {
target: config,
Expand Down Expand Up @@ -35,15 +35,15 @@ export default (config) => {
return engine
}
},
'engine:source': async ({documents}) =>
'engine:source': async ({ documents }) =>
each(configs, true, async (config) => {
const docs = await step_1_normalize({ config })
.then(step_2_load)
.then(step_3_enrich)
.then(({ documents }) => documents)
documents.push(...docs)
})
}
}),
},
}
}

Expand Down
7 changes: 3 additions & 4 deletions packages/redac/lib/utils/filedirname.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@

import path from "path";
import { fileURLToPath } from "url";
import path from 'path'
import { fileURLToPath } from 'url'

const dirname = (imp) => {
return path.dirname(fileURLToPath(imp.meta.url))
Expand All @@ -10,4 +9,4 @@ const filename = (imp) => {
throw Error('Not yet implemented')
}

export {dirname, filename}
export { dirname, filename }
4 changes: 2 additions & 2 deletions packages/redac/lib/utils/mklayout.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export default async function mklayout(tmpdir, pages) {
await fs.writeFile(
path_relative,
frontmatter +
(content || '') +
((content || '').endsWith('\n') ? '' : '\n')
(content || '') +
((content || '').endsWith('\n') ? '' : '\n')
)
}
}
6 changes: 3 additions & 3 deletions packages/redac/lib/utils/slugger.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { slug } from "github-slugger"
import deburr from "lodash.deburr"
import { slug } from 'github-slugger'
import deburr from 'lodash.deburr'

const mkname = (raw) => {
return deburr(slug(raw))
};
}
export { mkname }
26 changes: 16 additions & 10 deletions packages/redac/lib/utils/sort.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@

/**
* Sort documents based on slug, lang and sort attributes.
*/

export default function pluginMdxSort (documents) {
export default function pluginMdxSort(documents) {
return documents
.sort( (a, b) => a.slug.length - b.slug.length )
.sort( (a, b) => {
.sort((a, b) => a.slug.length - b.slug.length)
.sort((a, b) => {
// Sort by collection
if (a.collection !== b.collection) return a.collection < b.collection ? -1 : 0
if (a.collection !== b.collection)
return a.collection < b.collection ? -1 : 0
// Sort by lang
if (a.lang !== b.lang) return a.lang < b.lang ? -1 : 0
// Keep original order of a and b
if (a.slug.length !== b.slug.length) return 0
// Compare 2 identical parent slugs with the sort attribute
const min = Math.min(a.slug.length, b.slug.length)
if(min === 0){
if (min === 0) {
return -1
}
const slugA = [...a.slug.slice(0, a.slug.length-1), a.sort ?? a.slug[a.slug.length-1]]
const slugB = [...b.slug.slice(0, b.slug.length-1), b.sort ?? b.slug[b.slug.length-1]]
const slugA = [
...a.slug.slice(0, a.slug.length - 1),
a.sort ?? a.slug[a.slug.length - 1],
]
const slugB = [
...b.slug.slice(0, b.slug.length - 1),
b.sort ?? b.slug[b.slug.length - 1],
]
for (let i = 0; i < min; i++) {
// Last element, use the sort key
const itemA = slugA[i]
const itemB = slugB[i]
// Keep going if parent is shared
if(itemA === itemB){
if (itemA === itemB) {
continue
}
// Diverging parent
return itemA > itemB ? 1 : - 1
return itemA > itemB ? 1 : -1
}
})
}
83 changes: 43 additions & 40 deletions packages/redac/lib/utils/tree.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,61 @@
import { mutate } from 'mixme'

const getIndexInTree = (tree, el) => {
for(let i = 0; i < tree.length; i++){
for (let i = 0; i < tree.length; i++) {
const doc = tree[i]
if(doc.slug[doc.slug.length-1] === el) return i
if (doc.slug[doc.slug.length - 1] === el) return i
}
}

/**
* Organize document as a tree using slug and slug_relative attribute and
* placing child documents inside a children attribute.
*/
export default function tree (documents) {
let tree = [];
export default function tree(documents) {
let tree = []
let root = undefined
documents
// Find comment root
.map((document) => {
if(root === undefined){
// root = document.slug
root = document.slug.slice(0, document.slug.length-1)
}
for(const i in root){
if(root[i] !== document.slug[i]){
root = root.slice(0, i)
// Find comment root
.map((document) => {
if (root === undefined) {
root = document.slug.slice(0, document.slug.length - 1)
}
}
return document
})
// Strip slug from root
.map((document) => {
return {...document, slug_relative: document.slug.slice(root.length, document.slug.length)}
})
// Build the tree
.map((document) => {
let ltree = tree
for(let i=0; i<document.slug_relative.length; i++){
let treeIndex = getIndexInTree(ltree, document.slug_relative[i])
// Document not yet inside the tree
if (treeIndex === undefined){
treeIndex = ltree.length
ltree.push({
children: [],
slug: [...root, ...document.slug_relative.slice(0, i + 1)],
slug_relative: document.slug_relative.slice(0, i + 1)
})
for (const i in root) {
if (root[i] !== document.slug[i]) {
root = root.slice(0, i)
}
}
// Document
if(i == document.slug_relative.length - 1){
mutate(ltree[treeIndex], document)
} else { // Parent
ltree = ltree[treeIndex].children
return document
})
// Strip slug from root
.map((document) => {
return {
...document,
slug_relative: document.slug.slice(root.length, document.slug.length),
}
}
})
})
// Build the tree
.map((document) => {
let ltree = tree
for (let i = 0; i < document.slug_relative.length; i++) {
let treeIndex = getIndexInTree(ltree, document.slug_relative[i])
// Document not yet inside the tree
if (treeIndex === undefined) {
treeIndex = ltree.length
ltree.push({
children: [],
slug: [...root, ...document.slug_relative.slice(0, i + 1)],
slug_relative: document.slug_relative.slice(0, i + 1),
})
}
// Document
if (i == document.slug_relative.length - 1) {
mutate(ltree[treeIndex], document)
} else {
// Parent
ltree = ltree[treeIndex].children
}
}
})
return tree
}

0 comments on commit e740963

Please sign in to comment.