Skip to content

Commit b104ce4

Browse files
committed
Add the option to preserve duplicate elements
1 parent 5861957 commit b104ce4

File tree

2 files changed

+23
-11
lines changed

2 files changed

+23
-11
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,12 @@ Output:
5858
<a><img src="https://example.com/image" id="logo"></a>
5959
</body>
6060
```
61+
62+
63+
## Options
64+
65+
An options object can be passed as the second argument to `cssToHtml()` to customize the behaviour of the HTML generator.
66+
67+
| Option | Values | Description |
68+
| :----------- | :------------------- | :---------- |
69+
| `duplicates` | `preserve`, `remove` | |

src/Generator.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
type Combinator = '>' | '~' | '+';
22

33
interface Options {
4+
duplicates?: 'preserve' | 'remove';
45
}
56

67
/**
@@ -92,17 +93,19 @@ export function cssToHtml(css: CSSRuleList | string, options: Options = {}): HTM
9293
};
9394

9495
function addElementToOutput (): void {
95-
// If an identical element already exists, skip adding the new element.
96-
const existingElements = Array.from(
97-
(descriptor.combinator === '>' ?
98-
descriptor.previousElement?.children :
99-
descriptor.previousElement?.parentElement?.children) ?? output.children
100-
);
101-
const matchingElement = existingElements.find((element) => descriptor.matchesElement(element));
102-
if (matchingElement) {
103-
// Reference the matching element so properties such as `content` can cascade.
104-
descriptor.previousElement = matchingElement as HTMLElement;
105-
return;
96+
if (options.duplicates !== 'preserve') {
97+
// If an identical element already exists, skip adding the new element.
98+
const existingElements = Array.from(
99+
(descriptor.combinator === '>' ?
100+
descriptor.previousElement?.children :
101+
descriptor.previousElement?.parentElement?.children) ?? output.children
102+
);
103+
const matchingElement = existingElements.find((element) => descriptor.matchesElement(element));
104+
if (matchingElement) {
105+
// Reference the matching element so properties such as `content` can cascade.
106+
descriptor.previousElement = matchingElement as HTMLElement;
107+
return;
108+
}
106109
}
107110
// Create the new element.
108111
const newElement = document.createElement(descriptor.tag || 'div');

0 commit comments

Comments
 (0)