Skip to content

Commit

Permalink
feat: basic functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
cossssmin committed Nov 16, 2024
1 parent d25dee0 commit 0b8e6d7
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 12 deletions.
28 changes: 25 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,31 @@
export default (options = {}) => tree => {
// Accept options and set defaults
options.foo = options.foo || {}
options.attributes = options.attributes || ['prevent-widows', 'no-widows']

const process = node => {
// Write your code...
const process = (node, shouldReplace = false) => {
// If node is a string and the parent has the attribute, replace the last space with a non-breaking space
if (typeof node === 'string') {
return shouldReplace ? node.replace(/ ([^ ]+)$/, ' $1') : node
}

// If node is a tag, check if it has one of the predefined attributes
if (node.tag && node.attrs) {
for (const attr of options.attributes) {
if (attr in node.attrs) {
// Delete the attribute from node.attrs
delete node.attrs[attr]

shouldReplace = true

break
}
}
}

// If `content` is an array, recursively process each item
if (Array.isArray(node.content)) {
node.content = node.content.map(child => process(child, shouldReplace))
}

// Return the node
return node
Expand Down
6 changes: 5 additions & 1 deletion test/expected/basic.html
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
<!doctype html>
skips unmarked strings

<p class="one two">
<span>lorem ipsum&nbsp;dolor</span>
</p>
6 changes: 5 additions & 1 deletion test/fixtures/basic.html
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
<!doctype html>
skips unmarked strings

<p class="one two" prevent-widows>
<span>lorem ipsum dolor</span>
</p>
7 changes: 0 additions & 7 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {fileURLToPath} from 'node:url'
import {test, expect} from 'vitest'
import posthtml from 'posthtml'
import plugin from '../lib/index.js'
import asyncPlugin from '../lib/index-async.js'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

Expand All @@ -25,9 +24,3 @@ const process = (name, options, log = false) => {
test('Basic', () => {
return process('basic')
})

test('Async plugin', () => {
return posthtml([asyncPlugin()])
.process(fixture('basic'))
.then(result => expect(clean(result.html)).toEqual(expected('basic')))
})

0 comments on commit 0b8e6d7

Please sign in to comment.