Skip to content

Commit

Permalink
adjust key value assignment logic when processing documentation files…
Browse files Browse the repository at this point in the history
… to ensure uniqueness/consistency
  • Loading branch information
derekwolpert committed Sep 28, 2022
1 parent f4774d0 commit 3817cfa
Showing 1 changed file with 67 additions and 9 deletions.
76 changes: 67 additions & 9 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ class Documentation {
}

class Page {
key
#file
title
body
sections = []
#raw
#entries

constructor (key, raw) {
this.key = key
constructor (file, raw) {
this.#file = file
this.#raw = raw
}

Expand Down Expand Up @@ -101,6 +101,24 @@ class Page {
await Promise.all(this.sections.map(section => section.load()))
return this
}

get key () {
return (
this.#file
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.replace(/\s+/g, '-')
.toLowerCase() ||
'page'
)
}

toJSON () {
return {
key: this.key,
...this
}
}
}

class Section {
Expand All @@ -114,13 +132,26 @@ class Section {
constructor (parent, [header, ...entries]) {
this.#parent = parent
this.#entries = entries

const key = header.text.replace(/[^a-zA-Z0-9_]+/g, '')
const prior = this.page.sections.map(section => [section, ...section.subSections]).flat()
const existing = prior.filter(section => section.title.replace(/[^a-zA-Z0-9_]+/g, '') === key)

this.title = header.text
this.key = `${key}${existing.length ? (existing.length + 1) : ''}`

const prior = [
this.page.key,
...this.page.sections
.map(section => [section, ...section.subSections])
.flat()
.map(section => section.rawKey)
]

const existing = prior
.filter(key => key === this.rawKey)

this.key = `${
this.rawKey
}${
(existing.length || ['page', 'section', 'subsection'].includes(this.rawKey))
? (`_${existing.length + 1}`)
: ''
}`
}

async load () {
Expand Down Expand Up @@ -151,6 +182,33 @@ class Section {
return this
}

get rawKey () {
return (
// The resulting raw keyvalue might be shared with another
// section/subsection within this page. The value will be
// iterated to de-duplicate within the Section's constructor
this.title
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.replace(/\s+/g, '-')
.toLowerCase() ||
(
// if there is a parent section that is using a non-default raw key value
(this.section?.rawKey && this.section.rawKey !== 'section')
// use the parent raw key value
? this.section.rawKey
// otherwise check if the parent page has a non-default raw key value
: (this.page?.key && this.page.key !== 'page')
// use the parent raw key value
? this.page.key
// fallback to default value for section raw key value
: this.section
? 'subsection'
: 'section'
)
)
}

get parent () {
return this.#parent
}
Expand Down

0 comments on commit 3817cfa

Please sign in to comment.