@mgdis/core-ui-helpers 1.3.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,7 @@
10
10
  slotRelocation: true};
11
11
 
12
12
  /*
13
- Stencil Client Platform v4.43.5 | MIT Licensed | https://stenciljs.com
13
+ Stencil Client Platform v4.45.1 | MIT Licensed | https://stenciljs.com
14
14
  */
15
15
 
16
16
 
@@ -26,6 +26,7 @@
26
26
  return void 0;
27
27
  };
28
28
  var isMemberInElement = (elm, memberName) => memberName in elm;
29
+ var consoleError = (e, el) => (0, console.error)(e, el);
29
30
  var XLINK_NS = "http://www.w3.org/1999/xlink";
30
31
  var win = typeof window !== "undefined" ? window : {};
31
32
  var plt = {
@@ -78,7 +79,7 @@
78
79
  slottedNodes.push(childNode);
79
80
  if (typeof slotName !== "undefined") return slottedNodes;
80
81
  }
81
- slottedNodes = [...slottedNodes, ...getHostSlotNodes(childNode.childNodes, hostName, slotName)];
82
+ slottedNodes = [...slottedNodes, ...getHostSlotNodes(internalCall(childNode, "childNodes"), hostName, slotName)];
82
83
  }
83
84
  return slottedNodes;
84
85
  }
@@ -180,6 +181,11 @@
180
181
  } else if (child != null && typeof child !== "boolean") {
181
182
  if (simple = !isComplexType(child)) {
182
183
  child = String(child);
184
+ } else if (child.$flags$ === void 0) {
185
+ {
186
+ consoleError("Invalid vNode child");
187
+ }
188
+ continue;
183
189
  }
184
190
  if (simple && lastSimple) {
185
191
  vNodeChildren[vNodeChildren.length - 1].$text$ += child;
@@ -342,7 +348,7 @@
342
348
  }
343
349
  }
