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