From fde714b7c5039cdd6e07650375bb178181413fa0 Mon Sep 17 00:00:00 2001 From: George Phillips Date: Thu, 26 Feb 2026 16:33:17 +1300 Subject: [PATCH 1/3] Add better variable names --- src/collection.ts | 22 +- src/directory.ts | 42 +- src/document.ts | 6 + src/helpers/Data.ts | 45 +- src/helpers/component-builder.ts | 41 +- src/helpers/dom-diff.ts | 105 +++-- src/helpers/variation-map.ts | 416 ++++++++++++++++++ .../sites/conditional-to-loop/collection.json | 92 ++-- .../four-pages-conditional/collection.json | 80 ++-- .../sites/loop-to-conditional/collection.json | 92 ++-- .../three-pages-attr-variable/collection.json | 44 +- .../three-pages-body-content/collection.json | 34 +- .../collection.json | 68 +-- .../collection.json | 44 +- .../three-pages-conditional/collection.json | 68 +-- .../collection.json | 44 +- .../three-pages-xkcd-news/collection.json | 165 ------- .../sites/three-pages/collection.json | 34 +- .../two-pages-attr-variable/collection.json | 36 +- .../two-pages-body-content/collection.json | 26 +- .../collection.json | 129 ------ .../collection.json | 20 +- .../collection.json | 6 +- .../two-pages-conditional/collection.json | 42 +- .../two-pages-fuzzy-image/collection.json | 161 ------- .../two-pages-fuzzy-loop/collection.json | 156 ------- .../sites/two-pages-loop/collection.json | 64 +-- .../collection.json | 42 +- .../sites/two-pages-not-loop/collection.json | 34 +- .../collection.json | 173 -------- .../two-pages-recursive-loop/collection.json | 26 +- .../two-pages-title-variable/collection.json | 34 +- test/fixtures/sites/two-pages/collection.json | 24 +- 33 files changed, 1114 insertions(+), 1301 deletions(-) create mode 100644 src/helpers/variation-map.ts delete mode 100644 test/fixtures/sites/three-pages-xkcd-news/collection.json delete mode 100644 test/fixtures/sites/two-pages-conditional-content/collection.json delete mode 100644 test/fixtures/sites/two-pages-fuzzy-image/collection.json delete mode 100644 test/fixtures/sites/two-pages-fuzzy-loop/collection.json delete mode 100644 test/fixtures/sites/two-pages-recursive-loop-multiple/collection.json diff --git a/src/collection.ts b/src/collection.ts index 0138824..1feb700 100644 --- a/src/collection.ts +++ b/src/collection.ts @@ -8,6 +8,7 @@ const slugify = (_slugify as any).default as (str: string) => string; import Data from './helpers/Data.ts'; import { mergeTree } from './helpers/dom-diff.ts'; import { ASTNode } from './types.ts'; +import VariationMap, { remapData, remapASTReferences, ScopedNameMap } from './helpers/variation-map.ts'; export interface CollectionConfig { name: string; @@ -65,6 +66,8 @@ export default class Collection { } async build(): Promise { + const variationMap = new VariationMap(); + const documents = await Promise.all( this.files.map(async (file) => { const html = await file.read(); @@ -76,7 +79,8 @@ export default class Collection { content: this.content }, processorConfig: this.processorConfig || {}, - logger: this.logger + logger: this.logger, + variationMap }); }) ); @@ -117,7 +121,6 @@ export default class Collection { const currentPreMergeData = structuredClone(current.base.data.data); const nextPreMergeData = structuredClone(next.base.data.data); - // Merge the next and current bases const layout = mergeTree( current.base.data, next.base.data, @@ -130,12 +133,14 @@ export default class Collection { for (let i = 0; i < current.pages.length; i++) { const page = current.pages[i]; const nextData = new Data([], structuredClone(nextPreMergeData)); + nextData.variationMap = variationMap; mergeTree(page.data, nextData, current.layout, next.layout, [], this.logger); } for (let i = 0; i < next.pages.length; i++) { const page = next.pages[i]; const currentData = new Data([], structuredClone(currentPreMergeData)); + currentData.variationMap = variationMap; mergeTree(page.data, currentData, next.layout, current.layout, [], this.logger); } @@ -155,9 +160,18 @@ export default class Collection { } await this.logger.rotateLog(); + const displayNames = variationMap.generateDisplayNames(); + const remappedLayout = remapASTReferences(current.layout, displayNames); + const remappedPages = [current.base.toJSON(), ...current.pages.map((page) => page.toJSON())] + .map((page) => ({ + ...page, + data: remapData(page.data, displayNames), + content: remapASTReferences(page.content, displayNames) + })); + return { - pages: [current.base.toJSON(), ...current.pages.map((page) => page.toJSON())], - layout: current.layout + pages: remappedPages, + layout: remappedLayout }; } } diff --git a/src/directory.ts b/src/directory.ts index 33432d5..db0ca0b 100644 --- a/src/directory.ts +++ b/src/directory.ts @@ -20,32 +20,30 @@ export default class Directory { async files(): Promise { const absolutePath = this.absolutePath(); - const items = await fs.promises.readdir(absolutePath); + const items = (await fs.promises.readdir(absolutePath)).sort(); const files = [] as File[]; - await Promise.all( - items.map(async (pathname) => { - const relativePath = path.join(this.options.pathname, pathname); - const filePath = path.join(absolutePath, pathname); - const stat = await fs.promises.stat(filePath); - - if (stat.isDirectory()) { - const directory = new Directory({ + for (const pathname of items) { + const relativePath = path.join(this.options.pathname, pathname); + const filePath = path.join(absolutePath, pathname); + const stat = await fs.promises.stat(filePath); + + if (stat.isDirectory()) { + const directory = new Directory({ + basePath: this.options.basePath, + pathname: relativePath + }); + const subfiles = await directory.files(); + files.push(...subfiles); + } else { + files.push( + new File({ basePath: this.options.basePath, pathname: relativePath - }); - const subfiles = await directory.files(); - files.push(...subfiles); - } else { - files.push( - new File({ - basePath: this.options.basePath, - pathname: relativePath - }) - ); - } - }) - ); + }) + ); + } + } return files; } diff --git a/src/document.ts b/src/document.ts index f98d698..6c16eff 100644 --- a/src/document.ts +++ b/src/document.ts @@ -5,6 +5,7 @@ import htmlToAST, { HtmlProcessorConfig, PageContentsConfig } from './helpers/ht import { ASTNode } from './types.ts'; import Data from './helpers/Data.ts'; import { Logger } from './logger.ts'; +import VariationMap from './helpers/variation-map.ts'; export interface ASTTree { base: Page; @@ -22,6 +23,7 @@ export interface DocumentOptions { config: DocumentConfig; processorConfig: HtmlProcessorConfig; logger: Logger; + variationMap?: VariationMap; } export default class Document { @@ -30,10 +32,12 @@ export default class Document { data: Data; layout: ASTNode[]; contents: ASTNode[]; + variationMap?: VariationMap; constructor(options: DocumentOptions) { this.logger = options.logger; this.pathname = options.pathname; + this.variationMap = options.variationMap; const { layout, contents } = htmlToAST( options.content, options.config, @@ -42,10 +46,12 @@ export default class Document { this.layout = layout; this.contents = contents; this.data = new Data([], {}); + this.data.variationMap = this.variationMap; } diff(other: Document): ASTTree { this.data = new Data([], {}); + this.data.variationMap = this.variationMap; this.logger.log(`Comparing ${this.pathname} and ${other.pathname}`); const tree = mergeTree(this.data, other.data, this.layout, other.layout, [], this.logger); diff --git a/src/helpers/Data.ts b/src/helpers/Data.ts index e384418..de7fb41 100644 --- a/src/helpers/Data.ts +++ b/src/helpers/Data.ts @@ -1,6 +1,7 @@ import { ASTAttribute, ASTElementNode } from '../types.ts'; import { getElementSignature } from './getElementSignature.ts'; import { getClassList } from './node-helper.ts'; +import VariationMap, { extractStaticContext } from './variation-map.ts'; const htmlTagToVariableSuffix: Record = { ol: 'list', @@ -119,14 +120,19 @@ export function joinNameParts(parts: string[]) { export default class Data { chain: string[]; data: Record; + variationMap?: VariationMap; + variationScope: string; constructor(chain: string[], data: Record) { this.chain = chain; this.data = data; + this.variationScope = ''; } set(variableName: string, value: any): void { - this.data[formatVariable(variableName)] = value; + const formatted = formatVariable(variableName); + this.data[formatted] = value; + this.variationMap?.recordValue(formatted, value, this.variationScope); } delete(variableName: string): void { @@ -163,12 +169,21 @@ export default class Data { } getVariableName(parentElements: ASTElementNode[], prefix?: string, suffix?: string): string { - const length = parentElements.length; + const lastElement = length > 0 ? parentElements[length - 1] : undefined; + + const signature = lastElement ? getElementSignature(lastElement) : ''; + const key = this.versionedVarableName(joinNameParts([prefix || '', signature, suffix || ''])); + + if (this.variationMap && lastElement) { + this.variationMap.record(key, { + sourceElement: extractStaticContext(lastElement), + suffix: suffix || undefined, + scope: this.variationScope + }); + } - const signature = - length > 0 ? getElementSignature(parentElements[parentElements.length - 1]) : ''; - return this.versionedVarableName(joinNameParts([prefix || '', signature, suffix || ''])); + return key; } versionedVarableName(variableName: string): string { @@ -195,11 +210,27 @@ export default class Data { merge(other: Data): Data { const clone = mergeHash(this.data, other.data); - return new Data(this.chain, clone); + const merged = new Data(this.chain, clone); + merged.variationMap = this.variationMap ?? other.variationMap; + merged.variationScope = this.variationScope; + return merged; } createSubdata(variableName: string, data?: Record): Data { - return new Data(this.getChain(formatVariable(variableName)), data || {}); + const sub = new Data(this.getChain(formatVariable(variableName)), data || {}); + sub.variationMap = this.variationMap; + sub.variationScope = formatVariable(variableName); + return sub; + } + + withVariationMap(map: VariationMap): Data { + this.variationMap = map; + return this; + } + + withScope(scope: string): Data { + this.variationScope = scope; + return this; } toJSON(): Record { diff --git a/src/helpers/component-builder.ts b/src/helpers/component-builder.ts index 1938886..4fd31c2 100644 --- a/src/helpers/component-builder.ts +++ b/src/helpers/component-builder.ts @@ -13,6 +13,7 @@ import { import { diffNodes } from './dom-diff.ts'; import { Logger, nodeDebugString } from '../logger.ts'; import { liftVariables } from './variable-lifting.ts'; +import { extractStaticContext } from './variation-map.ts'; export interface ComponentBuilderConfig { disableMarkdown?: boolean; @@ -41,6 +42,13 @@ export function convertAttrsToVariables( const attr = element.attrs[attrName]; if (attr && attr.type === 'attribute' && editableAttrs[attrName]) { const variableName = data.getVariableName([element], '', attrName); + if (data.variationMap) { + data.variationMap.record(variableName, { + sourceElement: extractStaticContext(element), + attrName, + scope: data.variationScope + }); + } data.set(variableName, attr.value); converted[attrName] = { type: 'variable-attribute', @@ -97,7 +105,8 @@ function buildLoop( inputData: Data, outputData: Data, config: ComponentBuilderConfig, - logger: Logger + logger: Logger, + scopeHint?: string ): Loop | null { const data = [] as Data[]; const base = elements[0]; @@ -114,6 +123,8 @@ function buildLoop( for (let i = 1; i < elements.length; i++) { const loopEl = elements[i]; const newBaseData = new Data([], structuredClone(inputBaseData)); + newBaseData.variationMap = outputData.variationMap; + if (scopeHint) newBaseData.variationScope = scopeHint; const inputLoopData: Record = {}; const liftedVariables = liftVariables(loopEl, inputData); Object.keys(liftedVariables).forEach((variableName) => { @@ -122,6 +133,8 @@ function buildLoop( }); const otherData = new Data([], structuredClone(inputLoopData)); + otherData.variationMap = outputData.variationMap; + if (scopeHint) otherData.variationScope = scopeHint; const template = diffNodes( newBaseData, otherData, @@ -275,18 +288,20 @@ export function convertTreeToComponents( .slice(0, repeatedIndex + 1) .filter((node) => node.type === 'element') as ASTElementNode[]; - if (repeatedElements.length > 1) { - const loopData = buildLoop( - repeatedElements, - parentElements, - existingData, - data, - config, - logger - ); - if (loopData) { - const { itemData, template } = loopData; - const variableName = data.getVariableName(parentElements, '', 'items'); + if (repeatedElements.length > 1) { + const anticipatedLoopVar = data.getVariableName(parentElements, '', 'items'); + const loopData = buildLoop( + repeatedElements, + parentElements, + existingData, + data, + config, + logger, + anticipatedLoopVar + ); + if (loopData) { + const { itemData, template } = loopData; + const variableName = anticipatedLoopVar; data.set( variableName, itemData.map((item: Data) => item.toJSON()) diff --git a/src/helpers/dom-diff.ts b/src/helpers/dom-diff.ts index 2b58c82..d4f01a6 100644 --- a/src/helpers/dom-diff.ts +++ b/src/helpers/dom-diff.ts @@ -29,6 +29,7 @@ import { booleanAttributes } from './attributes.ts'; import { Logger, nodeDebugString } from '../logger.ts'; import { convertTreeToComponents, convertElementToComponent } from './component-builder.ts'; import { liftVariables } from './variable-lifting.ts'; +import { extractStaticContext } from './variation-map.ts'; export function diffBasicNode( firstData: Data, @@ -278,7 +279,11 @@ function diffConditionalAndElementNode( }); const existingData = new Data([], structuredClone(existingValue)); + existingData.variationMap = conditionalData.variationMap; + existingData.variationScope = variableName; const newData = new Data([], structuredClone(liftedVariables)); + newData.variationMap = elementData.variationMap; + newData.variationScope = variableName; const template = diffElementNode( existingData, @@ -338,10 +343,14 @@ function diffConditionalNodes( [], firstSubData === null || typeof firstSubData !== 'object' ? {} : firstSubData ); + newData.variationMap = firstData.variationMap; + newData.variationScope = variableName; const otherData = new Data( [], secondSubData === null || typeof secondSubData !== 'object' ? {} : secondSubData ); + otherData.variationMap = secondData.variationMap; + otherData.variationScope = variableName; const template = diffElementNode( newData, @@ -398,7 +407,11 @@ function diffLoopAndElementNode( }); const existingData = new Data([], existingItems[0]); + existingData.variationMap = loopData.variationMap; + existingData.variationScope = variableName; const newData = new Data([], structuredClone(liftedVariables)); + newData.variationMap = elementData.variationMap; + newData.variationScope = variableName; diffElementNode(existingData, newData, loopNode.template, elementNode, parentElements, logger); elementData.chainSet(loopNode.reference, [newData.toJSON()]); @@ -448,6 +461,13 @@ function mergeAttribute( logger: Logger ): ASTAttribute { const variableName = firstData.getVariableName([element], '', attrName); + if (firstData.variationMap) { + firstData.variationMap.record(variableName, { + sourceElement: extractStaticContext(element), + attrName, + scope: firstData.variationScope + }); + } if (firstAttr.type !== 'attribute') { logger?.warn('TODO: add relevant null state for !secondAttr'); if (secondAttr?.type === 'attribute') { @@ -575,7 +595,9 @@ function buildLoop( firstEls: ASTElementNode[], secondEls: ASTElementNode[], parentElements: ASTElementNode[], - logger: Logger + logger: Logger, + variationMap?: import('./variation-map.ts').default, + scopeHint?: string ): Loop | null { const firstItems = [] as Data[]; const secondItems = [] as Data[]; @@ -599,7 +621,11 @@ function buildLoop( for (let i = 1; i < elements.length; i++) { const loopEl = elements[i]; const newBaseData = new Data([], {}); + newBaseData.variationMap = variationMap; + if (scopeHint) newBaseData.variationScope = scopeHint; const otherData = new Data([], {}); + otherData.variationMap = variationMap; + if (scopeHint) otherData.variationScope = scopeHint; const template = diffNodes( newBaseData, otherData, @@ -742,7 +768,10 @@ export function mergeTree( const parents = [...parentElements]; if (node.type === 'element') { parents.push(node); + const variableName = firstData.getVariableName(parents); const newData = new Data([], {}); + newData.variationMap = firstData.variationMap; + newData.variationScope = variableName; const config = {}; // TODO pass component config const template = convertElementToComponent( newData, @@ -752,7 +781,6 @@ export function mergeTree( firstData, logger ); - const variableName = firstData.getVariableName(parents); firstData.set(variableName, newData.toJSON()); secondData.set(variableName, null); merged.push({ @@ -826,29 +854,32 @@ export function mergeTree( firstEls.length === secondEls.length && nodeTreeEquivalencyScore(firstEls, secondEls) === 1; - // TODO: Object building - if (!isExactMatch) { - const loopData = buildLoop( - firstEls, - secondEls, - parentElements, - logger + // TODO: Object building + if (!isExactMatch) { + const anticipatedLoopVar = firstData.getVariableName( + parentElements, + '', + 'items' + ); + const loopData = buildLoop( + firstEls, + secondEls, + parentElements, + logger, + firstData.variationMap, + anticipatedLoopVar + ); + if (loopData) { + const { firstItems, secondItems, template } = loopData; + const variableName = anticipatedLoopVar; + firstData.set( + variableName, + firstItems.map((item: Data) => item.toJSON()) + ); + secondData.set( + variableName, + secondItems.map((item: Data) => item.toJSON()) ); - if (loopData) { - const { firstItems, secondItems, template } = loopData; - const variableName = firstData.getVariableName( - parentElements, - '', - 'items' - ); - firstData.set( - variableName, - firstItems.map((item: Data) => item.toJSON()) - ); - secondData.set( - variableName, - secondItems.map((item: Data) => item.toJSON()) - ); logger.log('🔄 Added loop', nodeDebugString(template)); merged.push({ @@ -890,14 +921,14 @@ export function mergeTree( nodeDebugString(other, 0, 0) ); - if (current.type === 'element' && other.type === 'loop') { - const repeatedIndex = findRepeatedIndex(firstRemainingNodes); - if (repeatedIndex > 0) { - const elements = firstRemainingNodes - .slice(0, repeatedIndex + 1) - .filter((node) => node.type === 'element') as ASTElementNode[]; - if (elements.length > 1) { - const loopData = buildLoop(elements, [], parentElements, logger); + if (current.type === 'element' && other.type === 'loop') { + const repeatedIndex = findRepeatedIndex(firstRemainingNodes); + if (repeatedIndex > 0) { + const elements = firstRemainingNodes + .slice(0, repeatedIndex + 1) + .filter((node) => node.type === 'element') as ASTElementNode[]; + if (elements.length > 1) { + const loopData = buildLoop(elements, [], parentElements, logger, firstData.variationMap, other.reference[0]); if (loopData) { const { firstItems, template } = loopData; firstData.chainSet( @@ -939,11 +970,11 @@ export function mergeTree( .slice(0, repeatedIndex + 1) .filter((node) => node.type === 'element') as ASTElementNode[]; if (elements.length > 1) { - const loopData = buildLoop(elements, [], parentElements, logger); - if (loopData) { - const { secondItems, template } = loopData; - secondData.chainSet( - current.reference, + const loopData = buildLoop(elements, [], parentElements, logger, secondData.variationMap, current.reference[0]); + if (loopData) { + const { secondItems, template } = loopData; + secondData.chainSet( + current.reference, secondItems.map((item: Data) => item.toJSON()) ); diff --git a/src/helpers/variation-map.ts b/src/helpers/variation-map.ts new file mode 100644 index 0000000..58b89de --- /dev/null +++ b/src/helpers/variation-map.ts @@ -0,0 +1,416 @@ +import { ASTElementNode } from '../types.ts'; +import { normalizeClassList } from './node-helper.ts'; + +export interface SourceElementContext { + tag: string; + staticId?: string; + staticClasses?: string[]; + identifyingAttrs?: Record; +} + +export interface VariationEntry { + internalKey: string; + values: any[]; + sourceElement?: SourceElementContext; + attrName?: string; + suffix?: string; + scope: string; +} + +const htmlTagToSemanticName: Record = { + h1: ['heading', 'subheading'], + h2: ['heading', 'subheading'], + h3: ['heading', 'subheading'], + h4: ['heading', 'subheading'], + h5: ['heading', 'subheading'], + h6: ['heading', 'subheading'], + li: ['item'], + nav: ['navigation'], + img: ['image'] +}; + +function formatForSSG(variable: string): string { + return variable.replaceAll(/([\[\]\(\)%—,\-\:])+/g, '_'); +} + +export function extractStaticContext(element: ASTElementNode): SourceElementContext { + const context: SourceElementContext = { tag: element.name }; + + const idAttr = element.attrs['id']; + if (idAttr?.type === 'attribute' && idAttr.value) { + context.staticId = idAttr.value.trim(); + } + + const classAttr = element.attrs['class']; + if (classAttr?.type === 'attribute' && classAttr.value) { + context.staticClasses = normalizeClassList(classAttr.value); + } + + if (element.name === 'meta') { + const identifying: Record = {}; + for (const attr of ['name', 'property', 'http-equiv']) { + const a = element.attrs[attr]; + if (a?.type === 'attribute' && a.value) { + identifying[attr] = a.value.trim(); + } + } + if (Object.keys(identifying).length > 0) { + context.identifyingAttrs = identifying; + } + } + + if (element.name === 'link') { + const relAttr = element.attrs['rel']; + if (relAttr?.type === 'attribute' && relAttr.value) { + context.identifyingAttrs = { rel: relAttr.value.trim() }; + } + } + + return context; +} + +export type ScopedNameMap = Map>; + +export default class VariationMap { + private scopes: Map> = new Map(); + + record(key: string, meta: Partial>): void { + const scope = meta.scope ?? ''; + if (!this.scopes.has(scope)) this.scopes.set(scope, new Map()); + const scopeMap = this.scopes.get(scope)!; + + if (!scopeMap.has(key)) { + scopeMap.set(key, { + internalKey: key, + values: [], + scope, + ...meta + }); + } else { + const existing = scopeMap.get(key)!; + if (meta.attrName && !existing.attrName) existing.attrName = meta.attrName; + if (meta.sourceElement && !existing.sourceElement) existing.sourceElement = meta.sourceElement; + if (meta.suffix && !existing.suffix) existing.suffix = meta.suffix; + } + } + + recordValue(key: string, value: any, scope: string): void { + const scopeMap = this.scopes.get(scope); + if (scopeMap) { + const entry = scopeMap.get(key); + if (entry) { + entry.values.push(value); + return; + } + } + for (const sm of this.scopes.values()) { + const entry = sm.get(key); + if (entry) { + entry.values.push(value); + return; + } + } + } + + generateDisplayNames(): ScopedNameMap { + const result: ScopedNameMap = new Map(); + const flatLookup = new Map(); + + const processed = new Set(); + const queue = ['']; + + while (queue.length > 0) { + const scope = queue.shift()!; + if (processed.has(scope)) continue; + processed.add(scope); + + const scopeEntries = this.scopes.get(scope); + if (!scopeEntries) continue; + + const parentDisplayName = scope === '' ? undefined : flatLookup.get(scope); + const scopeNames = this.generateScopeNames( + [...scopeEntries.values()], + parentDisplayName + ); + + result.set(scope, scopeNames); + for (const [internalKey, displayName] of scopeNames) { + flatLookup.set(internalKey, displayName); + if (this.scopes.has(internalKey)) { + queue.push(internalKey); + } + } + } + + for (const scope of this.scopes.keys()) { + if (!processed.has(scope)) { + const scopeEntries = this.scopes.get(scope)!; + const parentDisplayName = flatLookup.get(scope); + const scopeNames = this.generateScopeNames( + [...scopeEntries.values()], + parentDisplayName + ); + result.set(scope, scopeNames); + for (const [internalKey, displayName] of scopeNames) { + flatLookup.set(internalKey, displayName); + } + } + } + + return result; + } + + private generateScopeNames( + entries: VariationEntry[], + parentDisplayName?: string + ): Map { + const result = new Map(); + const taken = new Set(); + + const entriesWithCandidates = entries.map((entry) => ({ + entry, + candidates: this.generateCandidateNames(entry) + })); + + entriesWithCandidates.sort((a, b) => { + const diff = a.candidates.length - b.candidates.length; + if (diff !== 0) return diff; + return a.entry.internalKey.localeCompare(b.entry.internalKey); + }); + + for (const { entry, candidates } of entriesWithCandidates) { + let chosen: string | null = null; + for (const candidate of candidates) { + const formatted = formatForSSG(candidate); + if ( + formatted && + !taken.has(formatted) && + formatted !== parentDisplayName + ) { + chosen = formatted; + break; + } + } + + if (!chosen) { + const base = formatForSSG(candidates[0] || entry.internalKey); + let i = 0; + while (taken.has(`${base}_${i}`)) i++; + chosen = `${base}_${i}`; + } + + taken.add(chosen); + result.set(entry.internalKey, chosen); + } + + return result; + } + + private generateCandidateNames(entry: VariationEntry): string[] { + const candidates: string[] = []; + const el = entry.sourceElement; + const suffix = entry.suffix; + const attrName = entry.attrName; + const isNonRootScope = entry.scope !== ''; + + if (!el) { + candidates.push(entry.internalKey); + return candidates; + } + + if (attrName === 'class') { + const stableClasses = this.findStableClasses(entry); + const sorted = stableClasses.sort((a, b) => a.length - b.length); + for (const cls of sorted) { + candidates.push(`${cls}_class`); + } + if (el.staticClasses?.length) { + const elSorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + for (const cls of elSorted) { + if (!stableClasses.includes(cls)) { + candidates.push(`${cls}_class`); + } + } + } + candidates.push(`${el.tag}_class`); + candidates.push(entry.internalKey); + return candidates; + } + + if (attrName) { + if (el.identifyingAttrs) { + for (const value of Object.values(el.identifyingAttrs)) { + candidates.push(value); + } + } + candidates.push(attrName); + if (el.staticId) candidates.push(`${el.staticId}_${attrName}`); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + for (const cls of sorted) { + candidates.push(`${cls}_${attrName}`); + } + } + const semanticNames = htmlTagToSemanticName[el.tag]; + if (semanticNames) { + for (const name of semanticNames) { + candidates.push(`${name}_${attrName}`); + } + } + candidates.push(`${el.tag}_${attrName}`); + candidates.push(entry.internalKey); + return candidates; + } + + if (suffix === 'items') { + if (el.staticId) candidates.push(`${el.staticId}_items`); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + for (const cls of sorted) { + candidates.push(`${cls}_items`); + } + } + candidates.push('items'); + candidates.push(`${el.tag}_items`); + candidates.push(entry.internalKey); + return candidates; + } + + if (suffix === 'markdown' || suffix === 'inline_markdown') { + candidates.push(suffix); + const semanticNames = htmlTagToSemanticName[el.tag]; + if (semanticNames) { + candidates.push(...semanticNames); + } + if (el.staticId) candidates.push(el.staticId); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + candidates.push(...sorted); + } + candidates.push(`${el.tag}_${suffix}`); + candidates.push(entry.internalKey); + return candidates; + } + + if (isNonRootScope) { + candidates.push('text'); + } + const semanticNames = htmlTagToSemanticName[el.tag]; + if (semanticNames) { + candidates.push(...semanticNames); + } + if (el.staticId) candidates.push(el.staticId); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + candidates.push(...sorted); + } + candidates.push(el.tag); + candidates.push(entry.internalKey); + return candidates; + } + + private findStableClasses(entry: VariationEntry): string[] { + const stringValues = entry.values.filter( + (v): v is string => typeof v === 'string' + ); + if (stringValues.length === 0) { + return entry.sourceElement?.staticClasses ?? []; + } + + const classLists = stringValues.map((v) => normalizeClassList(v)); + return classLists.reduce((acc, list) => acc.filter((cls) => list.includes(cls))); + } +} + +export function remapData( + data: Record, + scopeMap: ScopedNameMap, + scope: string = '' +): Record { + const nameMap = scopeMap.get(scope); + const result: Record = {}; + for (const [key, value] of Object.entries(data)) { + const newKey = nameMap?.get(key) ?? key; + if (Array.isArray(value)) { + result[newKey] = value.map((item) => + typeof item === 'object' && item !== null + ? remapData(item, scopeMap, key) + : item + ); + } else if (typeof value === 'object' && value !== null) { + result[newKey] = remapData(value, scopeMap, key); + } else { + result[newKey] = value; + } + } + return result; +} + +export function remapASTReferences( + tree: import('../types.ts').ASTNode[], + scopeMap: ScopedNameMap, + scope: string = '' +): import('../types.ts').ASTNode[] { + return tree.map((node) => remapASTNode(node, scopeMap, scope)); +} + +function remapReference(ref: string[], nameMap: Map | undefined): string[] { + if (!nameMap) return ref; + return ref.map((part) => nameMap.get(part) ?? part); +} + +function remapASTNode( + node: import('../types.ts').ASTNode, + scopeMap: ScopedNameMap, + scope: string +): import('../types.ts').ASTNode { + const nameMap = scopeMap.get(scope); + switch (node.type) { + case 'variable': + case 'markdown-variable': + case 'inline-markdown-variable': + return { ...node, reference: remapReference(node.reference, nameMap) }; + case 'conditional': { + const innerScope = node.reference[0]; + return { + ...node, + reference: remapReference(node.reference, nameMap), + template: remapASTNode(node.template, scopeMap, innerScope) as import('../types.ts').ASTElementNode + }; + } + case 'loop': { + const innerScope = node.reference[0]; + return { + ...node, + reference: remapReference(node.reference, nameMap), + template: remapASTNode(node.template, scopeMap, innerScope) as import('../types.ts').ASTElementNode + }; + } + case 'element': + return { + ...node, + attrs: remapAttrList(node.attrs, nameMap), + children: remapASTReferences(node.children, scopeMap, scope) + }; + default: + return node; + } +} + +function remapAttrList( + attrs: import('../types.ts').ASTAttributeList, + nameMap: Map | undefined +): import('../types.ts').ASTAttributeList { + const result: import('../types.ts').ASTAttributeList = {}; + for (const [key, attr] of Object.entries(attrs)) { + if (attr.type === 'variable-attribute' || attr.type === 'conditional-attribute') { + result[key] = { + ...attr, + reference: remapReference(attr.reference, nameMap) + }; + } else { + result[key] = attr; + } + } + return result; +} diff --git a/test/fixtures/sites/conditional-to-loop/collection.json b/test/fixtures/sites/conditional-to-loop/collection.json index b63ab92..b568df7 100644 --- a/test/fixtures/sites/conditional-to-loop/collection.json +++ b/test/fixtures/sites/conditional-to-loop/collection.json @@ -5,41 +5,41 @@ { "pathname": "a.html", "data": { - "title": "Page A", - "nav": "Nav A", - "div_card": [ - { - "div_card": "Card A" - } - ] + "title": "Page A", + "navigation": "Nav A", + "card": [ + { + "text": "Card A" + } + ] }, "content": [] }, { "pathname": "b.html", "data": { - "title": "Page B", - "nav": "Nav B", - "div_card": [] + "title": "Page B", + "navigation": "Nav B", + "card": [] }, "content": [] }, { "pathname": "c.html", "data": { - "div_items": [ - { - "div_card": "Card C1" - }, - { - "div_card": "Card C2" - }, - { - "div_card": "Card C3" - } - ], - "title": "Page C", - "nav": "Nav C" + "items": [ + { + "text": "Card C1" + }, + { + "text": "Card C2" + }, + { + "text": "Card C3" + } + ], + "title": "Page C", + "navigation": "Nav C" }, "content": [] } @@ -112,7 +112,7 @@ { "type": "variable", "reference": [ - "nav" + "navigation" ] } ] @@ -123,28 +123,28 @@ }, { "type": "loop", - "reference": [ - "div_card" - ], - "template": { - "type": "element", - "name": "div", - "attrs": { - "class": { - "type": "attribute", - "name": "class", - "value": "card" - } - }, - "children": [ - { - "type": "variable", - "reference": [ - "div_card" - ] - } - ] - } + "reference": [ + "card" + ], + "template": { + "type": "element", + "name": "div", + "attrs": { + "class": { + "type": "attribute", + "name": "class", + "value": "card" + } + }, + "children": [ + { + "type": "variable", + "reference": [ + "text" + ] + } + ] + } }, { "type": "text", diff --git a/test/fixtures/sites/four-pages-conditional/collection.json b/test/fixtures/sites/four-pages-conditional/collection.json index 2cd35bb..3288488 100644 --- a/test/fixtures/sites/four-pages-conditional/collection.json +++ b/test/fixtures/sites/four-pages-conditional/collection.json @@ -1,49 +1,48 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Home | Test", - "meta_description": { - "meta_description_content": "Home" - }, - "h1_inline_markdown": "Home" - } + "inline_markdown": "About", + "meta": null, + "title": "Test" + }, + "content": [] }, { - "pathname": "staff.html", - "content": [], + "pathname": "contact.html", "data": { - "title": "Staff | Test", - "meta_description": { - "meta_description_content": "Fixed" + "inline_markdown": "Contact", + "meta": { + "description": "Fixed" }, - "h1_inline_markdown": "Staff" - } + "title": "Test" + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "index.html", "data": { - "title": "Test", - "meta_description": null, - "h1_inline_markdown": "About" - } + "inline_markdown": "Home", + "title": "Home | Test", + "meta": { + "description": "Home" + } + }, + "content": [] }, { - "pathname": "contact.html", - "content": [], + "pathname": "staff.html", "data": { - "title": "Test", - "meta_description": { - "meta_description_content": "Fixed" - }, - "h1_inline_markdown": "Contact" - } + "inline_markdown": "Staff", + "title": "Staff | Test", + "meta": { + "description": "Fixed" + } + }, + "content": [] } ], "layout": [ @@ -72,7 +71,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -82,7 +83,9 @@ }, { "type": "conditional", - "reference": ["meta_description"], + "reference": [ + "meta" + ], "template": { "type": "element", "name": "meta", @@ -95,7 +98,9 @@ "content": { "type": "variable-attribute", "name": "content", - "reference": ["meta_description_content"] + "reference": [ + "description" + ] } }, "children": [] @@ -127,7 +132,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -141,5 +148,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/loop-to-conditional/collection.json b/test/fixtures/sites/loop-to-conditional/collection.json index 8fd739d..826ed48 100644 --- a/test/fixtures/sites/loop-to-conditional/collection.json +++ b/test/fixtures/sites/loop-to-conditional/collection.json @@ -5,41 +5,41 @@ { "pathname": "a.html", "data": { - "title": "Page A", - "nav": "Nav A", - "div_items": [ - { - "div_card": "Card A" - } - ] + "title": "Page A", + "navigation": "Nav A", + "items": [ + { + "text": "Card A" + } + ] }, "content": [] }, { "pathname": "b.html", "data": { - "div_items": [ - { - "div_card": "Card B1" - }, - { - "div_card": "Card B2" - }, - { - "div_card": "Card B3" - } - ], - "title": "Page B", - "nav": "Nav B" + "items": [ + { + "text": "Card B1" + }, + { + "text": "Card B2" + }, + { + "text": "Card B3" + } + ], + "title": "Page B", + "navigation": "Nav B" }, "content": [] }, { "pathname": "c.html", "data": { - "title": "Page C", - "nav": "Nav C", - "div_card": [] + "title": "Page C", + "navigation": "Nav C", + "card": [] }, "content": [] } @@ -112,7 +112,7 @@ { "type": "variable", "reference": [ - "nav" + "navigation" ] } ] @@ -123,28 +123,28 @@ }, { "type": "loop", - "reference": [ - "div_card" - ], - "template": { - "type": "element", - "name": "div", - "attrs": { - "class": { - "type": "attribute", - "name": "class", - "value": "card" - } - }, - "children": [ - { - "type": "variable", - "reference": [ - "div_card" - ] - } - ] - } + "reference": [ + "card" + ], + "template": { + "type": "element", + "name": "div", + "attrs": { + "class": { + "type": "attribute", + "name": "class", + "value": "card" + } + }, + "children": [ + { + "type": "variable", + "reference": [ + "text" + ] + } + ] + } }, { "type": "text", diff --git a/test/fixtures/sites/three-pages-attr-variable/collection.json b/test/fixtures/sites/three-pages-attr-variable/collection.json index fc10239..5cb1de6 100644 --- a/test/fixtures/sites/three-pages-attr-variable/collection.json +++ b/test/fixtures/sites/three-pages-attr-variable/collection.json @@ -1,31 +1,30 @@ { - "staticFiles": ["assets/goose.jpg"], "collections": { "pages": { "pages": [ - { - "pathname": "index.html", - "content": [], - "data": { - "title": "Goose Owner", - "img_alt": "Our goose" - } - }, { "pathname": "about.html", - "content": [], "data": { "title": "Goose Admirer", - "img_alt": "Their goose" - } + "alt": "Their goose" + }, + "content": [] }, { "pathname": "contact.html", - "content": [], "data": { "title": "Another Goose Admirer", - "img_alt": "Their goose" - } + "alt": "Their goose" + }, + "content": [] + }, + { + "pathname": "index.html", + "data": { + "title": "Goose Owner", + "alt": "Our goose" + }, + "content": [] } ], "layout": [ @@ -54,7 +53,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -89,7 +90,9 @@ "alt": { "type": "variable-attribute", "name": "alt", - "reference": ["img_alt"] + "reference": [ + "alt" + ] } }, "children": [] @@ -104,5 +107,8 @@ } ] } - } -} + }, + "staticFiles": [ + "assets/goose.jpg" + ] +} \ No newline at end of file diff --git a/test/fixtures/sites/three-pages-body-content/collection.json b/test/fixtures/sites/three-pages-body-content/collection.json index 6014719..e6a0062 100644 --- a/test/fixtures/sites/three-pages-body-content/collection.json +++ b/test/fixtures/sites/three-pages-body-content/collection.json @@ -1,10 +1,12 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { "pathname": "about.html", + "data": { + "title": "About | Test" + }, "content": [ { "type": "element", @@ -21,13 +23,13 @@ "type": "text", "value": "\n" } - ], - "data": { - "title": "About | Test" - } + ] }, { "pathname": "contact.html", + "data": { + "title": "Contact | Test" + }, "content": [ { "type": "element", @@ -44,13 +46,13 @@ "type": "text", "value": "\n" } - ], - "data": { - "title": "Contact | Test" - } + ] }, { "pathname": "index.html", + "data": { + "title": "Home | Test" + }, "content": [ { "type": "element", @@ -67,10 +69,7 @@ "type": "text", "value": "\n" } - ], - "data": { - "title": "Home | Test" - } + ] } ], "layout": [ @@ -99,7 +98,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -135,5 +136,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json b/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json index d2a413d..21f25bb 100644 --- a/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json +++ b/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json @@ -1,38 +1,37 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "contact.html", "data": { - "title": "Home | Test", - "meta_description": { - "meta_description_content": "Home" - }, - "h1_inline_markdown": "Home" - } + "inline_markdown": "Contact", + "title": "Test", + "meta": { + "description": "Fixed" + } + }, + "content": [] }, { - "pathname": "zabout.html", - "content": [], + "pathname": "index.html", "data": { - "title": "Test", - "meta_description": null, - "h1_inline_markdown": "About" - } + "inline_markdown": "Home", + "title": "Home | Test", + "meta": { + "description": "Home" + } + }, + "content": [] }, { - "pathname": "contact.html", - "content": [], + "pathname": "zabout.html", "data": { - "title": "Test", - "meta_description": { - "meta_description_content": "Fixed" - }, - "h1_inline_markdown": "Contact" - } + "inline_markdown": "About", + "meta": null, + "title": "Test" + }, + "content": [] } ], "layout": [ @@ -61,7 +60,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -71,7 +72,9 @@ }, { "type": "conditional", - "reference": ["meta_description"], + "reference": [ + "meta" + ], "template": { "type": "element", "name": "meta", @@ -83,8 +86,10 @@ }, "content": { "type": "variable-attribute", - "reference": ["meta_description_content"], - "name": "content" + "name": "content", + "reference": [ + "description" + ] } }, "children": [] @@ -116,7 +121,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -130,5 +137,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json b/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json index 236aa96..597e9b5 100644 --- a/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json +++ b/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json @@ -5,21 +5,21 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "Beta", - "ul_items": [ + "inline_markdown": "Beta", + "items": [ { - "li": "Beta description", - "strong": null + "item": "Beta description", + "text": null }, { - "li": "", - "strong": { + "item": "", + "text": { "strong": "Beta closed" } }, { - "li": "Beta time", - "strong": null + "item": "Beta time", + "text": null } ], "title": "Beta | Test" @@ -29,16 +29,16 @@ { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Gamma", - "ul_items": [ + "inline_markdown": "Gamma", + "items": [ { - "li": "Gamma description" + "item": "Gamma description" }, { - "li": "Gamma open" + "item": "Gamma open" }, { - "li": "Gamma time" + "item": "Gamma time" } ], "title": "Gamma | Test" @@ -48,16 +48,16 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Alpha", - "ul_items": [ + "inline_markdown": "Alpha", + "items": [ { - "li": "Alpha description" + "item": "Alpha description" }, { - "li": "Alpha open" + "item": "Alpha open" }, { - "li": "Alpha time" + "item": "Alpha time" } ], "title": "Alpha | Test" @@ -124,7 +124,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] @@ -145,7 +145,7 @@ { "type": "loop", "reference": [ - "ul_items" + "items" ], "template": { "type": "element", @@ -174,13 +174,13 @@ { "type": "variable", "reference": [ - "li" + "item" ] }, { "type": "conditional", "reference": [ - "strong" + "text" ], "template": { "type": "element", diff --git a/test/fixtures/sites/three-pages-conditional/collection.json b/test/fixtures/sites/three-pages-conditional/collection.json index 705f29e..d856097 100644 --- a/test/fixtures/sites/three-pages-conditional/collection.json +++ b/test/fixtures/sites/three-pages-conditional/collection.json @@ -1,38 +1,37 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ - { - "pathname": "index.html", - "content": [], - "data": { - "title": "Home | Test", - "meta_description": { - "meta_description_content": "Home" - }, - "h1_inline_markdown": "Home" - } - }, { "pathname": "about.html", - "content": [], "data": { - "title": "Test", - "meta_description": null, - "h1_inline_markdown": "About" - } + "inline_markdown": "About", + "meta": null, + "title": "Test" + }, + "content": [] }, { "pathname": "contact.html", - "content": [], "data": { - "title": "Test", - "meta_description": { - "meta_description_content": "Fixed" + "inline_markdown": "Contact", + "meta": { + "description": "Fixed" }, - "h1_inline_markdown": "Contact" - } + "title": "Test" + }, + "content": [] + }, + { + "pathname": "index.html", + "data": { + "inline_markdown": "Home", + "title": "Home | Test", + "meta": { + "description": "Home" + } + }, + "content": [] } ], "layout": [ @@ -61,7 +60,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -71,7 +72,9 @@ }, { "type": "conditional", - "reference": ["meta_description"], + "reference": [ + "meta" + ], "template": { "type": "element", "name": "meta", @@ -83,8 +86,10 @@ }, "content": { "type": "variable-attribute", - "reference": ["meta_description_content"], - "name": "content" + "name": "content", + "reference": [ + "description" + ] } }, "children": [] @@ -116,7 +121,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -130,5 +137,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/three-pages-title-variable/collection.json b/test/fixtures/sites/three-pages-title-variable/collection.json index 72401cc..4613051 100644 --- a/test/fixtures/sites/three-pages-title-variable/collection.json +++ b/test/fixtures/sites/three-pages-title-variable/collection.json @@ -1,31 +1,30 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Home | Test", - "h1_inline_markdown": "Home" - } + "inline_markdown": "About", + "title": "Test" + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "contact.html", "data": { - "title": "Test", - "h1_inline_markdown": "About" - } + "inline_markdown": "Contact", + "title": "Test" + }, + "content": [] }, { - "pathname": "contact.html", - "content": [], + "pathname": "index.html", "data": { - "title": "Test", - "h1_inline_markdown": "Contact" - } + "inline_markdown": "Home", + "title": "Home | Test" + }, + "content": [] } ], "layout": [ @@ -54,7 +53,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -84,7 +85,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -98,5 +101,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/three-pages-xkcd-news/collection.json b/test/fixtures/sites/three-pages-xkcd-news/collection.json deleted file mode 100644 index 3ff4767..0000000 --- a/test/fixtures/sites/three-pages-xkcd-news/collection.json +++ /dev/null @@ -1,165 +0,0 @@ -{ - "collections": { - "pages": { - "pages": [ - { - "pathname": "about.html", - "data": { - "div_news_inline_markdown": "", - "div_xkcdNews": { - "div_countdown_inline_markdown": "[![](https://xkcd.com/s/5bef6b.png)](https://xkcd.com/what-if-2/)", - "div_xkcdNews_inline_markdown": "What If? 2 is ![now available](https://xkcd.com/what-if-2/#UK) in paperback in the UK!" - } - }, - "content": [] - }, - { - "pathname": "contact.html", - "data": { - "div_news_inline_markdown": "There's a larger version of this map [here](https://xkcd.com/1079/large/)! It's also available as a [poster](https://store.xkcd.com/products/united-shapes-poster). \n \nNew: [what-if.xkcd.com](https://what-if.xkcd.com/1/): abusing science to answer hypothetical questions. \n \nI'll answer a new reader question every Tuesday.", - "div_xkcdNews": null - }, - "content": [] - }, - { - "pathname": "index.html", - "data": { - "div_news_inline_markdown": "A helpful reader has provided an [s/keyboard/leopard/ user script](https://userscripts.org/scripts/show/128626).", - "div_xkcdNews": null - }, - "content": [] - } - ], - "layout": [ - { - "type": "doctype", - "value": "html" - }, - { - "type": "element", - "name": "html", - "attrs": {}, - "children": [ - { - "type": "element", - "name": "head", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "title", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "Test" - } - ] - }, - { - "type": "text", - "value": "\n\t" - } - ] - }, - { - "type": "text", - "value": "\n\t" - }, - { - "type": "element", - "name": "body", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "div", - "attrs": { - "id": { - "type": "attribute", - "name": "id", - "value": "news" - } - }, - "children": [ - { - "type": "inline-markdown-variable", - "reference": [ - "div_news_inline_markdown" - ] - }, - { - "type": "conditional", - "reference": [ - "div_xkcdNews" - ], - "template": { - "type": "element", - "name": "div", - "attrs": { - "id": { - "type": "attribute", - "name": "id", - "value": "xkcdNews" - } - }, - "children": [ - { - "type": "text", - "value": "\n\t\t\t\t" - }, - { - "type": "element", - "name": "div", - "attrs": { - "id": { - "type": "attribute", - "name": "id", - "value": "countdown" - } - }, - "children": [ - { - "type": "inline-markdown-variable", - "reference": [ - "div_countdown_inline_markdown" - ] - } - ] - }, - { - "type": "inline-markdown-variable", - "reference": [ - "div_xkcdNews_inline_markdown" - ] - } - ] - } - }, - { - "type": "text", - "value": "\n\t\t" - } - ] - }, - { - "type": "text", - "value": "\n\t\n" - } - ] - } - ] - } - ] - } - }, - "staticFiles": [] -} \ No newline at end of file diff --git a/test/fixtures/sites/three-pages/collection.json b/test/fixtures/sites/three-pages/collection.json index ab3b63c..a7c0bbb 100644 --- a/test/fixtures/sites/three-pages/collection.json +++ b/test/fixtures/sites/three-pages/collection.json @@ -1,28 +1,27 @@ { - "staticFiles": ["assets/goose.jpg"], "collections": { "pages": { "pages": [ { "pathname": "about.html", - "content": [], "data": { - "h1_inline_markdown": "About" - } + "inline_markdown": "About" + }, + "content": [] }, { - "pathname": "index.html", - "content": [], + "pathname": "contact.html", "data": { - "h1_inline_markdown": "Home" - } + "inline_markdown": "Contact" + }, + "content": [] }, { - "pathname": "contact.html", - "content": [], + "pathname": "index.html", "data": { - "h1_inline_markdown": "Contact" - } + "inline_markdown": "Home" + }, + "content": [] } ], "layout": [ @@ -81,7 +80,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -95,5 +96,8 @@ } ] } - } -} + }, + "staticFiles": [ + "assets/goose.jpg" + ] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-attr-variable/collection.json b/test/fixtures/sites/two-pages-attr-variable/collection.json index 5a44d0c..bf8d28d 100644 --- a/test/fixtures/sites/two-pages-attr-variable/collection.json +++ b/test/fixtures/sites/two-pages-attr-variable/collection.json @@ -1,23 +1,22 @@ { - "staticFiles": ["assets/goose.jpg"], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Goose Owner", - "img_alt": "Our goose" - } + "title": "Goose Admirer", + "alt": "Their goose" + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "index.html", "data": { - "title": "Goose Admirer", - "img_alt": "Their goose" - } + "title": "Goose Owner", + "alt": "Our goose" + }, + "content": [] } ], "layout": [ @@ -46,7 +45,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -81,7 +82,9 @@ "alt": { "type": "variable-attribute", "name": "alt", - "reference": ["img_alt"] + "reference": [ + "alt" + ] } }, "children": [] @@ -96,5 +99,8 @@ } ] } - } -} + }, + "staticFiles": [ + "assets/goose.jpg" + ] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-body-content/collection.json b/test/fixtures/sites/two-pages-body-content/collection.json index d68f82b..f5d625a 100644 --- a/test/fixtures/sites/two-pages-body-content/collection.json +++ b/test/fixtures/sites/two-pages-body-content/collection.json @@ -1,10 +1,12 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { "pathname": "about.html", + "data": { + "title": "About | Test" + }, "content": [ { "type": "element", @@ -21,13 +23,13 @@ "type": "text", "value": "\n" } - ], - "data": { - "title": "About | Test" - } + ] }, { "pathname": "index.html", + "data": { + "title": "Home | Test" + }, "content": [ { "type": "element", @@ -44,10 +46,7 @@ "type": "text", "value": "\n" } - ], - "data": { - "title": "Home | Test" - } + ] } ], "layout": [ @@ -76,7 +75,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -112,5 +113,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-conditional-content/collection.json b/test/fixtures/sites/two-pages-conditional-content/collection.json deleted file mode 100644 index fa607e1..0000000 --- a/test/fixtures/sites/two-pages-conditional-content/collection.json +++ /dev/null @@ -1,129 +0,0 @@ -{ - "staticFiles": [], - "collections": { - "pages": { - "pages": [ - { - "pathname": "about.html", - "content": [], - "data": { - "title": "About | Test" - } - }, - { - "pathname": "index.html", - "content": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "h1", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "Home" - } - ] - }, - { - "type": "text", - "value": "\n\t" - } - ], - "data": { - "title": "Home | Test" - } - } - ], - "layout": [ - { - "type": "doctype", - "value": "html" - }, - { - "type": "element", - "name": "html", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t" - }, - { - "type": "element", - "name": "head", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "title", - "attrs": {}, - "children": [ - { - "type": "variable", - "reference": ["title"] - } - ] - }, - { - "type": "text", - "value": "\n\t" - } - ] - }, - { - "type": "text", - "value": "\n\t" - }, - { - "type": "element", - "name": "body", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "reference": ["show-div.content"], - "type": "conditional", - "template": { - "type": "element", - "name": "div", - "attrs": [ - { - "type": "attribute", - "name": "class", - "value": "content" - } - ], - "children": [ - { - "type": "content" - } - ] - } - }, - { - "type": "text", - "value": "\n\t" - } - ] - }, - { - "type": "text", - "value": "\n" - } - ] - } - ] - } - } -} diff --git a/test/fixtures/sites/two-pages-conditional-loop/collection.json b/test/fixtures/sites/two-pages-conditional-loop/collection.json index 4bbb8e4..dcbe2bb 100644 --- a/test/fixtures/sites/two-pages-conditional-loop/collection.json +++ b/test/fixtures/sites/two-pages-conditional-loop/collection.json @@ -8,13 +8,13 @@ "div": { "div_items": [ { - "div_markdown": "Lorem Ipsum 1\n\n![](https://placebear.com/250/50)" + "markdown": "Lorem Ipsum 1\n\n![](https://placebear.com/250/50)" }, { - "div_markdown": "Lorem Ipsum 2\n\n![](https://placebear.com/150/50)" + "markdown": "Lorem Ipsum 2\n\n![](https://placebear.com/150/50)" }, { - "div_markdown": "Lorem Ipsum 3\n\n![](https://placebear.com/50/50)" + "markdown": "Lorem Ipsum 3\n\n![](https://placebear.com/50/50)" } ] } @@ -80,7 +80,9 @@ }, { "type": "conditional", - "reference": ["div"], + "reference": [ + "div" + ], "template": { "type": "element", "name": "div", @@ -92,7 +94,9 @@ }, { "type": "loop", - "reference": ["div_items"], + "reference": [ + "div_items" + ], "template": { "type": "element", "name": "div", @@ -104,7 +108,9 @@ }, { "type": "markdown-variable", - "reference": ["div_markdown"] + "reference": [ + "markdown" + ] }, { "type": "text", @@ -132,4 +138,4 @@ } }, "staticFiles": [] -} +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-conditional-object/collection.json b/test/fixtures/sites/two-pages-conditional-object/collection.json index e22edb8..89c37fc 100644 --- a/test/fixtures/sites/two-pages-conditional-object/collection.json +++ b/test/fixtures/sites/two-pages-conditional-object/collection.json @@ -5,7 +5,7 @@ { "pathname": "about.html", "data": { - "div_twoColumn": { + "twoColumn": { "div_twoColumn_left_markdown": "Lorem ipsum dolor sit amet", "div_twoColumn_right_markdown": "Etiam nibh metus, imperdiet eu eros vel, congue aliquet eros." } @@ -15,7 +15,7 @@ { "pathname": "index.html", "data": { - "div_twoColumn": null + "twoColumn": null }, "content": [] } @@ -72,7 +72,7 @@ { "type": "conditional", "reference": [ - "div_twoColumn" + "twoColumn" ], "template": { "type": "element", diff --git a/test/fixtures/sites/two-pages-conditional/collection.json b/test/fixtures/sites/two-pages-conditional/collection.json index 0d4d32e..1d534ea 100644 --- a/test/fixtures/sites/two-pages-conditional/collection.json +++ b/test/fixtures/sites/two-pages-conditional/collection.json @@ -1,25 +1,24 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Home | Test", - "meta_description": {}, - "h1_inline_markdown": "Home" - } + "inline_markdown": "About", + "title": "Test", + "meta": null + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "index.html", "data": { - "title": "Test", - "meta_description": null, - "h1_inline_markdown": "About" - } + "inline_markdown": "Home", + "title": "Home | Test", + "meta": {} + }, + "content": [] } ], "layout": [ @@ -48,7 +47,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -58,7 +59,9 @@ }, { "type": "conditional", - "reference": ["meta_description"], + "reference": [ + "meta" + ], "template": { "type": "element", "name": "meta", @@ -103,7 +106,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -117,5 +122,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-fuzzy-image/collection.json b/test/fixtures/sites/two-pages-fuzzy-image/collection.json deleted file mode 100644 index a75f93a..0000000 --- a/test/fixtures/sites/two-pages-fuzzy-image/collection.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "staticFiles": ["assets/goose.jpg", "assets/goose-reversed.jpg"], - "collections": { - "pages": { - "pages": [ - { - "pathname": "index.html", - "content": [], - "data": { - "title": "Goose Owner", - "img": { - "src": "assets/goose.jpg", - "class": "", - "alt": "Goose" - }, - "h1_inline_markdown": "Goose Owner" - } - }, - { - "pathname": "about.html", - "content": [], - "data": { - "title": "Goose Admirer", - "img": { - "src": "assets/goose-reversed.jpg", - "class": "reversed", - "alt": "Goose Reversed" - }, - "h1_inline_markdown": "Goose Admirer" - } - } - ], - "layout": [ - { - "type": "doctype", - "value": "html" - }, - { - "type": "element", - "name": "html", - "attrs": {}, - "children": [ - { - "type": "element", - "name": "head", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "title", - "attrs": {}, - "children": [ - { - "type": "variable", - "reference": ["title"] - } - ] - }, - { - "type": "text", - "value": "\n\t" - } - ] - }, - { - "type": "text", - "value": "\n\t" - }, - { - "type": "element", - "name": "body", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "section", - "attrs": { - "class": { - "type": "attribute", - "name": "class", - "value": "hero" - } - }, - "children": [ - { - "type": "text", - "value": "\n\t\t\t" - }, - { - "type": "element", - "name": "img", - "attrs": { - "alt": { - "type": "variable-attribute", - "name": "alt", - "reference": ["img", "alt"] - }, - "class": { - "type": "variable-attribute", - "name": "class", - "reference": ["img", "class"] - }, - "height": { - "type": "attribute", - "name": "height", - "value": "275" - }, - "src": { - "type": "variable-attribute", - "name": "src", - "reference": ["img", "src"] - }, - "width": { - "type": "attribute", - "name": "width", - "value": "183" - } - }, - "children": [] - }, - { - "type": "text", - "value": "\n\t\t\t" - }, - { - "type": "element", - "name": "h1", - "attrs": {}, - "children": [ - { - "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] - } - ] - }, - { - "type": "text", - "value": "\n\t\t" - } - ] - }, - { - "type": "text", - "value": "\n\t\n" - } - ] - } - ] - } - ] - } - } -} diff --git a/test/fixtures/sites/two-pages-fuzzy-loop/collection.json b/test/fixtures/sites/two-pages-fuzzy-loop/collection.json deleted file mode 100644 index a339f6f..0000000 --- a/test/fixtures/sites/two-pages-fuzzy-loop/collection.json +++ /dev/null @@ -1,156 +0,0 @@ -{ - "staticFiles": [], - "collections": { - "pages": { - "pages": [ - { - "pathname": "bethunes-gully.html", - "content": [], - "data": { - "title": "Bethune’s Gully", - "h2": "Bethune’s Gully", - "div.badge_items": [ - { - "div.badge": "picnic", - "div.badge_class": "badge-orange" - }, - { - "div.badge": "walk", - "div.badge_class": "badge-green" - } - ] - } - }, - { - "pathname": "smails-beach.html", - "content": [], - "data": { - "title": "Smails Beach", - "h2": "Smails Beach", - "div.badge_items": [ - { - "div.badge": "beach", - "div.badge_class": "badge-blue" - }, - { - "div.badge": "wildlife", - "div.badge_class": "badge-navy" - } - ] - } - } - ], - "layout": [ - { - "type": "doctype", - "value": "html" - }, - { - "type": "element", - "name": "html", - "attrs": {}, - "children": [ - { - "type": "element", - "name": "head", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "title", - "attrs": {}, - "children": [ - { - "type": "variable", - "reference": ["title"] - } - ] - }, - { - "type": "text", - "value": "\n\t" - } - ] - }, - { - "type": "text", - "value": "\n\t" - }, - { - "type": "element", - "name": "body", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "element", - "name": "h2", - "attrs": {}, - "children": [ - { - "type": "variable", - "reference": ["h2"] - } - ] - }, - { - "type": "text", - "value": "\n\n\t\t" - }, - { - "type": "element", - "name": "ul", - "attrs": { - "class": { - "type": "attribute", - "name": "class", - "value": "badges" - } - }, - "children": [ - { - "type": "text", - "value": "\n\t\t\t" - }, - { - "type": "loop", - "reference": ["li.badge.badge-orange_items"], - "template": { - "type": "element", - "name": "li", - "attrs": { - "class": { - "type": "variable-attribute", - "name": "class", - "reference": ["li.badge.badge-orange_class"] - } - }, - "children": [ - { - "type": "variable", - "reference": ["li.badge.badge-orange"] - } - ] - } - } - ] - }, - { - "type": "text", - "value": "\n\t\n" - } - ] - } - ] - } - ] - } - } -} diff --git a/test/fixtures/sites/two-pages-loop/collection.json b/test/fixtures/sites/two-pages-loop/collection.json index 72732d0..91a69ce 100644 --- a/test/fixtures/sites/two-pages-loop/collection.json +++ b/test/fixtures/sites/two-pages-loop/collection.json @@ -1,39 +1,38 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ - { - "pathname": "index.html", - "content": [], - "data": { - "title": "Home | Test", - "h1_inline_markdown": "Home", - "div_items": [ - { - "div_block": "Home first item" - } - ] - } - }, { "pathname": "about.html", - "content": [], "data": { - "title": "About | Test", - "h1_inline_markdown": "About", - "div_items": [ + "inline_markdown": "About", + "items": [ { - "div_block": "About first item" + "text": "About first item" }, { - "div_block": "About second item" + "text": "About second item" }, { - "div_block": "About third item" + "text": "About third item" + } + ], + "title": "About | Test" + }, + "content": [] + }, + { + "pathname": "index.html", + "data": { + "inline_markdown": "Home", + "title": "Home | Test", + "items": [ + { + "text": "Home first item" } ] - } + }, + "content": [] } ], "layout": [ @@ -62,7 +61,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -92,7 +93,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -111,7 +114,9 @@ }, { "type": "loop", - "reference": ["div_items"], + "reference": [ + "items" + ], "template": { "type": "element", "name": "div", @@ -125,7 +130,9 @@ "children": [ { "type": "variable", - "reference": ["div_block"] + "reference": [ + "text" + ] } ] } @@ -146,5 +153,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-markdown-variable/collection.json b/test/fixtures/sites/two-pages-markdown-variable/collection.json index 21f8056..2599689 100644 --- a/test/fixtures/sites/two-pages-markdown-variable/collection.json +++ b/test/fixtures/sites/two-pages-markdown-variable/collection.json @@ -1,25 +1,24 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Home | Test", - "h1_inline_markdown": "Home", - "div_markdown": "## Home h2\n\nHome p" - } + "inline_markdown": "About", + "markdown": "## About h2\n\nAbout p", + "title": "About | Test" + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "index.html", "data": { - "title": "About | Test", - "h1_inline_markdown": "About", - "div_markdown": "## About h2\n\nAbout p" - } + "inline_markdown": "Home", + "markdown": "## Home h2\n\nHome p", + "title": "Home | Test" + }, + "content": [] } ], "layout": [ @@ -48,7 +47,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -78,7 +79,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -97,7 +100,9 @@ }, { "type": "markdown-variable", - "reference": ["div_markdown"] + "reference": [ + "markdown" + ] }, { "type": "text", @@ -115,5 +120,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-not-loop/collection.json b/test/fixtures/sites/two-pages-not-loop/collection.json index 8f19a70..07a8ba2 100644 --- a/test/fixtures/sites/two-pages-not-loop/collection.json +++ b/test/fixtures/sites/two-pages-not-loop/collection.json @@ -1,23 +1,22 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Home | Test", - "h1_inline_markdown": "Home" - } + "inline_markdown": "About", + "title": "About | Test" + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "index.html", "data": { - "title": "About | Test", - "h1_inline_markdown": "About" - } + "inline_markdown": "Home", + "title": "Home | Test" + }, + "content": [] } ], "layout": [ @@ -46,7 +45,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -133,7 +134,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -147,5 +150,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-recursive-loop-multiple/collection.json b/test/fixtures/sites/two-pages-recursive-loop-multiple/collection.json deleted file mode 100644 index b5012c3..0000000 --- a/test/fixtures/sites/two-pages-recursive-loop-multiple/collection.json +++ /dev/null @@ -1,173 +0,0 @@ -{ - "staticFiles": [], - "collections": { - "pages": { - "pages": [ - { - "pathname": "about.html", - "data": { - "body_items": [ - { - "div_first_class": "first", - "div_second_items": [ - { - "p_test_inline_markdown": "Test 1" - } - ] - }, - { - "div_first_class": "second", - "div_second_items": [ - { - "p_test_inline_markdown": "Test 2" - }, - { - "p_test_inline_markdown": "Test 3" - } - ] - }, - { - "div_first_class": "third", - "div_second_items": [ - { - "p_test_inline_markdown": "Test 4" - }, - { - "p_test_inline_markdown": "Test 5" - }, - { - "p_test_inline_markdown": "Test 6" - } - ] - } - ] - }, - "content": [] - }, - { - "pathname": "index.html", - "data": { - "body_items": [] - }, - "content": [] - } - ], - "layout": [ - { - "type": "doctype", - "value": "html" - }, - { - "type": "element", - "name": "html", - "attrs": {}, - "children": [ - { - "type": "element", - "name": "head", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "text", - "value": "\n\t" - }, - { - "type": "element", - "name": "title", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "Test" - } - ] - }, - { - "type": "text", - "value": "\n" - } - ] - }, - { - "type": "text", - "value": "\n\n" - }, - { - "type": "element", - "name": "body", - "attrs": {}, - "children": [ - { - "type": "text", - "value": "\n\t" - }, - { - "type": "loop", - "reference": [ - "body_items" - ], - "template": { - "type": "element", - "name": "div", - "attrs": { - "class": { - "type": "variable-attribute", - "name": "class", - "reference": [ - "div_first_class" - ] - } - }, - "children": [ - { - "type": "text", - "value": "\n\t\t" - }, - { - "type": "loop", - "reference": [ - "div_second_items" - ], - "template": { - "type": "element", - "name": "p", - "attrs": { - "class": { - "type": "attribute", - "name": "class", - "value": "test" - } - }, - "children": [ - { - "type": "inline-markdown-variable", - "reference": [ - "p_test_inline_markdown" - ] - } - ] - } - }, - { - "type": "text", - "value": "\n\t" - } - ] - } - }, - { - "type": "text", - "value": "\n\n\n" - } - ] - } - ] - } - ] - } - } -} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-recursive-loop/collection.json b/test/fixtures/sites/two-pages-recursive-loop/collection.json index aa7ad6b..6088511 100644 --- a/test/fixtures/sites/two-pages-recursive-loop/collection.json +++ b/test/fixtures/sites/two-pages-recursive-loop/collection.json @@ -1,30 +1,29 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { "pathname": "about.html", "data": { - "body_items": [ + "items": [ { - "div_first_class": "first", + "first_class": "first", "div_second_items": [ { - "p_test_inline_markdown": "Test 1" + "inline_markdown": "Test 1" } ] }, { - "div_first_class": "second", "div_second_items": [ { - "p_test_inline_markdown": "Test 2" + "inline_markdown": "Test 2" }, { - "p_test_inline_markdown": "Test 3" + "inline_markdown": "Test 3" } - ] + ], + "first_class": "second" } ] }, @@ -33,7 +32,7 @@ { "pathname": "index.html", "data": { - "body_items": [] + "items": [] }, "content": [] } @@ -94,7 +93,7 @@ { "type": "loop", "reference": [ - "body_items" + "items" ], "template": { "type": "element", @@ -104,7 +103,7 @@ "type": "variable-attribute", "name": "class", "reference": [ - "div_first_class" + "first_class" ] } }, @@ -132,7 +131,7 @@ { "type": "inline-markdown-variable", "reference": [ - "p_test_inline_markdown" + "inline_markdown" ] } ] @@ -155,5 +154,6 @@ } ] } - } + }, + "staticFiles": [] } \ No newline at end of file diff --git a/test/fixtures/sites/two-pages-title-variable/collection.json b/test/fixtures/sites/two-pages-title-variable/collection.json index 926f0b3..43abb18 100644 --- a/test/fixtures/sites/two-pages-title-variable/collection.json +++ b/test/fixtures/sites/two-pages-title-variable/collection.json @@ -1,23 +1,22 @@ { - "staticFiles": [], "collections": { "pages": { "pages": [ { - "pathname": "index.html", - "content": [], + "pathname": "about.html", "data": { - "title": "Home | Test", - "h1_inline_markdown": "Home" - } + "inline_markdown": "About", + "title": "About | Test" + }, + "content": [] }, { - "pathname": "about.html", - "content": [], + "pathname": "index.html", "data": { - "title": "About | Test", - "h1_inline_markdown": "About" - } + "inline_markdown": "Home", + "title": "Home | Test" + }, + "content": [] } ], "layout": [ @@ -46,7 +45,9 @@ "children": [ { "type": "variable", - "reference": ["title"] + "reference": [ + "title" + ] } ] }, @@ -76,7 +77,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -90,5 +93,6 @@ } ] } - } -} + }, + "staticFiles": [] +} \ No newline at end of file diff --git a/test/fixtures/sites/two-pages/collection.json b/test/fixtures/sites/two-pages/collection.json index 011a22c..bea0aaa 100644 --- a/test/fixtures/sites/two-pages/collection.json +++ b/test/fixtures/sites/two-pages/collection.json @@ -1,21 +1,20 @@ { - "staticFiles": ["assets/goose.jpg"], "collections": { "pages": { "pages": [ { "pathname": "about.html", - "content": [], "data": { - "h1_inline_markdown": "About" - } + "inline_markdown": "About" + }, + "content": [] }, { "pathname": "index.html", - "content": [], "data": { - "h1_inline_markdown": "Home" - } + "inline_markdown": "Home" + }, + "content": [] } ], "layout": [ @@ -74,7 +73,9 @@ "children": [ { "type": "inline-markdown-variable", - "reference": ["h1_inline_markdown"] + "reference": [ + "inline_markdown" + ] } ] }, @@ -88,5 +89,8 @@ } ] } - } -} + }, + "staticFiles": [ + "assets/goose.jpg" + ] +} \ No newline at end of file From b7760fb0a387ed93866be5cbf8a394526da3f788 Mon Sep 17 00:00:00 2001 From: George Phillips Date: Thu, 26 Feb 2026 16:43:27 +1300 Subject: [PATCH 2/3] Add actions to PRs --- .github/workflows/ci.yml | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3a640f7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + pull_request: + branches: [main] + push: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + node-version: [18, 20, 22] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - run: npm ci + - run: npm test + + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npx tsc --noEmit + + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npx prettier --config .prettierrc 'src/**/*.ts' 'test/**/*.ts' 'test/**/*.json' --check From c80b92d4704c2382917baf122ba702f065865b7e Mon Sep 17 00:00:00 2001 From: George Phillips Date: Thu, 26 Feb 2026 16:49:01 +1300 Subject: [PATCH 3/3] Fix Tests --- .github/workflows/ci.yml | 4 +- package.json | 2 +- src/collection.ts | 24 ++++---- src/export-engines/html.ts | 38 +++++++------ src/export-engines/hugo.ts | 46 ++++++++++----- src/helpers/Data.ts | 10 ++-- src/helpers/component-builder.ts | 36 ++++++------ src/helpers/dom-diff.ts | 97 ++++++++++++++++++-------------- src/helpers/html-parser.ts | 17 +++++- src/helpers/markdown.ts | 4 +- src/helpers/node-equivalency.ts | 4 +- src/helpers/variation-map.ts | 29 +++++----- test/layout.ts | 36 ++++++++---- test/node-equivalency.ts | 6 +- tsconfig.json | 2 + 15 files changed, 212 insertions(+), 143 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a640f7..2a4235e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node-version: [18, 20, 22] + node-version: [20, 22] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -41,4 +41,4 @@ jobs: node-version: 22 cache: npm - run: npm ci - - run: npx prettier --config .prettierrc 'src/**/*.ts' 'test/**/*.ts' 'test/**/*.json' --check + - run: npx prettier --config .prettierrc 'src/**/*.ts' 'test/**/*.ts' --check diff --git a/package.json b/package.json index 95884e0..ae12c59 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ ], "engines": { "npm": ">=8.0.0", - "node": ">=18.0.0" + "node": ">=20.0.0" }, "bin": "lib/cli.js", "type": "module", diff --git a/src/collection.ts b/src/collection.ts index 1feb700..94d4a0e 100644 --- a/src/collection.ts +++ b/src/collection.ts @@ -8,7 +8,7 @@ const slugify = (_slugify as any).default as (str: string) => string; import Data from './helpers/Data.ts'; import { mergeTree } from './helpers/dom-diff.ts'; import { ASTNode } from './types.ts'; -import VariationMap, { remapData, remapASTReferences, ScopedNameMap } from './helpers/variation-map.ts'; +import VariationMap, { remapData, remapASTReferences } from './helpers/variation-map.ts'; export interface CollectionConfig { name: string; @@ -109,8 +109,7 @@ export default class Collection { await this.logger.writeLog('layout.json', JSON.stringify(current.layout, null, '\t')); for (let i = 2; i < documents.length; i++) { await this.logger.rotateLog(); - try - { + try { const next = baseDoc.diff(documents[i]); await this.logger.writeLog( `${slugify(documents[i].pathname)}.json`, @@ -151,9 +150,8 @@ export default class Collection { pages: [...current.pages, ...next.pages], layout }; - } - catch(err){ - console.error("Error hit exporting log") + } catch (err) { + console.error('Error hit exporting log'); await this.logger.rotateLog(); throw err; } @@ -162,12 +160,14 @@ export default class Collection { const displayNames = variationMap.generateDisplayNames(); const remappedLayout = remapASTReferences(current.layout, displayNames); - const remappedPages = [current.base.toJSON(), ...current.pages.map((page) => page.toJSON())] - .map((page) => ({ - ...page, - data: remapData(page.data, displayNames), - content: remapASTReferences(page.content, displayNames) - })); + const remappedPages = [ + current.base.toJSON(), + ...current.pages.map((page) => page.toJSON()) + ].map((page) => ({ + ...page, + data: remapData(page.data, displayNames), + content: remapASTReferences(page.content, displayNames) + })); return { pages: remappedPages, diff --git a/src/export-engines/html.ts b/src/export-engines/html.ts index 2f36904..f79b719 100644 --- a/src/export-engines/html.ts +++ b/src/export-engines/html.ts @@ -96,7 +96,7 @@ export default class HtmlExportEngine { throw new Error(`${node.type} render: not yet implemented`); } - renderDoctype(doctype: ASTDoctypeNode, variableScope: string): string { + renderDoctype(doctype: ASTDoctypeNode, _variableScope: string): string { return ``; } @@ -119,15 +119,18 @@ export default class HtmlExportEngine { .join(' ')}`; } - renderAttribute(attr: ASTStaticAttribute, variableScope: string): string { + renderAttribute(attr: ASTStaticAttribute, _variableScope: string): string { return [attr.name, `"${attr.value}"`].join('='); } - renderVariableAttribute(_attr: ASTVariableAttribute | ASTConditionalAttribute, variableScope: string): string { + renderVariableAttribute( + _attr: ASTVariableAttribute | ASTConditionalAttribute, + _variableScope: string + ): string { throw new Error('Not yet implemented'); } - renderConditionalAttribute(_attr: ASTConditionalAttribute, variableScope: string): string { + renderConditionalAttribute(_attr: ASTConditionalAttribute, _variableScope: string): string { throw new Error('Not yet implemented'); } @@ -138,53 +141,54 @@ export default class HtmlExportEngine { name = name.substring(5); } - // Elements that don't need closing tags - if(name === "meta" || name === "link" || name === "img"){ + // Elements that don't need closing tags + if (name === 'meta' || name === 'link' || name === 'img') { return `<${name}${this.renderAttributes(element.attrs, variableScope)}>${this.renderAST(element.children, variableScope)}`; } - // // TODO: Fix style tags + // // TODO: Fix style tags // if(name === "style"){ // return ``; // } // TODO: Fix scripts - if(name === "script"){ + if (name === 'script') { return ``; } return `<${name}${this.renderAttributes(element.attrs, variableScope)}>${this.renderAST( - element.children, variableScope + element.children, + variableScope )}`; } - renderText(text: ASTTextNode, variableScope: string): string { + renderText(text: ASTTextNode, _variableScope: string): string { return text.value; } - renderComment(text: ASTCommentNode, variableScope: string): string { + renderComment(text: ASTCommentNode, _variableScope: string): string { return ``; } - renderVariable(_node: ASTVariableNode, variableScope: string): string { + renderVariable(_node: ASTVariableNode, _variableScope: string): string { throw new Error('Variable render not yet implemented'); } - renderMarkdownVariable(_node: ASTMarkdownNode, variableScope: string): string { + renderMarkdownVariable(_node: ASTMarkdownNode, _variableScope: string): string { throw new Error('Markdown render not yet implemented'); } - renderInlineMarkdownVariable(_node: ASTInlineMarkdownNode, variableScope: string): string { + renderInlineMarkdownVariable(_node: ASTInlineMarkdownNode, _variableScope: string): string { throw new Error('Inline markdown render not yet implemented'); } - renderConditional(_node: ASTConditionalNode, variableScope: string): string { + renderConditional(_node: ASTConditionalNode, _variableScope: string): string { throw new Error('Conditional render not yet implemented'); } - renderLoop(_node: ASTLoopNode, variableScope: string): string { + renderLoop(_node: ASTLoopNode, _variableScope: string): string { throw new Error('Loop render not yet implemented'); } - renderContent(_node: ASTContentNode, variableScope: string): string { + renderContent(_node: ASTContentNode, _variableScope: string): string { throw new Error('Content render not yet implemented'); } } diff --git a/src/export-engines/hugo.ts b/src/export-engines/hugo.ts index 5ddac22..f20c277 100644 --- a/src/export-engines/hugo.ts +++ b/src/export-engines/hugo.ts @@ -21,11 +21,20 @@ function renderFrontMatter(data: Record) { } /** - * - * @param node + * + * @param node * @returns a string that is hugo formatted */ -function formatParam(node: ASTVariableNode | ASTMarkdownNode | ASTInlineMarkdownNode | ASTConditionalNode | ASTLoopNode | ASTVariableAttribute | ASTConditionalAttribute){ +function formatParam( + node: + | ASTVariableNode + | ASTMarkdownNode + | ASTInlineMarkdownNode + | ASTConditionalNode + | ASTLoopNode + | ASTVariableAttribute + | ASTConditionalAttribute +) { return node.reference.join('.').replaceAll(/([\-\:\s\@])+/g, '_'); } @@ -50,19 +59,19 @@ export default class HugoExportEngine extends HtmlExportEngine { exportLayout( layout: ASTNode[], - collection: CollectionResponse, + _collection: CollectionResponse, collectionKey: string ): FileExport { return { // TODO: this logic is currently fixed to use a default layout (list.html) pathname: `layouts/${collectionKey}/list.html`, - contents: this.renderAST(layout, ".Params.") + contents: this.renderAST(layout, '.Params.') }; } exportCollectionItem( item: Record, - collection: CollectionResponse, + _collection: CollectionResponse, collectionKey: string ): FileExport { const folder = collectionKey !== 'pages' ? `${collectionKey}/` : ''; @@ -73,10 +82,13 @@ export default class HugoExportEngine extends HtmlExportEngine { }; return { pathname: `content/${folder}${item.pathname.replace('index', '_index')}`, - contents: [renderFrontMatter(frontMatter), this.renderAST(item.content, ".Params.")].join('\n') + contents: [ + renderFrontMatter(frontMatter), + this.renderAST(item.content, '.Params.') + ].join('\n') }; } - + renderVariable(node: ASTVariableNode, variableScope: string): string { return `{{ ${variableScope}${formatParam(node)} }}`; } @@ -89,29 +101,33 @@ export default class HugoExportEngine extends HtmlExportEngine { // return `{{ .Params.${formatParam(node)} | fake_inline_markdownify_filter }}`; // TODO: fix fake_inline_markdownify_filter return `{{ ${variableScope}${formatParam(node)} | markdownify }}`; - } renderConditional(node: ASTConditionalNode, variableScope: string): string { return `{{ with ${variableScope}${formatParam(node)} }} ${this.renderASTNode( - node.template, "." + node.template, + '.' )}{{ end }}`; } renderLoop(node: ASTLoopNode, variableScope: string): string { return `{{ range ${variableScope}${formatParam(node)} }}${this.renderASTNode( - node.template, "." + node.template, + '.' )}{{ end }}`; } - renderContent(_node: ASTContentNode, variableScope: string): string { - return `{{ .Content }}`; + renderContent(_node: ASTContentNode, _variableScope: string): string { + return `{{ .Content }}`; } - renderVariableAttribute(attr: ASTVariableAttribute | ASTConditionalAttribute, variableScope: string): string { + renderVariableAttribute( + attr: ASTVariableAttribute | ASTConditionalAttribute, + variableScope: string + ): string { return [attr.name, `"{{ ${variableScope}${formatParam(attr)} }}"`].join('='); } - + renderConditionalAttribute(attr: ASTConditionalAttribute, variableScope: string): string { return `{{ with ${variableScope}${formatParam(attr)} }}{{ . }}{{ end }}`; } diff --git a/src/helpers/Data.ts b/src/helpers/Data.ts index de7fb41..a89f83e 100644 --- a/src/helpers/Data.ts +++ b/src/helpers/Data.ts @@ -28,11 +28,11 @@ function getAttributeSignature(attr: ASTAttribute | undefined): string | null { } /** - * - * @param variable string containing a variable name. + * + * @param variable string containing a variable name. * @returns a string that is formatted to work across various ssgs. */ -function formatVariable(variable: String){ +function formatVariable(variable: String) { return variable.replaceAll(/([\[\]\(\)%—,\-\:])+/g, '_'); } @@ -173,7 +173,9 @@ export default class Data { const lastElement = length > 0 ? parentElements[length - 1] : undefined; const signature = lastElement ? getElementSignature(lastElement) : ''; - const key = this.versionedVarableName(joinNameParts([prefix || '', signature, suffix || ''])); + const key = this.versionedVarableName( + joinNameParts([prefix || '', signature, suffix || '']) + ); if (this.variationMap && lastElement) { this.variationMap.record(key, { diff --git a/src/helpers/component-builder.ts b/src/helpers/component-builder.ts index 4fd31c2..7162c5b 100644 --- a/src/helpers/component-builder.ts +++ b/src/helpers/component-builder.ts @@ -104,7 +104,7 @@ function buildLoop( parentElements: ASTElementNode[], inputData: Data, outputData: Data, - config: ComponentBuilderConfig, + _config: ComponentBuilderConfig, logger: Logger, scopeHint?: string ): Loop | null { @@ -113,7 +113,7 @@ function buildLoop( let current: LoopState | null = null; let inputBaseData: Record = {}; - + const baseLiftedVariables = liftVariables(base, inputData); Object.keys(baseLiftedVariables).forEach((variableName) => { inputBaseData[variableName] = inputData.getKey(variableName); @@ -288,20 +288,24 @@ export function convertTreeToComponents( .slice(0, repeatedIndex + 1) .filter((node) => node.type === 'element') as ASTElementNode[]; - if (repeatedElements.length > 1) { - const anticipatedLoopVar = data.getVariableName(parentElements, '', 'items'); - const loopData = buildLoop( - repeatedElements, - parentElements, - existingData, - data, - config, - logger, - anticipatedLoopVar - ); - if (loopData) { - const { itemData, template } = loopData; - const variableName = anticipatedLoopVar; + if (repeatedElements.length > 1) { + const anticipatedLoopVar = data.getVariableName( + parentElements, + '', + 'items' + ); + const loopData = buildLoop( + repeatedElements, + parentElements, + existingData, + data, + config, + logger, + anticipatedLoopVar + ); + if (loopData) { + const { itemData, template } = loopData; + const variableName = anticipatedLoopVar; data.set( variableName, itemData.map((item: Data) => item.toJSON()) diff --git a/src/helpers/dom-diff.ts b/src/helpers/dom-diff.ts index d4f01a6..a3f564b 100644 --- a/src/helpers/dom-diff.ts +++ b/src/helpers/dom-diff.ts @@ -37,7 +37,7 @@ export function diffBasicNode( firstNode: ASTValueNode, secondNode: ASTValueNode, parentElements: ASTElementNode[], - logger: Logger + _logger: Logger ): ASTNode { const valuesMatch = firstNode.value.trim() === secondNode.value.trim(); if (valuesMatch) { @@ -429,10 +429,7 @@ function diffConditionalAndLoopNode( const variableName = conditionalNode.reference[0]; if (conditionalData.hasKey(variableName)) { const existingValue = conditionalData.getKey(variableName); - conditionalData.set( - variableName, - existingValue != null ? [existingValue] : [] - ); + conditionalData.set(variableName, existingValue != null ? [existingValue] : []); } const promotedLoop: ASTLoopNode = { @@ -854,32 +851,32 @@ export function mergeTree( firstEls.length === secondEls.length && nodeTreeEquivalencyScore(firstEls, secondEls) === 1; - // TODO: Object building - if (!isExactMatch) { - const anticipatedLoopVar = firstData.getVariableName( - parentElements, - '', - 'items' - ); - const loopData = buildLoop( - firstEls, - secondEls, - parentElements, - logger, - firstData.variationMap, - anticipatedLoopVar - ); - if (loopData) { - const { firstItems, secondItems, template } = loopData; - const variableName = anticipatedLoopVar; - firstData.set( - variableName, - firstItems.map((item: Data) => item.toJSON()) + // TODO: Object building + if (!isExactMatch) { + const anticipatedLoopVar = firstData.getVariableName( + parentElements, + '', + 'items' ); - secondData.set( - variableName, - secondItems.map((item: Data) => item.toJSON()) + const loopData = buildLoop( + firstEls, + secondEls, + parentElements, + logger, + firstData.variationMap, + anticipatedLoopVar ); + if (loopData) { + const { firstItems, secondItems, template } = loopData; + const variableName = anticipatedLoopVar; + firstData.set( + variableName, + firstItems.map((item: Data) => item.toJSON()) + ); + secondData.set( + variableName, + secondItems.map((item: Data) => item.toJSON()) + ); logger.log('🔄 Added loop', nodeDebugString(template)); merged.push({ @@ -921,14 +918,21 @@ export function mergeTree( nodeDebugString(other, 0, 0) ); - if (current.type === 'element' && other.type === 'loop') { - const repeatedIndex = findRepeatedIndex(firstRemainingNodes); - if (repeatedIndex > 0) { - const elements = firstRemainingNodes - .slice(0, repeatedIndex + 1) - .filter((node) => node.type === 'element') as ASTElementNode[]; - if (elements.length > 1) { - const loopData = buildLoop(elements, [], parentElements, logger, firstData.variationMap, other.reference[0]); + if (current.type === 'element' && other.type === 'loop') { + const repeatedIndex = findRepeatedIndex(firstRemainingNodes); + if (repeatedIndex > 0) { + const elements = firstRemainingNodes + .slice(0, repeatedIndex + 1) + .filter((node) => node.type === 'element') as ASTElementNode[]; + if (elements.length > 1) { + const loopData = buildLoop( + elements, + [], + parentElements, + logger, + firstData.variationMap, + other.reference[0] + ); if (loopData) { const { firstItems, template } = loopData; firstData.chainSet( @@ -970,11 +974,18 @@ export function mergeTree( .slice(0, repeatedIndex + 1) .filter((node) => node.type === 'element') as ASTElementNode[]; if (elements.length > 1) { - const loopData = buildLoop(elements, [], parentElements, logger, secondData.variationMap, current.reference[0]); - if (loopData) { - const { secondItems, template } = loopData; - secondData.chainSet( - current.reference, + const loopData = buildLoop( + elements, + [], + parentElements, + logger, + secondData.variationMap, + current.reference[0] + ); + if (loopData) { + const { secondItems, template } = loopData; + secondData.chainSet( + current.reference, secondItems.map((item: Data) => item.toJSON()) ); @@ -1011,7 +1022,7 @@ export function mergeTree( '\nvs\n', JSON.stringify(other), '?????????????????????????' - ); + ); } merged.push(diffNodes(firstData, secondData, current, other, parentElements, logger)); diff --git a/src/helpers/html-parser.ts b/src/helpers/html-parser.ts index 497b8c6..63ceaec 100644 --- a/src/helpers/html-parser.ts +++ b/src/helpers/html-parser.ts @@ -11,7 +11,16 @@ import { } from '../types.ts'; import { DocumentConfig } from '../document.ts'; -type NodeType = 'element' | 'attribute' | 'text' | 'cdata' | 'PROCESSING_INSTRUCTION_NODE' | 'comment' | 'DOCUMENT_NODE' | 'docType' | 'DOCUMENT_FRAGMENT_NODE'; +type NodeType = + | 'element' + | 'attribute' + | 'text' + | 'cdata' + | 'PROCESSING_INSTRUCTION_NODE' + | 'comment' + | 'DOCUMENT_NODE' + | 'docType' + | 'DOCUMENT_FRAGMENT_NODE'; // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType const nodeTypes = { @@ -180,7 +189,11 @@ interface HTMLProcessorResponse { contents: ASTNode[]; } -export default function htmlToAST(html: string, documentConfig: DocumentConfig, processorConfig: HtmlProcessorConfig): HTMLProcessorResponse { +export default function htmlToAST( + html: string, + documentConfig: DocumentConfig, + processorConfig: HtmlProcessorConfig +): HTMLProcessorResponse { const processor = new htmlProcessor(documentConfig.content || {}, processorConfig); const layout = processor.parse(html); diff --git a/src/helpers/markdown.ts b/src/helpers/markdown.ts index ce54555..708e8c9 100644 --- a/src/helpers/markdown.ts +++ b/src/helpers/markdown.ts @@ -1,6 +1,5 @@ import HtmlExportEngine from '../export-engines/html.ts'; import { ASTElementNode, ASTNode } from '../types.ts'; -import { findLastNonWhitespaceIndex } from './node-helper.ts'; import * as Turndown from 'turndown'; const TurndownService = (Turndown as any).default; @@ -106,8 +105,7 @@ export function isMarkdownInlineTree( } export function isMarkdownTree(nodes: ASTNode[]): boolean { - const nonWhitespaceIndex = findLastNonWhitespaceIndex(nodes); - const { lastElIndex, lastCheckedIndex } = findEndOfMarkdownIndex(nodes); + const { lastCheckedIndex } = findEndOfMarkdownIndex(nodes); return lastCheckedIndex === nodes.length - 1; } diff --git a/src/helpers/node-equivalency.ts b/src/helpers/node-equivalency.ts index f9b3f52..e0ca45e 100644 --- a/src/helpers/node-equivalency.ts +++ b/src/helpers/node-equivalency.ts @@ -139,7 +139,9 @@ export function nodeTreeEquivalencyScore(firstTree: ASTNode[], secondTree: ASTNo export function nodeEquivalencyScore(first: ASTNode, second: ASTNode): number { if (first.type === 'conditional' && second.type === 'conditional') { - return first.reference.join('') === second.reference.join('') ? (1 + nodeEquivalencyScore(first.template, second.template))/2 : 0; + return first.reference.join('') === second.reference.join('') + ? (1 + nodeEquivalencyScore(first.template, second.template)) / 2 + : 0; } if (second.type === 'conditional') { diff --git a/src/helpers/variation-map.ts b/src/helpers/variation-map.ts index 58b89de..29f5001 100644 --- a/src/helpers/variation-map.ts +++ b/src/helpers/variation-map.ts @@ -89,7 +89,8 @@ export default class VariationMap { } else { const existing = scopeMap.get(key)!; if (meta.attrName && !existing.attrName) existing.attrName = meta.attrName; - if (meta.sourceElement && !existing.sourceElement) existing.sourceElement = meta.sourceElement; + if (meta.sourceElement && !existing.sourceElement) + existing.sourceElement = meta.sourceElement; if (meta.suffix && !existing.suffix) existing.suffix = meta.suffix; } } @@ -182,11 +183,7 @@ export default class VariationMap { let chosen: string | null = null; for (const candidate of candidates) { const formatted = formatForSSG(candidate); - if ( - formatted && - !taken.has(formatted) && - formatted !== parentDisplayName - ) { + if (formatted && !taken.has(formatted) && formatted !== parentDisplayName) { chosen = formatted; break; } @@ -310,9 +307,7 @@ export default class VariationMap { } private findStableClasses(entry: VariationEntry): string[] { - const stringValues = entry.values.filter( - (v): v is string => typeof v === 'string' - ); + const stringValues = entry.values.filter((v): v is string => typeof v === 'string'); if (stringValues.length === 0) { return entry.sourceElement?.staticClasses ?? []; } @@ -333,9 +328,7 @@ export function remapData( const newKey = nameMap?.get(key) ?? key; if (Array.isArray(value)) { result[newKey] = value.map((item) => - typeof item === 'object' && item !== null - ? remapData(item, scopeMap, key) - : item + typeof item === 'object' && item !== null ? remapData(item, scopeMap, key) : item ); } else if (typeof value === 'object' && value !== null) { result[newKey] = remapData(value, scopeMap, key); @@ -375,7 +368,11 @@ function remapASTNode( return { ...node, reference: remapReference(node.reference, nameMap), - template: remapASTNode(node.template, scopeMap, innerScope) as import('../types.ts').ASTElementNode + template: remapASTNode( + node.template, + scopeMap, + innerScope + ) as import('../types.ts').ASTElementNode }; } case 'loop': { @@ -383,7 +380,11 @@ function remapASTNode( return { ...node, reference: remapReference(node.reference, nameMap), - template: remapASTNode(node.template, scopeMap, innerScope) as import('../types.ts').ASTElementNode + template: remapASTNode( + node.template, + scopeMap, + innerScope + ) as import('../types.ts').ASTElementNode }; } case 'element': diff --git a/test/layout.ts b/test/layout.ts index 658129b..e01f1e5 100644 --- a/test/layout.ts +++ b/test/layout.ts @@ -24,14 +24,14 @@ async function runTest(testName: string) { ( await fs.promises.readFile(`./test/fixtures/layouts/${testName}/a-data.json`) ).toString('utf-8') - ) + ) : {}; const bDataContents = fs.existsSync(`./test/fixtures/layouts/${testName}/b-data.json`) ? JSON.parse( ( await fs.promises.readFile(`./test/fixtures/layouts/${testName}/b-data.json`) ).toString('utf-8') - ) + ) : {}; let aData = new Data([], structuredClone(aDataContents)); let bData = new Data([], structuredClone(bDataContents)); @@ -63,16 +63,16 @@ async function runTest(testName: string) { assert.deepStrictEqual(forwards, expected); const expectedAData = JSON.parse( - (await fs.promises.readFile(`./test/fixtures/layouts/${testName}/a-data-merged.json`)).toString( - 'utf-8' - ) + ( + await fs.promises.readFile(`./test/fixtures/layouts/${testName}/a-data-merged.json`) + ).toString('utf-8') ); assert.deepStrictEqual(aData.toJSON(), expectedAData); const expectedBData = JSON.parse( - (await fs.promises.readFile(`./test/fixtures/layouts/${testName}/b-data-merged.json`)).toString( - 'utf-8' - ) + ( + await fs.promises.readFile(`./test/fixtures/layouts/${testName}/b-data-merged.json`) + ).toString('utf-8') ); assert.deepStrictEqual(bData.toJSON(), expectedBData); @@ -81,10 +81,22 @@ async function runTest(testName: string) { bData = new Data([], structuredClone(bDataContents)); const backwards = merge(b, a, bData, aData); assert.deepStrictEqual(backwards, expected); - assert.deepStrictEqual(merge(backwards, a, bData, new Data([], structuredClone(aDataContents))), expected); - assert.deepStrictEqual(merge(backwards, b, bData, new Data([], structuredClone(bDataContents))), expected); - assert.deepStrictEqual(merge(forwards, a, bData, new Data([], structuredClone(aDataContents))), expected); - assert.deepStrictEqual(merge(forwards, b, bData, new Data([], structuredClone(bDataContents))), expected); + assert.deepStrictEqual( + merge(backwards, a, bData, new Data([], structuredClone(aDataContents))), + expected + ); + assert.deepStrictEqual( + merge(backwards, b, bData, new Data([], structuredClone(bDataContents))), + expected + ); + assert.deepStrictEqual( + merge(forwards, a, bData, new Data([], structuredClone(aDataContents))), + expected + ); + assert.deepStrictEqual( + merge(forwards, b, bData, new Data([], structuredClone(bDataContents))), + expected + ); assert.deepStrictEqual(merge(forwards, backwards, bData, aData), expected); assert.deepStrictEqual(merge(forwards, forwards, bData, aData), expected); assert.deepStrictEqual(merge(backwards, forwards, bData, aData), expected); diff --git a/test/node-equivalency.ts b/test/node-equivalency.ts index 7d3fc76..1109cc4 100644 --- a/test/node-equivalency.ts +++ b/test/node-equivalency.ts @@ -1,6 +1,10 @@ import { test } from 'node:test'; import * as assert from 'node:assert/strict'; -import { isBestMatch, nodeEquivalencyScore, loopThreshold } from '../src/helpers/node-equivalency.ts'; +import { + isBestMatch, + nodeEquivalencyScore, + loopThreshold +} from '../src/helpers/node-equivalency.ts'; import { ASTElementNode, ASTNode, ASTTextNode } from '../src/types.ts'; import { TestLogger } from './helpers/test-logger.ts'; diff --git a/tsconfig.json b/tsconfig.json index 370ff44..54f2c00 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,8 @@ "moduleResolution": "nodenext", "rewriteRelativeImportExtensions": true, "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "outDir": "./lib" }, "include": ["src"],