344
350
  if (newValue == null || newValue === false) {
345
- if (newValue !== false || elm.getAttribute(memberName) === "") {
351
+ if (newValue !== false || elm.getAttribute(memberName) === "" || flags & 4 /* isHost */ && !isEnumeratedAttribute(memberName)) {
346
352
  if (xlink) {
347
353
  elm.removeAttributeNS(XLINK_NS, memberName);
348
354
  } else {
@@ -359,6 +365,8 @@
359
365
  }
360
366
  }
361
367
  };
368
+ var ENUMERATED_ATTRIBUTES = /* @__PURE__ */ new Set(["draggable", "contenteditable", "spellcheck"]);
369
+ var isEnumeratedAttribute = (attrName) => ENUMERATED_ATTRIBUTES.has(attrName) || attrName.startsWith("aria-");
362
370
  var parseClassListRegex = /\s/;
363
371
  var parseClassList = (value) => {
364
372
  if (typeof value === "object" && value && "baseVal" in value) {
@@ -650,7 +658,7 @@
650
658
  if (idxInOld >= 0) {
651
659
  elmToMove = oldCh[idxInOld];
652
660
  if (elmToMove.$tag$ !== newStartVnode.$tag$) {
653
- node = createElm(oldCh && oldCh[newStartIdx], newVNode2, idxInOld);
661
+ node = createElm(oldCh && oldCh[newStartIdx], newVNode2, newStartIdx);
654
662
  } else {
655
663
  patch(elmToMove, newStartVnode, isInitialRender);
656
664
  oldCh[idxInOld] = void 0;
@@ -755,7 +763,10 @@
755
763
  const slotName = childNode["s-sn"];
756
764
  for (j = hostContentNodes.length - 1; j >= 0; j--) {
757
765
  node = hostContentNodes[j];
758
- if (!node["s-cn"] && !node["s-nr"] && node["s-hn"] !== childNode["s-hn"] && (!node["s-sh"] || node["s-sh"] !== childNode["s-hn"])) {
766
+ if (!node["s-cn"] && !node["s-nr"] && node["s-hn"] !== childNode["s-hn"] && // let an exact named-slot match override a stale default-slot claim. Skip this for
767
+ // `slotName === ''` itself - a matched default node's cached `s-sn` is `''` too, which
768
+ // would trivially "match" on every re-render and force pointless re-insertion.
769
+ (!node["s-sh"] || node["s-sh"] !== childNode["s-hn"] || slotName !== "" && getSlotName(node) === slotName)) {
759
770
  if (isNodeLocatedInSlot(node, slotName)) {
760
771
  let relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
761
772
  checkSlotFallbackVisibility = true;
@@ -825,7 +836,7 @@
825
836
  return newNode;
826
837
  }
827
838
  }
828
- if (parent.__insertBefore) {
839
+ if ((parent == null ? void 0 : parent.__insertBefore)) {
829
840
  return parent.__insertBefore(newNode, reference);
830
841
  } else {
831
842
  return parent == null ? void 0 : parent.insertBefore(newNode, reference);
@@ -1008,7 +1019,7 @@
1008
1019
  ];
1009
1020
 
1010
1021
  /**
1011
- * Defined by state.js and configuration.
1022
+ * Defined per formatting operation from configuration.
1012
1023
  *
1013
1024
  * CONTENT_IGNORE_PLACEHOLDER
1014
1025
  * SELF_CLOSING_PLACEHOLDER
@@ -1016,46 +1027,110 @@
1016
1027
  */
1017
1028
 
1018
1029
  /**
1019
- * @typedef {object} Constants
1030
+ * @typedef {object} HtmlfyConstants
1020
1031
  * @property {string} CONTENT_IGNORE_PLACEHOLDER
1021
1032
  * @property {string} SELF_CLOSING_PLACEHOLDER
1022
1033
  * @property {string} ATTRIBUTE_IGNORE_PLACEHOLDER
1023
1034
  */
1035
+
1024
1036
  /**
1025
- * @typedef {object} State
1026
- * @property {boolean} checked_html - If passed in HTML has been checked for HTML within it.
1027
- * @property {import("htmlfy").Config} config - Validated configuration.
1028
- * @property {boolean} ignored
1029
- * @property {Constants} constants - Constant strings, influenced by ignore_with.
1037
+ * Create the placeholders used during one formatting operation.
1038
+ *
1039
+ * @param {string} [ignore_with]
1040
+ * @returns {HtmlfyConstants}
1030
1041
  */
1042
+ const createConstants = (ignore_with = CONFIG.ignore_with) => ({
1043
+ CONTENT_IGNORE_PLACEHOLDER: `${ignore_with}_`,
1044
+ SELF_CLOSING_PLACEHOLDER: `${ignore_with}/_>`,
1045
+ ATTRIBUTE_IGNORE_PLACEHOLDER: `${ignore_with}=_`
1046
+ });
1047
+
1048
+ const DEFAULT_CONSTANTS = createConstants();
1031
1049
 
1032
1050
  /**
1033
- * @type State
1034
- *
1035
- * `constants` prefixes and suffixes must be in sync with those in utils.js
1051
+ * Visit complete tags without treating brackets inside quoted attributes as boundaries.
1052
+ * Returning true from the visitor stops the scan.
1053
+ *
1054
+ * @param {string} content
1055
+ * @param {(tag: string, start: number, end: number) => boolean | void} visitor
1056
+ * @returns {boolean}
1036
1057
  */
1037
- const state = {
1038
- checked_html: false,
1039
- config: { ...CONFIG },
1040
- ignored: false,
1041
- constants: {
1042
- CONTENT_IGNORE_PLACEHOLDER: `${CONFIG.ignore_with}_`,
1043
- SELF_CLOSING_PLACEHOLDER: `${CONFIG.ignore_with}/_>`,
1044
- ATTRIBUTE_IGNORE_PLACEHOLDER: `${CONFIG.ignore_with}=_`
1058
+ const scanTags = (content, visitor) => {
1059
+ let tag_start = -1;
1060
+ let quote = '';
1061
+
1062
+ for (let index = 0; index < content.length; index++) {
1063
+ const character = content[index];
1064
+
1065
+ if (tag_start === -1) {
1066
+ if (character === '<') tag_start = index;
1067
+ continue
1068
+ }
1069
+
1070
+ if (quote) {
1071
+ if (character === quote) quote = '';
1072
+ continue
1073
+ }
1074
+
1075
+ if (character === '"' || character === "'") {
1076
+ quote = character;
1077
+ } else if (character === '<') {
1078
+ tag_start = index;
1079
+ } else if (character === '>') {
1080
+ if (visitor(content.slice(tag_start, index + 1), tag_start, index + 1)) return true
1081
+ tag_start = -1;
1082
+ }
1045
1083
  }
1084
+
1085
+ return false
1046
1086
  };
1047
1087
 
1048
1088
  /**
1049
- *
1050
- * @returns {State}
1089
+ * Parse the name of an opening tag and return its end offset within the tag.
1090
+ *
1091
+ * @param {string} tag
1092
+ * @returns {{ name: string, name_end: number } | undefined}
1051
1093
  */
1052
- const getState = () => state;
1094
+ const getOpeningTag = (tag) => {
1095
+ let name_start = 1;
1096
+ while (/\s/.test(tag[name_start] || '')) name_start++;
1097
+ if (!/[A-Za-z]/.test(tag[name_start] || '')) return
1098
+
1099
+ let name_end = name_start + 1;
1100
+ while (name_end < tag.length && !/[\s/>]/.test(tag[name_end])) name_end++;
1101
+
1102
+ const name = tag.slice(name_start, name_end);
1103
+ if (!/^[A-Za-z][A-Za-z0-9:._-]*$/.test(name)) return
1104
+
1105
+ return { name, name_end }
1106
+ };
1053
1107
 
1054
1108
  /**
1055
- *
1056
- * @param {Partial<State>} new_state
1109
+ * Transform complete opening tags while preserving all content between them.
1110
+ *
1111
+ * @param {string} content
1112
+ * @param {(tag: string, name: string, name_end: number) => string} transform
1113
+ * @returns {string}
1057
1114
  */
1058
- const setState = (new_state) => Object.assign(state, new_state);
1115
+ const transformOpeningTags = (content, transform) => {
1116
+ const chunks = [];
1117
+ let previous_end = 0;
1118
+
1119
+ scanTags(content, (tag, start, end) => {
1120
+ const opening_tag = getOpeningTag(tag);
1121
+ if (!opening_tag) return
1122
+
1123
+ chunks.push(
1124
+ content.slice(previous_end, start),
1125
+ transform(tag, opening_tag.name, opening_tag.name_end)
1126
+ );
1127
+ previous_end = end;
1128
+ });
1129
+
1130
+ if (chunks.length === 0) return content
1131
+ chunks.push(content.slice(previous_end));
1132
+ return chunks.join('')
1133
+ };
1059
1134
 
1060
1135
  /**
1061
1136
  * Checks if content contains at least one HTML element or custom HTML element.
@@ -1080,11 +1155,30 @@
1080
1155
  * @returns {boolean} A boolean.
1081
1156
  */
1082
1157
  const isHtml = (content) => {
1083
- setState({ checked_html: true });
1158
+ const paired_elements = new Set();
1159
+ const standard_element = /^[A-Za-z][A-Za-z0-9]*$/;
1160
+ const namespaced_element = /^(?:[A-Za-z][A-Za-z0-9]*:)[A-Za-z][A-Za-z0-9]*$/;
1161
+ const custom_element = /^(?:[a-z][a-z0-9._]*:)?[a-z][a-z0-9._]*-[a-z0-9._-]+$/;
1162
+
1163
+ return scanTags(content, (tag) => {
1164
+ if (tag.startsWith('</')) {
1165
+ const name = tag.slice(2, -1);
1166
+ return paired_elements.has(name)
1167
+ }
1168
+
1169
+ const opening_tag = getOpeningTag(tag);
1170
+ if (!opening_tag) return false
1171
+
1172
+ const suffix_start = tag[opening_tag.name_end];
1173
+ if (!(suffix_start === '>' || /\s/.test(suffix_start) || (suffix_start === '/' && tag[opening_tag.name_end + 1] === '>')))
1174
+ return false
1084
1175
 
1085
- return /<(?:[A-Za-z]+[A-Za-z0-9]*)(?:\s+.*?)*?\/{0,1}>/.test(content) ||
1086
- /<(?<Element>(?:[A-Za-z]+[A-Za-z0-9]*:)?(?:[A-Za-z]+[A-Za-z0-9]*))(?:\s+.*?)*?>(?:.|\n)*?<\/{1}\k<Element>>/.test(content) ||
1087
- /<(?<Element>(?:[a-z][a-z0-9._]*:)?[a-z][a-z0-9._]*-[a-z0-9._-]+)(?:\s+.*?)*?>(?:.|\n)*?<\/{1}\k<Element>>/.test(content)
1176
+ if (standard_element.test(opening_tag.name)) return true
1177
+ if (namespaced_element.test(opening_tag.name) || custom_element.test(opening_tag.name))
1178
+ paired_elements.add(opening_tag.name);
1179
+
1180
+ return false
1181
+ })
1088
1182
  };
1089
1183
 
1090
1184
  /**
@@ -1128,27 +1222,15 @@
1128
1222
  * @returns {import('htmlfy').Config}
1129
1223
  */
1130
1224
  const mergeConfig = (default_config, config) => {
1131
- const validated_config = mergeObjects(default_config, config);
1132
-
1133
- /* Below `constants` prefixes and suffixes must be in sync with those in state.js */
1134
- setState({
1135
- config: validated_config,
1136
- constants: {
1137
- CONTENT_IGNORE_PLACEHOLDER: `${validated_config.ignore_with}_`,
1138
- SELF_CLOSING_PLACEHOLDER: `${validated_config.ignore_with}/_>`,
1139
- ATTRIBUTE_IGNORE_PLACEHOLDER: `${validated_config.ignore_with}=_`
1140
- }
1141
- });
1142
- return validated_config
1225
+ return mergeObjects(default_config, config)
1143
1226
  };
1144
1227
 
1145
1228
  /**
1146
1229
  *
1147
- * @param {string} html
1230
+ * @param {string} html
1231
+ * @param {HtmlfyConstants} [constants]
1148
1232
  */
1149
- const protectAttributes = (html) => {
1150
- const { constants } = getState();
1151
-
1233
+ const protectAttributes = (html, constants = DEFAULT_CONSTANTS) => {
1152
1234
  html = html.replace(/<[\w:\-]+([^>]*[^\/])>/g, (/** @type {string} */match, /** @type {any} */capture) => {
1153
1235
  return match.replace(capture, (match) => {
1154
1236
  return match
@@ -1163,11 +1245,10 @@
1163
1245
 
1164
1246
  /**
1165
1247
  *
1166
- * @param {string} html
1248
+ * @param {string} html
1249
+ * @param {HtmlfyConstants} [constants]
1167
1250
  */
1168
- const protectContent = (html) => {
1169
- const { constants } = getState();
1170
-
1251
+ const protectContent = (html, constants = DEFAULT_CONSTANTS) => {
1171
1252
  return html
1172
1253
  .replace(/\n/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!')
1173
1254
  .replace(/\r/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!')
@@ -1176,11 +1257,11 @@
1176
1257
 
1177
1258
  /**
1178
1259
  *
1179
- * @param {string} html
1260
+ * @param {string} html
1261
+ * @param {HtmlfyConstants} [constants]
1180
1262
  */
1181
- const finalProtectContent = (html) => {
1263
+ const finalProtectContent = (html, constants = DEFAULT_CONSTANTS) => {
1182
1264
  const regex = /\s*<([a-zA-Z0-9:-]+)[^>]*>\n\s*<\/\1>(?=\n[ ]*[^\n]*__!i-£___£%__[^\n]*\n)(\n[ ]*\S[^\n]*\n)|<([a-zA-Z0-9:-]+)[^>]*>(?=\n[ ]*[^\n]*__!i-£___£%__[^\n]*\n)(\n[ ]*\S[^\n]*\n\s*)<\/\3>/g;
1183
- const { constants } = getState();
1184
1265
 
1185
1266
  return html
1186
1267
  .replace(regex, (/** @type {string} */match, p1, p2, p3, p4) => {
@@ -1201,22 +1282,39 @@
1201
1282
  /**
1202
1283
  * Replace html brackets with ignore string.
1203
1284
  *
1204
- * @param {string} html
1285
+ * @param {string} html
1286
+ * @param {HtmlfyConstants} [constants]
1205
1287
  * @returns {string}
1206
1288
  */
1207
- const setIgnoreAttribute = (html) => {
1208
- const regex = /<([A-Za-z][A-Za-z0-9]*|[a-z][a-z0-9._]*-[a-z0-9._-]+)((?:\s+[A-Za-z0-9_-]+="[^"]*"|\s*[a-z]*)*)>/g;
1209
- const { constants } = getState();
1289
+ const setIgnoreAttribute = (html, constants = DEFAULT_CONSTANTS) => {
1290
+ // Most documents do not contain HTML-like brackets inside attribute values.
1291
+ if (!/=\s*(?:"[^"]*[<>][^"]*"|'[^']*[<>][^']*')/.test(html)) return html
1292
+
1293
+ return transformOpeningTags(html, (tag, name, name_end) => {
1294
+ let quote = '';
1295
+ let previous_end = 0;
1296
+ const chunks = [];
1297
+
1298
+ for (let index = name_end; index < tag.length - 1; index++) {
1299
+ const character = tag[index];
1300
+
1301
+ if (!quote && (character === '"' || character === "'")) {
1302
+ quote = character;
1303
+ } else if (quote && character === quote) {
1304
+ quote = '';
1305
+ } else if (quote && (character === '<' || character === '>')) {
1306
+ chunks.push(
1307
+ tag.slice(previous_end, index),
1308
+ constants.ATTRIBUTE_IGNORE_PLACEHOLDER + (character === '<' ? 'lt!' : 'gt!')
1309
+ );
1310
+ previous_end = index + 1;
1311
+ }
1312
+ }
1210
1313
 
1211
- html = html.replace(regex, (/** @type {string} */match, p1, p2) => {
1212
- return match.replace(p2, (match) => {
1213
- return match
1214
- .replace(/</g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'lt!')
1215
- .replace(/>/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'gt!')
1216
- })
1217
- });
1218
-
1219
- return html
1314
+ if (chunks.length === 0) return tag
1315
+ chunks.push(tag.slice(previous_end));
1316
+ return chunks.join('')
1317
+ })
1220
1318
  };
1221
1319
 
1222
1320
  /**
@@ -1242,11 +1340,10 @@
1242
1340
 
1243
1341
  /**
1244
1342
  *
1245
- * @param {string} html
1343
+ * @param {string} html
1344
+ * @param {HtmlfyConstants} [constants]
1246
1345
  */
1247
- const unprotectAttributes = (html) => {
1248
- const { constants } = getState();
1249
-
1346
+ const unprotectAttributes = (html, constants = DEFAULT_CONSTANTS) => {
1250
1347
  html = html.replace(/<[\w:\-]+([^>]*[^\/])>/g, (/** @type {string} */match, /** @type {any} */capture) => {
1251
1348
  return match.replace(capture, (match) => {
1252
1349
  return match
@@ -1261,11 +1358,10 @@
1261
1358
 
1262
1359
  /**
1263
1360
  *
1264
- * @param {string} html
1361
+ * @param {string} html
1362
+ * @param {HtmlfyConstants} [constants]
1265
1363
  */
1266
- const unprotectContent = (html) => {
1267
- const { constants } = getState();
1268
-
1364
+ const unprotectContent = (html, constants = DEFAULT_CONSTANTS) => {
1269
1365
  html = html.replace(new RegExp(`.*${constants.CONTENT_IGNORE_PLACEHOLDER}[a-z]{2}!.*`, "g"), (/** @type {string} */match) => {
1270
1366
  return match.replace(new RegExp(`${constants.CONTENT_IGNORE_PLACEHOLDER}[a-z]{2}!`, "g"), (match) => {
1271
1367
  return match
@@ -1281,13 +1377,13 @@
1281
1377
  /**
1282
1378
  * Replace ignore string with html brackets.
1283
1379
  *
1284
- * @param {string} html
1380
+ * @param {string} html
1381
+ * @param {HtmlfyConstants} [constants]
1285
1382
  * @returns {string}
1286
1383
  */
1287
- const unsetIgnoreAttribute = (html) => {
1384
+ const unsetIgnoreAttribute = (html, constants = DEFAULT_CONSTANTS) => {
1288
1385
  /* Regex to find opening tags and capture their attributes. */
1289
1386
  const tagRegex = /<([\w:\-]+)([^>]*)>/g;
1290
- const { constants } = getState();
1291
1387
  const escapedIgnoreString = constants.ATTRIBUTE_IGNORE_PLACEHOLDER.replace(
1292
1388
  /[-\/\\^$*+?.()|[\]{}]/g,
1293
1389
  "\\$&"
@@ -1320,6 +1416,8 @@
1320
1416
  */
1321
1417
  const validateConfig = (config) => {
1322
1418
  if (typeof config !== 'object') throw new Error('Config must be an object.')
1419
+
1420
+ config = { ...config };
1323
1421
 
1324
1422
  const default_config = { ...CONFIG };
1325
1423
 
@@ -1334,7 +1432,6 @@
1334
1432
  );
1335
1433
 
1336
1434
  if (config_empty) {
1337
- setState({ config: default_config });
1338
1435
  return default_config
1339
1436
  }
1340
1437
 
@@ -1392,113 +1489,165 @@
1392
1489
  * @param {string} text
1393
1490
  * @param {number} width
1394
1491
  * @param {string} indent
1492
+ * @param {HtmlfyConstants} [constants]
1395
1493
  */
1396
- const wordWrap = (text, width, indent) => {
1494
+ const wordWrap = (text, width, indent, constants = DEFAULT_CONSTANTS) => {
1397
1495
  const words = text.trim().split(/\s+/);
1398
1496
 
1399
1497
  if (words.length === 0 || (words.length === 1 && words[0] === ''))
1400
1498
  return ""
1401
1499
 
1500
+ /** @type {string[]} */
1402
1501
  const lines = [];
1403
- let current_line = "";
1404
- const padding_string = indent;
1502
+ /** @type {string[]} */
1503
+ const current_words = [];
1504
+ let current_length = 0;
1505
+
1506
+ const flushLine = () => {
1507
+ if (current_words.length === 0) return
1508
+ lines.push(indent + current_words.join(' '));
1509
+ current_words.length = 0;
1510
+ current_length = 0;
1511
+ };
1405
1512
 
1406
- words.forEach((word) => {
1407
- if (word === "") return
1513
+ for (const word of words) {
1514
+ if (word === "") continue
1408
1515
 
1409
1516
  if (word.length >= width) {
1410
- /* If there's content on the current line, push it first with correct padding. */
1411
- if (current_line !== "")
1412
- lines.push(lines.length === 0 ? indent + current_line : padding_string + current_line);
1413
-
1414
- /* Push a long word on its own line with correct padding. */
1415
- lines.push(lines.length === 0 ? indent + word : padding_string + word);
1416
- current_line = ""; // Reset current line
1417
- return // Move to the next word
1517
+ flushLine();
1518
+ lines.push(indent + word);
1519
+ continue
1418
1520
  }
1419
1521
 
1420
- /* Check if adding the next word exceeds the wrap width. */
1421
- const test_line = current_line === "" ? word : current_line + " " + word;
1422
-
1423
- if (test_line.length <= width) {
1424
- current_line = test_line;
1522
+ const next_length = current_length + (current_words.length === 0 ? 0 : 1) + word.length;
1523
+ if (next_length <= width) {
1524
+ current_words.push(word);
1525
+ current_length = next_length;
1425
1526
  } else {
1426
- /* Word doesn't fit, finish the current line and push it. */
1427
- if (current_line !== "") {
1428
- /* Add padding based on whether it's the first line added or not. */
1429
- lines.push(lines.length === 0 ? indent + current_line : padding_string + current_line);
1430
- }
1431
- /* Start a new line with the current word. */
1432
- current_line = word;
1527
+ flushLine();
1528
+ current_words.push(word);
1529
+ current_length = word.length;
1433
1530
  }
1434
- });
1531
+ }
1435
1532
 
1436
- /* Add the last remaining line with appropriate padding. */
1437
- if (current_line !== "")
1438
- lines.push(lines.length === 0 ? indent + current_line : padding_string + current_line);
1533
+ flushLine();
1439
1534
 
1440
1535
  const result = lines.join("\n");
1441
1536
 
1442
- return protectContent(result)
1537
+ return protectContent(result, constants)
1443
1538
  };
1444
1539
 
1540
+ const IGNORE_MARKER_PREFIX = "___HTMLFY_SPECIAL_IGNORE_MARKER_";
1541
+ const IGNORE_MARKER_REGEX = /___HTMLFY_SPECIAL_IGNORE_MARKER_\d+___/g;
1542
+ const TEXTAREA_MARKER_PREFIX = "___HTMLFY_TEXTAREA_MARKER_";
1543
+ const TEXTAREA_MARKER_REGEX = /___HTMLFY_TEXTAREA_MARKER_\d+___/g;
1544
+
1445
1545
  /**
1446
- * Extract any HTML blocks to be ignored,
1447
- * and replace them with a placeholder
1448
- * for re-insertion later.
1449
- *
1450
- * @param {string} html
1451
- * @returns {{ html_with_markers: string, extracted_map: Map<any,any> }}
1546
+ * Extract the contents of matching elements in one traversal.
1547
+ *
1548
+ * @param {string} html
1549
+ * @param {Set<string>} names
1550
+ * @param {string} marker_prefix
1551
+ * @param {(content: string) => string} [transform]
1552
+ * @returns {{ html_with_markers: string, extracted_map: Map<string,string> }}
1452
1553
  */
1453
- function extractIgnoredBlocks(html) {
1454
- setState({ ignored: true });
1455
- const config = (getState()).config;
1456
- let current_html = html;
1554
+ const extractBlocks = (html, names, marker_prefix, transform = content => content) => {
1457
1555
  const extracted_blocks = new Map();
1556
+ const chunks = [];
1458
1557
  let marker_id = 0;
1459
- const MARKER_PREFIX = "___HTMLFY_SPECIAL_IGNORE_MARKER_";
1558
+ let previous_end = 0;
1460
1559
 
1461
- for (const tag of config.ignore) {
1462
- /* Ensure tag is escaped if it can contain regex special chars. */
1463
- const safe_tag_name = tag.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
1560
+ /** @type {{ name: string, content_start: number } | undefined} */
1561
+ let active_block;
1562
+ let tag_start = -1;
1563
+ let quote = '';
1464
1564
 
1465
- const regex = new RegExp(
1466
- `(<\\s*${safe_tag_name}[^>]*>)(.*?)(<\\s*\/\\s*${safe_tag_name}\\s*>)`,
1467
- "gs" // global and dotAll
1468
- );
1565
+ for (let index = 0; index < html.length; index++) {
1566
+ const character = html[index];
1469
1567
 
1470
- /** @type RegExpExecArray | null */
1471
- let match;
1568
+ if (active_block) {
1569
+ if (character !== '<') continue
1472
1570
 
1473
- /**
1474
- * @type {{ start: number; end: number; marker: string }[]}
1475
- */
1476
- const replacements = [];
1571
+ let closing_index = index + 1;
1572
+ while (/\s/.test(html[closing_index] || '')) closing_index++;
1573
+ if (html[closing_index] !== '/') continue
1574
+
1575
+ closing_index++;
1576
+ while (/\s/.test(html[closing_index] || '')) closing_index++;
1577
+ if (!html.startsWith(active_block.name, closing_index)) continue
1578
+
1579
+ closing_index += active_block.name.length;
1580
+ while (/\s/.test(html[closing_index] || '')) closing_index++;
1581
+ if (html[closing_index] !== '>') continue
1582
+
1583
+ const marker = `${marker_prefix}${marker_id++}___`;
1584
+ chunks.push(html.slice(previous_end, active_block.content_start), marker);
1585
+ extracted_blocks.set(marker, transform(html.slice(active_block.content_start, index)));
1586
+ previous_end = index;
1587
+ active_block = undefined;
1588
+ index = closing_index;
1589
+ continue
1590
+ }
1477
1591
 
1478
- while ((match = regex.exec(current_html)) !== null) {
1479
- const marker = `${MARKER_PREFIX}${marker_id++}___`;
1592
+ if (tag_start === -1) {
1593
+ if (character === '<') tag_start = index;
1594
+ continue
1595
+ }
1480
1596
 
1481
- /* Only store content, and minify tags later. */
1482
- extracted_blocks.set(marker, match[2]);
1483
-
1484
- replacements.push({
1485
- start: match.index + match[1].length, // start of content
1486
- end: match.index + match[1].length + match[2].length, // end of content
1487
- marker: marker,
1488
- });
1597
+ if (quote) {
1598
+ if (character === quote) quote = '';
1599
+ continue
1489
1600
  }
1490
1601
 
1491
- /* Apply replacements from the end to the beginning to keep indices valid. */
1492
- for (let i = replacements.length - 1; i >= 0; i--) {
1493
- const rep = replacements[i];
1494
- current_html =
1495
- current_html.substring(0, rep.start) +
1496
- rep.marker +
1497
- current_html.substring(rep.end);
1602
+ if (character === '"' || character === "'") {
1603
+ quote = character;
1604
+ } else if (character === '<') {
1605
+ tag_start = index;
1606
+ } else if (character === '>') {
1607
+ const opening_tag = getOpeningTag(html.slice(tag_start, index + 1));
1608
+ if (opening_tag && names.has(opening_tag.name)) {
1609
+ active_block = { name: opening_tag.name, content_start: index + 1 };
1610
+ }
1611
+ tag_start = -1;
1498
1612
  }
1499
1613
  }
1500
1614
 
1501
- return { html_with_markers: current_html, extracted_map: extracted_blocks }
1615
+ if (extracted_blocks.size === 0)
1616
+ return { html_with_markers: html, extracted_map: extracted_blocks }
1617
+
1618
+ chunks.push(html.slice(previous_end));
1619
+ return { html_with_markers: chunks.join(''), extracted_map: extracted_blocks }
1620
+ };
1621
+
1622
+ /**
1623
+ * Extract any HTML blocks to be ignored,
1624
+ * and replace them with a placeholder for re-insertion later.
1625
+ *
1626
+ * @param {string} html
1627
+ * @param {string[]} ignore
1628
+ * @returns {{ html_with_markers: string, extracted_map: Map<string,string> }}
1629
+ */
1630
+ function extractIgnoredBlocks(html, ignore) {
1631
+ return extractBlocks(html, new Set(ignore), IGNORE_MARKER_PREFIX)
1632
+ }
1633
+
1634
+ /**
1635
+ * Protect textarea contents without expanding them into entities.
1636
+ *
1637
+ * @param {string} html
1638
+ * @returns {{ html_with_markers: string, extracted_map: Map<string,string> }}
1639
+ */
1640
+ function extractTextareaBlocks(html) {
1641
+ return extractBlocks(html, new Set(['textarea']), TEXTAREA_MARKER_PREFIX, content => content
1642
+ .replace(/&lt;/g, '<')
1643
+ .replace(/&gt;/g, '>')
1644
+ .replace(/&quot;/g, '"')
1645
+ .replace(/&apos;/g, "'")
1646
+ .replace(/&#10;/g, '\n')
1647
+ .replace(/&#13;/g, '\r')
1648
+ .replace(/&nbsp;/g, ' ')
1649
+ .replace(/\s+/g, ' ')
1650
+ )
1502
1651
  }
1503
1652
 
1504
1653
  /**
@@ -1509,13 +1658,18 @@
1509
1658
  * @returns
1510
1659
  */
1511
1660
  function reinsertIgnoredBlocks(html_with_markers, extracted_map) {
1512
- setState({ ignored: false });
1513
- let final_html = html_with_markers;
1661
+ return html_with_markers.replace(IGNORE_MARKER_REGEX, marker => extracted_map.get(marker) ?? marker)
1662
+ }
1514
1663
 
1515
- for (const [marker, original_block] of extracted_map) {
1516
- final_html = final_html.split(marker).join(original_block);
1517
- }
1518
- return final_html
1664
+ /**
1665
+ * Re-insert protected textarea contents in one pass.
1666
+ *
1667
+ * @param {string} html_with_markers
1668
+ * @param {Map<string,string>} extracted_map
1669
+ * @returns {string}
1670
+ */
1671
+ function reinsertTextareaBlocks(html_with_markers, extracted_map) {
1672
+ return html_with_markers.replace(TEXTAREA_MARKER_REGEX, marker => extracted_map.get(marker) ?? marker)
1519
1673
  }
1520
1674
 
1521
1675
  const void_element_regex = new RegExp(`<(${VOID_ELEMENTS.join("|")})(?:\\s(?:[^/>]|/(?!>))*)*>`, 'g');
@@ -1524,12 +1678,11 @@
1524
1678
  * Add a placeholder for void elements that are not self-closing.
1525
1679
  * This is for internal processing only.
1526
1680
  *
1527
- * @param {string} html
1681
+ * @param {string} html
1682
+ * @param {HtmlfyConstants} [constants]
1528
1683
  * @returns
1529
1684
  */
1530
- function setSelfClosing(html) {
1531
- const { constants } = getState();
1532
-
1685
+ function setSelfClosing(html, constants = DEFAULT_CONSTANTS) {
1533
1686
  return html.replace(
1534
1687
  // match only void elements that are not self-closing
1535
1688
  void_element_regex,
@@ -1538,131 +1691,25 @@
1538
1691
  }
1539
1692
 
1540
1693
  /**
1541
- * Remove internal placeholder for non-native self-closing void elements.
1542
- *
1543
- * @param {string} html
1544
- * @returns
1545
- */
1546
- function unsetSelfClosing(html) {
1547
- const { constants } = getState();
1548
-
1549
- return html.replace(constants.SELF_CLOSING_PLACEHOLDER, ">")
1550
- }
1551
-
1552
- /**
1553
- * Enforce entity characters for textarea content.
1554
- * To also minifiy tags, pass `minify` as `true`.
1555
- *
1556
- * @param {string} html The HTML string to evaluate.
1557
- * @param {boolean} [minify] Minifies the textarea tags themselves.
1558
- * Defaults to `false`. We recommend a value of `true` if you're running `entify()`
1559
- * as a standalone function.
1560
- * @returns {string}
1561
- * @example <textarea>3 > 2</textarea> => <textarea>3&nbsp;&gt;&nbsp;2</textarea>
1562
- * @example With minify.
1563
- * <textarea >3 > 2</textarea> => <textarea>3&nbsp;&gt;&nbsp;2</textarea>
1564
- */
1565
- const entify = (html, minify = false) => {
1566
- /**
1567
- * Use entities inside textarea content.
1568
- */
1569
- html = html.replace(/<\s*textarea[^>]*>((.|\n)*?)<s*\/\s*textarea\s*>/g, (match, capture) => {
1570
- return match.replace(capture, (match) => {
1571
- return match
1572
- .replace(/</g, '&lt;')
1573
- .replace(/>/g, '&gt;')
1574
- .replace(/"/g, '&quot;')
1575
- .replace(/'/g, '&apos;')
1576
- .replace(/\n/g, '&#10;')
1577
- .replace(/\r/g, '&#13;')
1578
- .replace(/\s/g, '&nbsp;')
1579
- })
1580
- });
1581
-
1582
- if (minify) {
1583
- html = html.replace(/<\s*textarea[^>]*>(.|\n)*?<\s*\/\s*textarea\s*>/g, (match) => {
1584
- /* This only affects the html tags, since everything else has been entified. */
1585
- return match
1586
- .replace(/\s+/g, ' ')
1587
- .replace(/\s>/g, '>')
1588
- .replace(/>\s/g, '>')
1589
- .replace(/\s</g, '<')
1590
- .replace(/<\s/g, '<')
1591
- .replace(/<\/\s/g, '<\/')
1592
- .replace(/class=["']\s/g, (match) => match.replace(/\s/g, ''))
1593
- .replace(/(class=.*)\s(["'])/g, '$1'+'$2')
1594
- });
1595
- }
1596
-
1597
- return html
1598
- };
1599
-
1600
- /**
1601
- * Remove entity characters for textarea content.
1602
- * Currently internal use only.
1603
- *
1604
- * @param {string} html The HTML string to evaluate.
1694
+ * Minify HTML using configuration already validated by the caller.
1695
+ *
1696
+ * @param {string} html
1697
+ * @param {import('htmlfy').Config} validated_config
1698
+ * @param {boolean} extract_ignored
1605
1699
  * @returns {string}
1606
- * @example <textarea>3&nbsp;&gt;&nbsp;2</textarea> => <textarea>3 > 2</textarea>
1607
1700
  */
1608
- const dentify = (html) => {
1609
- /**
1610
- * Remove entities inside textarea content.
1611
- */
1612
- return html = html.replace(/<textarea[^>]*>((.|\n)*?)<\/textarea>/g, (match, capture) => {
1613
- return match.replace(capture, (match) => {
1614
- match = match
1615
- .replace(/&lt;/g, '<')
1616
- .replace(/&gt;/g, '>')
1617
- .replace(/&quot;/g, '"')
1618
- .replace(/&apos;/g, "'")
1619
- .replace(/&#10;/g, '\n')
1620
- .replace(/&#13;/g, '\r')
1621
- .replace(/&nbsp;/g, ' ')
1622
- // Ensure we collapse consecutive spaces, or they'll be completely removed later.
1623
- .replace(/\s+/g, ' ');
1624
-
1625
- return match
1626
- })
1627
- })
1628
- };
1629
-
1630
- /**
1631
- * @type {Map<any,any>}
1632
- */
1633
- let ignore_map$1;
1634
-
1635
- /**
1636
- * Creates a single-line HTML string
1637
- * by removing line returns, tabs, and relevant spaces.
1638
- *
1639
- * @param {string} html The HTML string to minify.
1640
- * @param {import('htmlfy').UserConfig} [config] A user configuration object.
1641
- * @returns {string} A minified HTML string.
1642
- */
1643
- const minify = (html, config) => {
1644
- let reinsert_ignored = false;
1645
- const { checked_html, ignored, constants } = getState();
1646
-
1647
- if (!checked_html && !isHtml(html)) return html
1648
-
1649
- const validated_config = (getState()).config;
1650
- const ignore = validated_config.ignore.length > 0;
1651
-
1652
- /* Extract ignored elements. Skipped if prettify has already ignored blocks. */
1653
- if (!ignored && ignore) {
1654
- const { html_with_markers, extracted_map } = extractIgnoredBlocks(html);
1701
+ const minifyHtml = (html, validated_config, extract_ignored) => {
1702
+ /** @type {Map<string,string> | undefined} */
1703
+ let textarea_map;
1704
+ validated_config.ignore.length > 0;
1705
+
1706
+ /* Keep textarea markup out of the general minification passes. */
1707
+ if (!validated_config.ignore.includes('textarea') && html.includes('textarea')) {
1708
+ const { html_with_markers, extracted_map } = extractTextareaBlocks(html);
1655
1709
  html = html_with_markers;
1656
- ignore_map$1 = extracted_map;
1657
- reinsert_ignored = true;
1710
+ textarea_map = extracted_map;
1658
1711
  }
1659
1712
 
1660
- /**
1661
- * Ensure textarea content is protected
1662
- * before general minification.
1663
- */
1664
- html = entify(html, true);
1665
-
1666
1713
  /* All other minification. */
1667
1714
  // Remove ALL newlines and tabs explicitly.
1668
1715
  html = html.replace(/\n|\t/g, '');
@@ -1701,131 +1748,230 @@
1701
1748
  html = html.replace(/ = /g, "=");
1702
1749
  // Consider safer alternatives if needed (e.g., / = "/g, '="')
1703
1750
 
1704
- // Trim whitespace inside attribute values
1705
- html = html.replace(
1706
- /([a-zA-Z0-9_-]+)=(['"])(.*?)\2/g,
1707
- (match, attr_name, quote, value) => {
1708
- // value.trim() handles both leading/trailing spaces
1709
- // and cases where the value is only whitespace (becomes empty string)
1710
- const trimmed_value = value.trim();
1711
- return `${attr_name}=${quote}${trimmed_value}${quote}`
1712
- }
1713
- );
1751
+ // Trim whitespace inside quoted attribute values when any are padded.
1752
+ if (/=["']\s|\s["']/.test(html)) {
1753
+ html = transformOpeningTags(html, (tag, name, name_end) => {
1754
+ const chunks = [];
1755
+ let previous_end = 0;
1756
+ let index = name_end;
1757
+
1758
+ while (index < tag.length - 1) {
1759
+ while (/\s/.test(tag[index] || '')) index++;
1760
+
1761
+ const attribute_start = index;
1762
+ while (/[a-zA-Z0-9_-]/.test(tag[index] || '')) index++;
1763
+ if (index === attribute_start || tag[index] !== '=') {
1764
+ index++;
1765
+ continue
1766
+ }
1767
+
1768
+ const quote = tag[index + 1];
1769
+ if (quote !== '"' && quote !== "'") {
1770
+ index++;
1771
+ continue
1772
+ }
1773
+
1774
+ const value_start = index + 2;
1775
+ const value_end = tag.indexOf(quote, value_start);
1776
+ if (value_end === -1) break
1777
+
1778
+ const value = tag.slice(value_start, value_end);
1779
+ const trimmed_value = value.trim();
1780
+ if (trimmed_value !== value) {
1781
+ chunks.push(tag.slice(previous_end, value_start), trimmed_value);
1782
+ previous_end = value_end;
1783
+ }
1784
+ index = value_end + 1;
1785
+ }
1786
+
1787
+ if (chunks.length === 0) return tag
1788
+ chunks.push(tag.slice(previous_end));
1789
+ return chunks.join('')
1790
+ });
1791
+ }
1714
1792
 
1715
1793
  // Final trim for the whole string
1716
1794
  html = html.trim();
1717
1795
 
1718
- /* Remove protective entities. */
1719
- html = dentify(html);
1720
-
1721
- /* Re-insert ignored elements. Skipped unless minify did the ignore. */
1722
- if (reinsert_ignored) {
1723
- html = reinsertIgnoredBlocks(html, ignore_map$1);
1796
+ if (textarea_map) {
1797
+ html = reinsertTextareaBlocks(html, textarea_map);
1724
1798
  }
1725
1799
 
1726
1800
  return html
1727
1801
  };
1728
1802
 
1729
1803
  /**
1730
- * @type {{ line: Record<string,string>[] }}
1804
+ * Minify HTML that has already been checked and had ignored blocks extracted.
1805
+ *
1806
+ * @param {string} html
1807
+ * @param {import('htmlfy').Config} config
1808
+ * @returns {string}
1731
1809
  */
1732
- const convert = {
1733
- line: []
1734
- };
1810
+ const minifyKnownHtml = (html, config) => minifyHtml(html, config);
1811
+
1812
+ const VOID_ELEMENT_SET = new Set(VOID_ELEMENTS);
1813
+ const TOKEN_CLOSING = 1;
1814
+ const TOKEN_COMMENT = 2;
1815
+ const TOKEN_DOCTYPE = 4;
1816
+ const TOKEN_IGNORED = 8;
1817
+ const TOKEN_SELF_CLOSING = 16;
1818
+ const TOKEN_SYNTHETIC_SELF_CLOSING = 32;
1819
+ const TOKEN_INLINE = 64;
1735
1820
 
1736
1821
  /**
1737
- * @type {Map<any,any>}
1822
+ * @typedef {object} Token
1823
+ * @property {'tag' | 'text'} type
1824
+ * @property {string} value
1825
+ * @property {number} flags
1738
1826
  */
1739
- let ignore_map;
1740
1827
 
1741
1828
  /**
1742
1829
  * Isolate tags, content, and comments.
1743
1830
  *
1744
1831
  * @param {string} html The HTML string to evaluate.
1745
- * @example <div>Hello World!</div> =>
1746
- * [#-# : 0 : <div> : #-#]
1747
- * Hello World!
1748
- * [#-# : 1 : </div> : #-#]
1832
+ * @param {import('./utils.js').HtmlfyConstants} constants
1833
+ * @returns {Token[]}
1749
1834
  */
1750
- const enqueue = (html) => {
1751
- convert.line = [];
1752
- let i = -1;
1835
+ const enqueue = (html, constants) => {
1836
+ /** @type {Token[]} */
1837
+ const lines = [];
1753
1838
  /* Regex to find tags OR text content between tags. */
1754
- const regex = /(<[^>]+>)|([^<]+)/g;
1839
+ const regex = /<[^>]+>|[^<]+/g;
1840
+
1841
+ /* Use replace for callback iteration, but avoid constructing the old marker output. */
1842
+ html.replace(regex, (value) => {
1843
+ const type = value.startsWith('<') ? 'tag' : 'text';
1844
+
1845
+ if (type === 'text') {
1846
+ if (value.trim().length > 0) {
1847
+ lines.push({
1848
+ type,
1849
+ value,
1850
+ flags: value.startsWith('___HTMLFY_SPECIAL_IGNORE_MARKER_') ? TOKEN_IGNORED : 0,
1851
+ });
1852
+ }
1853
+ return ''
1854
+ }
1855
+
1856
+ const trimmed = value.trim();
1857
+ const synthetic_self_closing = trimmed.endsWith(constants.SELF_CLOSING_PLACEHOLDER);
1858
+ let flags = 0;
1859
+ if (trimmed.startsWith('</')) flags |= TOKEN_CLOSING;
1860
+ if (trimmed.startsWith('<!--')) flags |= TOKEN_COMMENT;
1861
+ if (trimmed.startsWith('<!doctype')) flags |= TOKEN_DOCTYPE;
1862
+ if (trimmed.endsWith('/>') || synthetic_self_closing) flags |= TOKEN_SELF_CLOSING;
1863
+ if (synthetic_self_closing) flags |= TOKEN_SYNTHETIC_SELF_CLOSING;
1864
+
1865
+ lines.push({
1866
+ type,
1867
+ value,
1868
+ flags,
1869
+ });
1870
+ return ''
1871
+ });
1755
1872
 
1756
- html.replace(regex, (match, c1, c2) => {
1757
- if (c1) {
1758
- convert.line.push({ type: "tag", value: match });
1759
- } else if (c2 && c2.trim().length > 0) {
1760
- /* It's text content (and not just whitespace). */
1761
- convert.line.push({ type: "text", value: match });
1873
+ return lines
1874
+ };
1875
+
1876
+ /**
1877
+ * Collapse the same simple element pairs handled by the final output regex.
1878
+ *
1879
+ * @param {Token[]} lines
1880
+ * @returns {Token[]}
1881
+ */
1882
+ const collapseInlineTokens = (lines) => {
1883
+ /** @type {Token[]} */
1884
+ const collapsed = [];
1885
+
1886
+ for (let index = 0; index < lines.length; index++) {
1887
+ const opening = lines[index];
1888
+
1889
+ if (opening.type === 'tag' && !(opening.flags & (
1890
+ TOKEN_CLOSING |
1891
+ TOKEN_COMMENT |
1892
+ TOKEN_DOCTYPE |
1893
+ TOKEN_SELF_CLOSING
1894
+ ))) {
1895
+ const name_match = opening.value.match(/^<([^>\s]+)[^>]*>$/);
1896
+ const name = name_match?.[1];
1897
+ const content = lines[index + 1];
1898
+ const possible_closing = content?.type === 'text' ? lines[index + 2] : content;
1899
+
1900
+ if (name && possible_closing?.value === `</${name}>`) {
1901
+ const empty_pair = content?.type === 'tag' && /^[\w:._-]+$/.test(name);
1902
+ const text_pair = content?.type === 'text' && /[^><\/\s]/.test(content.value);
1903
+
1904
+ if (empty_pair || text_pair) {
1905
+ collapsed.push({
1906
+ type: 'tag',
1907
+ value: opening.value + (text_pair ? content.value.trim() : '') + possible_closing.value,
1908
+ flags: TOKEN_INLINE,
1909
+ });
1910
+ index += text_pair ? 2 : 1;
1911
+ continue
1912
+ }
1913
+ }
1762
1914
  }
1763
1915
 
1764
- i++;
1765
- return `\n[#-# : ${i} : ${match} : #-#]\n`
1766
- });
1916
+ collapsed.push(opening);
1917
+ }
1918
+
1919
+ return collapsed
1767
1920
  };
1768
1921
 
1769
1922
  /**
1770
1923
  * Process enqueued content.
1771
1924
  *
1925
+ * @param {Token[]} lines
1926
+ * @param {import('htmlfy').Config} config
1927
+ * @param {import('./utils.js').HtmlfyConstants} constants
1772
1928
  * @returns {string}
1773
1929
  */
1774
- const process = () => {
1775
- const { config, constants } = getState();
1930
+ const process = (lines, config, constants) => {
1776
1931
  const step = " ".repeat(config.tab_size);
1777
1932
  const tag_wrap = config.tag_wrap;
1778
1933
  const content_wrap = config.content_wrap;
1779
1934
  const strict = config.strict;
1780
1935
 
1781
1936
  /* Track current number of indentations needed. */
1782
- let indents = '';
1937
+ let indent_level = 0;
1783
1938
 
1784
1939
  /** @type string[] */
1785
1940
  const output_lines = [];
1786
- const tag_regex = /<[A-Za-z]+\b[^>]*(?:.|\n)*?\/?>/g; /* Is opening tag or void element. */
1941
+ const tag_regex = /<[A-Za-z]+\b[^>]*(?:.|\n)*?\/?>/; /* Is opening tag or void element. */
1787
1942
  const attribute_regex = /\s{1}[A-Za-z:@#*?$()\[\].-]+(?:=".*?")?/g; /* Matches all tag/element attributes. */
1788
1943
 
1789
1944
  /* Process lines and indent. */
1790
- convert.line.forEach((source, index) => {
1945
+ lines.forEach((source, index) => {
1791
1946
  let current_line_value = source.value;
1792
1947
 
1793
- const is_ignored_content =
1794
- current_line_value.startsWith('___HTMLFY_SPECIAL_IGNORE_MARKER_');
1795
-
1796
1948
  let subtrahend = 0;
1797
- const prev_line_data = convert.line[index - 1];
1798
- const prev_line_value = prev_line_data?.value ?? ""; // Use empty string if no prev line
1949
+ const prev_line_data = lines[index - 1];
1799
1950
 
1800
- /**
1801
- * Arbitratry character, to keep track of the string's length.
1802
- */
1803
- indents += '0';
1951
+ indent_level++;
1804
1952
 
1805
1953
  if (index === 0) subtrahend++;
1806
1954
  /* We're processing a closing tag. */
1807
- if (current_line_value.trim().startsWith("</")) subtrahend++;
1955
+ if (source.flags & TOKEN_CLOSING) subtrahend++;
1808
1956
  /* prevLine is a doctype declaration. */
1809
- if (prev_line_value.trim().startsWith("<!doctype")) subtrahend++;
1957
+ if (prev_line_data && (prev_line_data.flags & TOKEN_DOCTYPE)) subtrahend++;
1810
1958
  /* prevLine is a comment. */
1811
- if (prev_line_value.trim().startsWith("<!--")) subtrahend++;
1959
+ if (prev_line_data && (prev_line_data.flags & TOKEN_COMMENT)) subtrahend++;
1812
1960
  /* prevLine is a void element. */
1813
- if (
1814
- prev_line_value.trim().endsWith("/>") // native self-closing
1815
- ||
1816
- prev_line_value.trim().endsWith(constants.SELF_CLOSING_PLACEHOLDER) // synthetic self-closing
1817
- ) subtrahend++;
1961
+ if (prev_line_data && (prev_line_data.flags & TOKEN_SELF_CLOSING)) subtrahend++;
1818
1962
  /* prevLine is a closing tag. */
1819
- if (prev_line_value.trim().startsWith("</")) subtrahend++;
1963
+ if (prev_line_data && (prev_line_data.flags & TOKEN_CLOSING)) subtrahend++;
1964
+ /* prevLine opens and closes on the same line. */
1965
+ if (prev_line_data && (prev_line_data.flags & TOKEN_INLINE)) subtrahend++;
1820
1966
  /* prevLine is text. */
1821
1967
  if (prev_line_data?.type === "text") subtrahend++;
1822
1968
 
1823
1969
  /* Determine offset for line indentation. */
1824
- const offset = Math.max(0, indents.length - subtrahend);
1970
+ const offset = Math.max(0, indent_level - subtrahend);
1825
1971
  /* Correct indent level for *this* line's content */
1826
1972
  const current_indent_level = offset; // Store the level for this line
1827
1973
 
1828
- indents = indents.substring(0, current_indent_level); // Adjust for *next* round
1974
+ indent_level = current_indent_level;
1829
1975
 
1830
1976
  /**
1831
1977
  * Starts with a single punctuation character.
@@ -1848,25 +1994,26 @@
1848
1994
 
1849
1995
  const padding = step.repeat(current_indent_level);
1850
1996
 
1851
- if (is_ignored_content) {
1997
+ if (source.flags & TOKEN_IGNORED) {
1852
1998
  /* Stop processing this line, as it's set to be ignored. */
1853
1999
  output_lines.push(current_line_value);
1854
2000
  } else {
1855
2001
  /* Remove comment. */
1856
- if (strict && current_line_value.trim().startsWith("<!--"))
2002
+ if (strict && (source.flags & TOKEN_COMMENT))
1857
2003
  return
1858
2004
 
1859
2005
  let result = current_line_value;
1860
2006
 
1861
2007
  /* Remove self-closing placeholder, if needed. */
1862
- result = unsetSelfClosing(result);
2008
+ if (source.flags & TOKEN_SYNTHETIC_SELF_CLOSING)
2009
+ result = result.replace(constants.SELF_CLOSING_PLACEHOLDER, '>');
1863
2010
 
1864
2011
  if (
1865
2012
  source.type === 'text' &&
1866
2013
  content_wrap > 0 &&
1867
2014
  result.length >= content_wrap
1868
2015
  ) {
1869
- result = wordWrap(result, content_wrap, padding);
2016
+ result = wordWrap(result, content_wrap, padding, constants);
1870
2017
  }
1871
2018
  /* Wrap the attributes of open tags and void elements. */
1872
2019
  else if (
@@ -1874,30 +2021,36 @@
1874
2021
  result.length > tag_wrap &&
1875
2022
  tag_regex.test(result)
1876
2023
  ) {
1877
- tag_regex.lastIndex = 0; // Reset stateful regex
1878
2024
  attribute_regex.lastIndex = 0; // Reset stateful regex
1879
2025
 
1880
- const tag_parts = result.split(attribute_regex).filter(Boolean);
2026
+ const attributes = [];
2027
+ let first_attribute_start = -1;
2028
+ let last_attribute_end = -1;
2029
+ let attribute_match;
1881
2030
 
1882
- if (tag_parts.length >= 2) {
1883
- const attributes = result.matchAll(attribute_regex);
2031
+ while ((attribute_match = attribute_regex.exec(result)) !== null) {
2032
+ if (first_attribute_start === -1) first_attribute_start = attribute_match.index;
2033
+ last_attribute_end = attribute_regex.lastIndex;
2034
+ attributes.push(attribute_match[0].trim());
2035
+ }
2036
+
2037
+ if (attributes.length > 0) {
2038
+ const opening_part = result.slice(0, first_attribute_start);
2039
+ const closing_part = result.slice(last_attribute_end).trim();
1884
2040
  const inner_padding = padding + step;
1885
- let wrapped_tag = padding + tag_parts[0] + "\n";
2041
+ const wrapped_tag = [padding + opening_part];
1886
2042
 
1887
- for (const a of attributes) {
1888
- const attribute_string = a[0].trim();
1889
- wrapped_tag += inner_padding + attribute_string + "\n";
2043
+ for (const attribute of attributes) {
2044
+ wrapped_tag.push(inner_padding + attribute);
1890
2045
  }
1891
2046
 
1892
- const tag_name_match = tag_parts[0].match(/<([A-Za-z_:-]+)/);
2047
+ const tag_name_match = opening_part.match(/<([A-Za-z_:-]+)/);
1893
2048
  const tag_name = tag_name_match ? tag_name_match[1] : "";
1894
- const is_self_closing = tag_parts.at(-1)?.endsWith("/>") && VOID_ELEMENTS.includes(tag_name);
1895
- const closing_part = tag_parts[1].trim();
2049
+ const is_self_closing = result.endsWith("/>") && VOID_ELEMENT_SET.has(tag_name);
1896
2050
  const closing_padding = padding + (strict && is_self_closing ? " " : "");
1897
2051
 
1898
- wrapped_tag += closing_padding + closing_part;
1899
-
1900
- result = wrapped_tag; // Assign the fully wrapped string
2052
+ wrapped_tag.push(closing_padding + closing_part);
2053
+ result = wrapped_tag.join('\n');
1901
2054
  } else {
1902
2055
  result = padding + result;
1903
2056
  }
@@ -1915,30 +2068,32 @@
1915
2068
  let final_html = output_lines.join("\n");
1916
2069
 
1917
2070
  /* Preserve wrapped attributes. */
1918
- if (tag_wrap > 0) final_html = protectAttributes(final_html);
2071
+ if (tag_wrap > 0) final_html = protectAttributes(final_html, constants);
1919
2072
 
1920
2073
  /* Extra preserve wrapped content. */
1921
2074
  if (content_wrap > 0 && new RegExp(`/\\n[ ]*[^\\n]*${constants.CONTENT_IGNORE_PLACEHOLDER}[^\\n]*\\n/`).test(final_html))
1922
- final_html = finalProtectContent(final_html);
2075
+ final_html = finalProtectContent(final_html, constants);
1923
2076
 
1924
2077
  /* Remove line returns, tabs, and consecutive spaces within html elements or their content. */
1925
- final_html = final_html.replace(
1926
- /<(?<Element>[^>\s]+)[^>]*>[^<]*?[^><\/\s][^<]*?<\/\k<Element>>|<script[^>]*>[\s]*<\/script>|<([\w:\._-]+)([^>]*)><\/\2>|<([\w:\._-]+)([^>]*)>[\s]+<\/\4>/g,
1927
- match => {
1928
- // Check if this contains placeholder
1929
- if (match.includes(constants.SELF_CLOSING_PLACEHOLDER) || match.includes(constants.CONTENT_IGNORE_PLACEHOLDER)) {
1930
- return match // Don't modify if it contains the placeholder
1931
- }
2078
+ if (tag_wrap > 0 || content_wrap > 0) {
2079
+ final_html = final_html.replace(
2080
+ /<(?<Element>[^>\s]+)[^>]*>[^<]*?[^><\/\s][^<]*?<\/\k<Element>>|<script[^>]*>[\s]*<\/script>|<([\w:\._-]+)([^>]*)><\/\2>|<([\w:\._-]+)([^>]*)>[\s]+<\/\4>/g,
2081
+ match => {
2082
+ // Check if this contains placeholder
2083
+ if (match.includes(constants.SELF_CLOSING_PLACEHOLDER) || match.includes(constants.CONTENT_IGNORE_PLACEHOLDER)) {
2084
+ return match // Don't modify if it contains the placeholder
2085
+ }
1932
2086
 
1933
- return match.replace(/\n|\t|\s{2,}/g, '')
1934
- }
1935
- );
2087
+ return match.replace(/\n|\t|\s{2,}/g, '')
2088
+ }
2089
+ );
2090
+ }
1936
2091
 
1937
2092
  /* Revert wrapped content. */
1938
- if (content_wrap > 0) final_html = unprotectContent(final_html);
2093
+ if (content_wrap > 0) final_html = unprotectContent(final_html, constants);
1939
2094
 
1940
2095
  /* Revert wrapped attributes. */
1941
- if (tag_wrap > 0) final_html = unprotectAttributes(final_html);
2096
+ if (tag_wrap > 0) final_html = unprotectAttributes(final_html, constants);
1942
2097
 
1943
2098
  /* Remove self-closing nature of void elements. */
1944
2099
  if (strict) final_html = final_html.replace(/\s\/>|\/>/g, '>');
@@ -1958,43 +2113,44 @@
1958
2113
  * @returns {string} A well-formed HTML string.
1959
2114
  */
1960
2115
  const prettify = (html, config) => {
1961
- let reinsert_ignored = false;
1962
- const { checked_html, ignored } = getState();
1963
-
1964
2116
  /* Return content as-is if it does not contain any HTML elements. */
1965
- if (!checked_html && !isHtml(html)) return html
2117
+ if (!isHtml(html)) return html
1966
2118
 
1967
- /* Runs setState for config. */
1968
2119
  const validated_config = validateConfig(config || {});
2120
+ const constants = createConstants(validated_config.ignore_with);
1969
2121
 
1970
2122
  const ignore = validated_config.ignore.length > 0;
1971
2123
 
2124
+ /** @type {Map<any,any> | undefined} */
2125
+ let ignore_map;
2126
+
1972
2127
  /* Allows you to trimify before ignoring. */
1973
2128
  if (validated_config.trim.length > 0) html = trimify(html, validated_config.trim);
1974
2129
 
1975
2130
  /* Extract ignored elements. */
1976
- if (!ignored && ignore) {
1977
- const { html_with_markers, extracted_map } = extractIgnoredBlocks(html);
2131
+ if (ignore) {
2132
+ const { html_with_markers, extracted_map } = extractIgnoredBlocks(html, validated_config.ignore);
1978
2133
  html = html_with_markers;
1979
2134
  ignore_map = extracted_map;
1980
- reinsert_ignored = true;
1981
2135
  }
1982
2136
 
1983
2137
  /* Preserve html text within attribute values. */
1984
- html = setIgnoreAttribute(html);
2138
+ html = setIgnoreAttribute(html, constants);
1985
2139
 
1986
2140
  /* Insert placeholder for void elements that aren't self-closing. */
1987
- html = setSelfClosing(html);
2141
+ html = setSelfClosing(html, constants);
1988
2142
 
1989
- html = minify(html);
1990
- enqueue(html);
1991
- html = process();
2143
+ html = minifyKnownHtml(html, validated_config);
2144
+ let lines = enqueue(html, constants);
2145
+ if (validated_config.tag_wrap === 0 && validated_config.content_wrap === 0)
2146
+ lines = collapseInlineTokens(lines);
2147
+ html = process(lines, validated_config, constants);
1992
2148
 
1993
2149
  /* Revert html text within attribute values. */
1994
- html = unsetIgnoreAttribute(html);
2150
+ html = unsetIgnoreAttribute(html, constants);
1995
2151
 
1996
2152
  /* Re-insert ignored elements. */
1997
- if (reinsert_ignored) {
2153
+ if (ignore_map) {
1998
2154
  html = reinsertIgnoredBlocks(html, ignore_map);
1999
2155
  }
2000
2156