Skip to content

Commit bf800f9

Browse files
committed
fix: add more info to attr value / statement validity
1 parent e4df379 commit bf800f9

2 files changed

Lines changed: 24 additions & 6 deletions

File tree

.changeset/eleven-chicken-share.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"htmljs-parser": patch
3+
---
4+
5+
Expose extra information about statement and attr value validity.

src/util/validators.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,13 @@ const ROOT_RANGE = {
2828
end: 0,
2929
};
3030

31-
export function isValidStatement(code: string): boolean {
31+
export enum Validity {
32+
invalid,
33+
valid,
34+
enclosed,
35+
}
36+
37+
export function isValidStatement(code: string): Validity {
3238
return isValid(code, true, prepareStatement);
3339
}
3440

@@ -38,7 +44,7 @@ function prepareStatement(expr: STATE.ExpressionMeta) {
3844
expr.consumeIndentedContent = true;
3945
}
4046

41-
export function isValidAttrValue(code: string, concise: boolean): boolean {
47+
export function isValidAttrValue(code: string, concise: boolean): Validity {
4248
return isValid(code, concise, prepareAttrValue);
4349
}
4450

@@ -54,7 +60,7 @@ function isValid(
5460
data: string,
5561
concise: boolean,
5662
prepare: (expr: STATE.ExpressionMeta, concise: boolean) => void,
57-
) {
63+
): Validity {
5864
const parser = new Parser({});
5965
const maxPos = (parser.maxPos = data.length);
6066
parser.pos = 0;
@@ -68,6 +74,7 @@ function isValid(
6874
parser.activeState = ROOT_STATE;
6975
parser.activeRange = ROOT_RANGE;
7076
const expr = parser.enterState(STATE.EXPRESSION);
77+
let isEnclosed = true;
7178
prepare(expr, concise);
7279

7380
while (parser.pos < maxPos) {
@@ -80,23 +87,29 @@ function isValid(
8087
code === CODE.CARRIAGE_RETURN &&
8188
data.charCodeAt(parser.pos + 1) === CODE.NEWLINE
8289
) {
90+
if (isEnclosed && !expr.groupStack.length) isEnclosed = false;
8391
parser.forward = 2;
8492
parser.activeState.eol.call(parser, 2, parser.activeRange);
8593
} else {
94+
if (isEnclosed && !expr.groupStack.length) isEnclosed = false;
8695
parser.forward = 1;
8796
parser.activeState.char.call(parser, code, parser.activeRange);
8897
}
8998

9099
if (parser.activeRange === ROOT_RANGE) {
91-
return false;
100+
return Validity.invalid;
92101
}
93102

94103
parser.pos += parser.forward;
95104
}
96105

97-
return (
106+
if (
98107
parser.pos === maxPos &&
99108
parser.activeRange === expr &&
100109
!expr.groupStack.length
101-
);
110+
) {
111+
return isEnclosed ? Validity.enclosed : Validity.valid;
112+
}
113+
114+
return Validity.invalid;
102115
}

0 commit comments

Comments
 (0)