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