@mgdis/core-ui-helpers 1.3.1 → 1.3.2

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