@mgdis/core-ui-helpers 1.0.5 → 1.0.7

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.
@@ -934,37 +934,55 @@
934
934
  const CONFIG = {
935
935
  content_wrap: 0,
936
936
  ignore: [],
937
- ignore_with: '_!i-£___£%_',
937
+ ignore_with: '!i-£___£%_',
938
938
  strict: false,
939
939
  tab_size: 2,
940
940
  tag_wrap: 0,
941
- tag_wrap_width: 80,
942
941
  trim: []
943
942
  };
944
943
 
945
- const CONTENT_IGNORE_STRING = '__!i-£___£%__';
946
- const IGNORE_STRING = '!i-£___£%_';
947
-
948
944
  const VOID_ELEMENTS = [
949
945
  'area', 'base', 'br', 'col', 'embed', 'hr',
950
946
  'img', 'input', 'link', 'meta',
951
947
  'param', 'source', 'track', 'wbr'
952
948
  ];
953
949
 
950
+ /**
951
+ * Defined by state.js and configuration.
952
+ *
953
+ * CONTENT_IGNORE_PLACEHOLDER
954
+ * SELF_CLOSING_PLACEHOLDER
955
+ * ATTRIBUTE_IGNORE_PLACEHOLDER
956
+ */
957
+
958
+ /**
959
+ * @typedef {object} Constants
960
+ * @property {string} CONTENT_IGNORE_PLACEHOLDER
961
+ * @property {string} SELF_CLOSING_PLACEHOLDER
962
+ * @property {string} ATTRIBUTE_IGNORE_PLACEHOLDER
963
+ */
954
964
  /**
955
965
  * @typedef {object} State
956
966
  * @property {boolean} checked_html - If passed in HTML has been checked for HTML within it.
957
967
  * @property {import("htmlfy").Config} config - Validated configuration.
958
968
  * @property {boolean} ignored
969
+ * @property {Constants} constants - Constant strings, influenced by ignore_with.
959
970
  */
960
971
 
961
972
  /**
962
973
  * @type State
974
+ *
975
+ * `constants` prefixes and suffixes must be in sync with those in utils.js
963
976
  */
964
977
  const state = {
965
978
  checked_html: false,
966
979
  config: { ...CONFIG },
967
- ignored: false
980
+ ignored: false,
981
+ constants: {
982
+ CONTENT_IGNORE_PLACEHOLDER: `${CONFIG.ignore_with}_`,
983
+ SELF_CLOSING_PLACEHOLDER: `${CONFIG.ignore_with}/_>`,
984
+ ATTRIBUTE_IGNORE_PLACEHOLDER: `${CONFIG.ignore_with}=_`
985
+ }
968
986
  };
969
987
 
970
988
  /**
@@ -1051,7 +1069,16 @@
1051
1069
  */
1052
1070
  const mergeConfig = (default_config, config) => {
1053
1071
  const validated_config = mergeObjects(default_config, config);
1054
- setState({ config: validated_config });
1072
+
1073
+ /* Below `constants` prefixes and suffixes must be in sync with those in state.js */
1074
+ setState({
1075
+ config: validated_config,
1076
+ constants: {
1077
+ CONTENT_IGNORE_PLACEHOLDER: `${validated_config.ignore_with}_`,
1078
+ SELF_CLOSING_PLACEHOLDER: `${validated_config.ignore_with}/_>`,
1079
+ ATTRIBUTE_IGNORE_PLACEHOLDER: `${validated_config.ignore_with}=_`
1080
+ }
1081
+ });
1055
1082
  return validated_config
1056
1083
  };
1057
1084
 
@@ -1060,12 +1087,14 @@
1060
1087
  * @param {string} html
1061
1088
  */
1062
1089
  const protectAttributes = (html) => {
1090
+ const { constants } = getState();
1091
+
1063
1092
  html = html.replace(/<[\w:\-]+([^>]*[^\/])>/g, (/** @type {string} */match, /** @type {any} */capture) => {
1064
1093
  return match.replace(capture, (match) => {
1065
1094
  return match
1066
- .replace(/\n/g, IGNORE_STRING + 'nl!')
1067
- .replace(/\r/g, IGNORE_STRING + 'cr!')
1068
- .replace(/\s/g, IGNORE_STRING + 'ws!')
1095
+ .replace(/\n/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'nl!')
1096
+ .replace(/\r/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'cr!')
1097
+ .replace(/\s/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'ws!')
1069
1098
  })
1070
1099
  });
1071
1100
 
@@ -1077,10 +1106,12 @@
1077
1106
  * @param {string} html
1078
1107
  */
1079
1108
  const protectContent = (html) => {
1109
+ const { constants } = getState();
1110
+
1080
1111
  return html
1081
- .replace(/\n/g, CONTENT_IGNORE_STRING + 'nl!')
1082
- .replace(/\r/g, CONTENT_IGNORE_STRING + 'cr!')
1083
- .replace(/\s/g, CONTENT_IGNORE_STRING + 'ws!')
1112
+ .replace(/\n/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!')
1113
+ .replace(/\r/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!')
1114
+ .replace(/\s/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'ws!')
1084
1115
  };
1085
1116
 
1086
1117
  /**
@@ -1088,7 +1119,9 @@
1088
1119
  * @param {string} html
1089
1120
  */
1090
1121
  const finalProtectContent = (html) => {
1091
- 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;
1122
+ 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;
1123
+ const { constants } = getState();
1124
+
1092
1125
  return html
1093
1126
  .replace(regex, (/** @type {string} */match, p1, p2, p3, p4) => {
1094
1127
  const text_to_protect = p2 || p4;
@@ -1097,9 +1130,9 @@
1097
1130
  return match
1098
1131
 
1099
1132
  const protected_text = text_to_protect
1100
- .replace(/\n/g, CONTENT_IGNORE_STRING + 'nl!')
1101
- .replace(/\r/g, CONTENT_IGNORE_STRING + 'cr!')
1102
- .replace(/\s/g, CONTENT_IGNORE_STRING + "ws!");
1133
+ .replace(/\n/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!')
1134
+ .replace(/\r/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!')
1135
+ .replace(/\s/g, constants.CONTENT_IGNORE_PLACEHOLDER + "ws!");
1103
1136
 
1104
1137
  return match.replace(text_to_protect, protected_text)
1105
1138
  })
@@ -1112,13 +1145,14 @@
1112
1145
  * @returns {string}
1113
1146
  */
1114
1147
  const setIgnoreAttribute = (html) => {
1115
- 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;
1148
+ 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;
1149
+ const { constants } = getState();
1116
1150
 
1117
1151
  html = html.replace(regex, (/** @type {string} */match, p1, p2) => {
1118
1152
  return match.replace(p2, (match) => {
1119
1153
  return match
1120
- .replace(/</g, IGNORE_STRING + 'lt!')
1121
- .replace(/>/g, IGNORE_STRING + 'gt!')
1154
+ .replace(/</g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'lt!')
1155
+ .replace(/>/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'gt!')
1122
1156
  })
1123
1157
  });
1124
1158
 
@@ -1151,12 +1185,14 @@
1151
1185
  * @param {string} html
1152
1186
  */
1153
1187
  const unprotectAttributes = (html) => {
1188
+ const { constants } = getState();
1189
+
1154
1190
  html = html.replace(/<[\w:\-]+([^>]*[^\/])>/g, (/** @type {string} */match, /** @type {any} */capture) => {
1155
1191
  return match.replace(capture, (match) => {
1156
1192
  return match
1157
- .replace(new RegExp(IGNORE_STRING + 'nl!', "g"), '\n')
1158
- .replace(new RegExp(IGNORE_STRING + 'cr!', "g"), '\r')
1159
- .replace(new RegExp(IGNORE_STRING + 'ws!', "g"), ' ')
1193
+ .replace(new RegExp(constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'nl!', "g"), '\n')
1194
+ .replace(new RegExp(constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'cr!', "g"), '\r')
1195
+ .replace(new RegExp(constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'ws!', "g"), ' ')
1160
1196
  })
1161
1197
  });
1162
1198
 
@@ -1168,25 +1204,20 @@
1168
1204
  * @param {string} html
1169
1205
  */
1170
1206
  const unprotectContent = (html) => {
1171
- html = html.replace(/.*__!i-£___£%__[a-z]{2}!.*/g, (/** @type {string} */match) => {
1172
- return match.replace(/__!i-£___£%__[a-z]{2}!/g, (match) => {
1207
+ const { constants } = getState();
1208
+
1209
+ html = html.replace(new RegExp(`.*${constants.CONTENT_IGNORE_PLACEHOLDER}[a-z]{2}!.*`, "g"), (/** @type {string} */match) => {
1210
+ return match.replace(new RegExp(`${constants.CONTENT_IGNORE_PLACEHOLDER}[a-z]{2}!`, "g"), (match) => {
1173
1211
  return match
1174
- .replace(new RegExp(CONTENT_IGNORE_STRING + 'nl!', "g"), '\n')
1175
- .replace(new RegExp(CONTENT_IGNORE_STRING + 'cr!', "g"), '\r')
1176
- .replace(new RegExp(CONTENT_IGNORE_STRING + 'ws!', "g"), ' ')
1212
+ .replace(new RegExp(constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!', "g"), '\n')
1213
+ .replace(new RegExp(constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!', "g"), '\r')
1214
+ .replace(new RegExp(constants.CONTENT_IGNORE_PLACEHOLDER + 'ws!', "g"), ' ')
1177
1215
  })
1178
1216
  });
1179
1217
 
1180
1218
  return html
1181
1219
  };
1182
1220
 
1183
- const escapedIgnoreString = IGNORE_STRING.replace(
1184
- /[-\/\\^$*+?.()|[\]{}]/g,
1185
- "\\$&"
1186
- );
1187
- const ltPlaceholderRegex = new RegExp(escapedIgnoreString + "lt!", "g");
1188
- const gtPlaceholderRegex = new RegExp(escapedIgnoreString + "gt!", "g");
1189
-
1190
1221
  /**
1191
1222
  * Replace ignore string with html brackets.
1192
1223
  *
@@ -1196,6 +1227,13 @@
1196
1227
  const unsetIgnoreAttribute = (html) => {
1197
1228
  /* Regex to find opening tags and capture their attributes. */
1198
1229
  const tagRegex = /<([\w:\-]+)([^>]*)>/g;
1230
+ const { constants } = getState();
1231
+ const escapedIgnoreString = constants.ATTRIBUTE_IGNORE_PLACEHOLDER.replace(
1232
+ /[-\/\\^$*+?.()|[\]{}]/g,
1233
+ "\\$&"
1234
+ );
1235
+ const ltPlaceholderRegex = new RegExp(escapedIgnoreString + "lt!", "g");
1236
+ const gtPlaceholderRegex = new RegExp(escapedIgnoreString + "gt!", "g");
1199
1237
 
1200
1238
  return html.replace(
1201
1239
  tagRegex,
@@ -1232,7 +1270,6 @@
1232
1270
  Object.hasOwn(config, 'strict') ||
1233
1271
  Object.hasOwn(config, 'tab_size') ||
1234
1272
  Object.hasOwn(config, 'tag_wrap') ||
1235
- Object.hasOwn(config, 'tag_wrap_width') ||
1236
1273
  Object.hasOwn(config, 'trim')
1237
1274
  );
1238
1275
 
@@ -1260,37 +1297,29 @@
1260
1297
  }
1261
1298
 
1262
1299
  if (Object.hasOwn(config, 'content_wrap') && typeof config.content_wrap !== 'number')
1263
- throw new Error(`content_wrap config must be a number, not ${typeof config.tag_wrap_width}.`)
1300
+ throw new Error(`content_wrap config must be a number, not ${typeof config.content_wrap}.`)
1264
1301
 
1265
1302
  if (Object.hasOwn(config, 'ignore') && (!Array.isArray(config.ignore) || !config.ignore?.every((e) => typeof e === 'string')))
1266
1303
  throw new Error('Ignore config must be an array of strings.')
1267
1304
 
1268
- if (Object.hasOwn(config, 'ignore_with') && typeof config.ignore_with !== 'string')
1269
- throw new Error(`Ignore_with config must be a string, not ${typeof config.ignore_with}.`)
1305
+ if (Object.hasOwn(config, 'ignore_with')) {
1306
+ if (typeof config.ignore_with !== 'string')
1307
+ throw new Error(`ignore_with must be a string, not ${typeof config.ignore_with}.`)
1308
+ else if (config.ignore_with.startsWith('_'))
1309
+ /**
1310
+ * This negatively affects processing of preserved tag attributes,
1311
+ * because tag names can end with an underscore, so the regex
1312
+ * does not capture them.
1313
+ */
1314
+ throw new Error(`ignore_with cannot start with an underscore.`)
1315
+ }
1270
1316
 
1271
1317
  if (Object.hasOwn(config, 'strict') && typeof config.strict !== 'boolean')
1272
1318
  throw new Error(`Strict config must be a boolean, not ${typeof config.strict}.`)
1273
-
1274
- /* TODO remove in v0.9.0 */
1275
- if (Object.hasOwn(config, 'tag_wrap') && typeof config.tag_wrap === 'boolean') {
1276
- console.warn('tag_wrap as a boolean is deprecated, and will not be supported in v0.9.0+. Use `tag_wrap: <number>` instead; where <number> is the max character width acceptable before wrapping attributes.');
1277
- if (config.tag_wrap_width)
1278
- config.tag_wrap = config.tag_wrap_width;
1279
- else
1280
- config.tag_wrap = default_config.tag_wrap_width;
1281
- }
1282
1319
 
1283
1320
  if (Object.hasOwn(config, 'tag_wrap') && typeof config.tag_wrap !== 'number')
1284
1321
  throw new Error(`tag_wrap config must be a number, not ${typeof config.tag_wrap}.`)
1285
1322
 
1286
- /* TODO remove in v0.9.0 */
1287
- if (Object.hasOwn(config, 'tag_wrap_width'))
1288
- console.warn('tag_wrap_width is deprecated, and will not be supported in v0.9.0+. Use `tag_wrap: <number>` instead; where <number> is the max character width acceptable before wrapping attributes.');
1289
-
1290
- /* TODO remove in v0.9.0 */
1291
- if (Object.hasOwn(config, 'tag_wrap_width') && typeof config.tag_wrap_width !== 'number')
1292
- throw new Error(`tag_wrap_width config must be a number, not ${typeof config.tag_wrap_width}.`)
1293
-
1294
1323
  if (Object.hasOwn(config, 'trim') && (!Array.isArray(config.trim) || !config.trim?.every((e) => typeof e === 'string')))
1295
1324
  throw new Error('Trim config must be an array of strings.')
1296
1325
 
@@ -1359,11 +1388,11 @@
1359
1388
  * for re-insertion later.
1360
1389
  *
1361
1390
  * @param {string} html
1362
- * @param {import('htmlfy').Config} config
1363
- * @returns {{ html_with_markers: string, extracted_map: Map<any,any> }}
1391
+ * @returns {{ html_with_markers: string, extracted_map: Map<any,any> }}
1364
1392
  */
1365
- function extractIgnoredBlocks(html, config) {
1393
+ function extractIgnoredBlocks(html) {
1366
1394
  setState({ ignored: true });
1395
+ const config = (getState()).config;
1367
1396
  let current_html = html;
1368
1397
  const extracted_blocks = new Map();
1369
1398
  let marker_id = 0;
@@ -1374,19 +1403,27 @@
1374
1403
  const safe_tag_name = tag.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
1375
1404
 
1376
1405
  const regex = new RegExp(
1377
- `<${safe_tag_name}[^>]*>.*?<\/${safe_tag_name}>`,
1406
+ `(<\\s*${safe_tag_name}[^>]*>)(.*?)(<\\s*\/\\s*${safe_tag_name}\\s*>)`,
1378
1407
  "gs" // global and dotAll
1379
1408
  );
1380
1409
 
1410
+ /** @type RegExpExecArray | null */
1381
1411
  let match;
1382
- const replacements = []; // Store [startIndex, endIndex, marker]
1412
+
1413
+ /**
1414
+ * @type {{ start: number; end: number; marker: string }[]}
1415
+ */
1416
+ const replacements = [];
1383
1417
 
1384
1418
  while ((match = regex.exec(current_html)) !== null) {
1385
1419
  const marker = `${MARKER_PREFIX}${marker_id++}___`;
1386
- extracted_blocks.set(marker, match[0]); // Store the full original match
1420
+
1421
+ /* Only store content, and minify tags later. */
1422
+ extracted_blocks.set(marker, match[2]);
1423
+
1387
1424
  replacements.push({
1388
- start: match.index,
1389
- end: regex.lastIndex,
1425
+ start: match.index + match[1].length, // start of content
1426
+ end: match.index + match[1].length + match[2].length, // end of content
1390
1427
  marker: marker,
1391
1428
  });
1392
1429
  }
@@ -1400,6 +1437,7 @@
1400
1437
  current_html.substring(rep.end);
1401
1438
  }
1402
1439
  }
1440
+
1403
1441
  return { html_with_markers: current_html, extracted_map: extracted_blocks }
1404
1442
  }
1405
1443
 
@@ -1420,42 +1458,55 @@
1420
1458
  return final_html
1421
1459
  }
1422
1460
 
1461
+ const void_element_regex = new RegExp(`<(${VOID_ELEMENTS.join("|")})(?:\\s(?:[^/>]|/(?!>))*)*>`, 'g');
1462
+
1423
1463
  /**
1424
- * Ensure void elements are "self-closing".
1464
+ * Add a placeholder for void elements that are not self-closing.
1465
+ * This is for internal processing only.
1425
1466
  *
1426
- * @param {string} html The HTML string to evaluate.
1427
- * @returns {string}
1428
- * @example <br> => <br />
1467
+ * @param {string} html
1468
+ * @returns
1429
1469
  */
1430
- const closify = (html) => {
1431
- const { checked_html } = getState();
1432
-
1433
- if (!checked_html && !isHtml(html)) return html
1434
-
1435
- return html.replace(/<([a-zA-Z\-0-9:]+)[^>]*>/g, (match, name) => {
1436
- if (VOID_ELEMENTS.indexOf(name) > -1)
1437
- return (`${match.substring(0, match.length - 1)} />`).replace(/\/\s\//g, '/')
1470
+ function setSelfClosing(html) {
1471
+ const { constants } = getState();
1438
1472
 
1439
- return match.replace(/[\s]?\/>/g, `></${name}>`)
1440
- })
1441
- };
1473
+ return html.replace(
1474
+ // match only void elements that are not self-closing
1475
+ void_element_regex,
1476
+ match => match.replace(/>$/, constants.SELF_CLOSING_PLACEHOLDER)
1477
+ )
1478
+ }
1479
+
1480
+ /**
1481
+ * Remove internal placeholder for non-native self-closing void elements.
1482
+ *
1483
+ * @param {string} html
1484
+ * @returns
1485
+ */
1486
+ function unsetSelfClosing(html) {
1487
+ const { constants } = getState();
1488
+
1489
+ return html.replace(constants.SELF_CLOSING_PLACEHOLDER, ">")
1490
+ }
1442
1491
 
1443
1492
  /**
1444
1493
  * Enforce entity characters for textarea content.
1445
- * To also minifiy, pass `minify` as `true`.
1494
+ * To also minifiy tags, pass `minify` as `true`.
1446
1495
  *
1447
1496
  * @param {string} html The HTML string to evaluate.
1448
- * @param {boolean} [minify] Fully minifies the content of textarea elements.
1497
+ * @param {boolean} [minify] Minifies the textarea tags themselves.
1449
1498
  * Defaults to `false`. We recommend a value of `true` if you're running `entify()`
1450
1499
  * as a standalone function.
1451
1500
  * @returns {string}
1452
- * @example <textarea>3 > 2</textarea> => <textarea>3 &gt; 2</textarea>
1501
+ * @example <textarea>3 > 2</textarea> => <textarea>3&nbsp;&gt;&nbsp;2</textarea>
1502
+ * @example With minify.
1503
+ * <textarea >3 > 2</textarea> => <textarea>3&nbsp;&gt;&nbsp;2</textarea>
1453
1504
  */
1454
1505
  const entify = (html, minify = false) => {
1455
1506
  /**
1456
1507
  * Use entities inside textarea content.
1457
1508
  */
1458
- html = html.replace(/<textarea[^>]*>((.|\n)*?)<\/textarea>/g, (match, capture) => {
1509
+ html = html.replace(/<\s*textarea[^>]*>((.|\n)*?)<s*\/\s*textarea\s*>/g, (match, capture) => {
1459
1510
  return match.replace(capture, (match) => {
1460
1511
  return match
1461
1512
  .replace(/</g, '&lt;')
@@ -1468,33 +1519,54 @@
1468
1519
  })
1469
1520
  });
1470
1521
 
1471
- /* Typical minification, but only for textareas. */
1472
1522
  if (minify) {
1473
- html = html.replace(/<textarea[^>]*>((.|\n)*?)<\/textarea>/g, (match, capture) => {
1474
- /* Replace things inside the textarea content. */
1475
- match = match.replace(capture, (match) => {
1476
- return match
1477
- .replace(/\n|\t/g, '')
1478
- .replace(/[a-z]+="\s*"/ig, '')
1479
- .replace(/>\s+</g, '><')
1480
- .replace(/\s+/g, ' ')
1481
- });
1482
-
1483
- /* Replace things in the entire element */
1484
- match = match
1523
+ html = html.replace(/<\s*textarea[^>]*>(.|\n)*?<\s*\/\s*textarea\s*>/g, (match) => {
1524
+ /* This only affects the html tags, since everything else has been entified. */
1525
+ return match
1485
1526
  .replace(/\s+/g, ' ')
1486
1527
  .replace(/\s>/g, '>')
1487
1528
  .replace(/>\s/g, '>')
1488
1529
  .replace(/\s</g, '<')
1530
+ .replace(/<\s/g, '<')
1531
+ .replace(/<\/\s/g, '<\/')
1489
1532
  .replace(/class=["']\s/g, (match) => match.replace(/\s/g, ''))
1490
- .replace(/(class=.*)\s(["'])/g, '$1'+'$2');
1491
- return match
1533
+ .replace(/(class=.*)\s(["'])/g, '$1'+'$2')
1492
1534
  });
1493
1535
  }
1494
1536
 
1495
1537
  return html
1496
1538
  };
1497
1539
 
1540
+ /**
1541
+ * Remove entity characters for textarea content.
1542
+ * Currently internal use only.
1543
+ *
1544
+ * @param {string} html The HTML string to evaluate.
1545
+ * @returns {string}
1546
+ * @example <textarea>3&nbsp;&gt;&nbsp;2</textarea> => <textarea>3 > 2</textarea>
1547
+ */
1548
+ const dentify = (html) => {
1549
+ /**
1550
+ * Remove entities inside textarea content.
1551
+ */
1552
+ return html = html.replace(/<textarea[^>]*>((.|\n)*?)<\/textarea>/g, (match, capture) => {
1553
+ return match.replace(capture, (match) => {
1554
+ match = match
1555
+ .replace(/&lt;/g, '<')
1556
+ .replace(/&gt;/g, '>')
1557
+ .replace(/&quot;/g, '"')
1558
+ .replace(/&apos;/g, "'")
1559
+ .replace(/&#10;/g, '\n')
1560
+ .replace(/&#13;/g, '\r')
1561
+ .replace(/&nbsp;/g, ' ')
1562
+ // Ensure we collapse consecutive spaces, or they'll be completely removed later.
1563
+ .replace(/\s+/g, ' ');
1564
+
1565
+ return match
1566
+ })
1567
+ })
1568
+ };
1569
+
1498
1570
  /**
1499
1571
  * @type {Map<any,any>}
1500
1572
  */
@@ -1510,7 +1582,7 @@
1510
1582
  */
1511
1583
  const minify = (html, config) => {
1512
1584
  let reinsert_ignored = false;
1513
- const { checked_html, ignored } = getState();
1585
+ const { checked_html, ignored, constants } = getState();
1514
1586
 
1515
1587
  if (!checked_html && !isHtml(html)) return html
1516
1588
 
@@ -1519,17 +1591,17 @@
1519
1591
 
1520
1592
  /* Extract ignored elements. Skipped if prettify has already ignored blocks. */
1521
1593
  if (!ignored && ignore) {
1522
- const { html_with_markers, extracted_map } = extractIgnoredBlocks(html, validated_config);
1594
+ const { html_with_markers, extracted_map } = extractIgnoredBlocks(html);
1523
1595
  html = html_with_markers;
1524
1596
  ignore_map$1 = extracted_map;
1525
1597
  reinsert_ignored = true;
1526
1598
  }
1527
1599
 
1528
1600
  /**
1529
- * Ensure textarea content is specially minified and protected
1601
+ * Ensure textarea content is protected
1530
1602
  * before general minification.
1531
1603
  */
1532
- html = entify(html);
1604
+ html = entify(html, true);
1533
1605
 
1534
1606
  /* All other minification. */
1535
1607
  // Remove ALL newlines and tabs explicitly.
@@ -1541,11 +1613,28 @@
1541
1613
  // Collapse any remaining multiple spaces to single spaces.
1542
1614
  html = html.replace(/ {2,}/g, ' ');
1543
1615
 
1544
- // Remove specific single spaces OR whitespace within closing tags.
1616
+ // Protect space between text content and an opening tag (e.g., "text <a>")
1617
+ html = html.replace(
1618
+ /(\S) (<[a-zA-Z][a-zA-Z0-9_:-]*)/g,
1619
+ `$1___MINIFY-PROTECTED-SPACE___$2`
1620
+ );
1621
+
1622
+ // Protect space between a closing tag and text content (e.g., "</a> text")
1623
+ html = html.replace(
1624
+ /(<\/[a-zA-Z][a-zA-Z0-9_:-]*>) (\S)/g,
1625
+ `$1___MINIFY-PROTECTED-SPACE___$2`
1626
+ );
1627
+
1628
+ // Remove specific single spaces between tags and whitespace within tags.
1545
1629
  html = html.replace(/ >/g, ">"); // <tag > -> <tag>
1546
- html = html.replace(/ </g, "<"); // Text < -> Text< (Also handles leading space before tag)
1547
- html = html.replace(/> /g, ">"); // > Text -> >Text
1548
- html = html.replace(/<\s*\//g, '</'); // < /tag -> </tag>
1630
+ html = html.replace(/ </g, "<"); // leading space before tag
1631
+ html = html.replace(/> /g, ">"); // trailing space after tag
1632
+ html = html.replace(/< /g, "<"); // < tag> -> <tag>
1633
+ html = html.replace(/<\s+\//g, '</'); // < /tag> -> </tag>
1634
+ html = html.replace(/<\/\s+/g, '</'); // </ tag> -> </tag>
1635
+
1636
+ // Unprotect space around inner tags
1637
+ html = html.replace(new RegExp('___MINIFY-PROTECTED-SPACE___', 'g'), ' ');
1549
1638
 
1550
1639
  // Trim spaces around equals signs in attributes (run before value trim)
1551
1640
  // This handles `attr = "value"` -> `attr="value"`
@@ -1566,6 +1655,9 @@
1566
1655
  // Final trim for the whole string
1567
1656
  html = html.trim();
1568
1657
 
1658
+ /* Remove protective entities. */
1659
+ html = dentify(html);
1660
+
1569
1661
  /* Re-insert ignored elements. Skipped unless minify did the ignore. */
1570
1662
  if (reinsert_ignored) {
1571
1663
  html = reinsertIgnoredBlocks(html, ignore_map$1);
@@ -1590,7 +1682,6 @@
1590
1682
  * Isolate tags, content, and comments.
1591
1683
  *
1592
1684
  * @param {string} html The HTML string to evaluate.
1593
- * @returns {string}
1594
1685
  * @example <div>Hello World!</div> =>
1595
1686
  * [#-# : 0 : <div> : #-#]
1596
1687
  * Hello World!
@@ -1602,7 +1693,7 @@
1602
1693
  /* Regex to find tags OR text content between tags. */
1603
1694
  const regex = /(<[^>]+>)|([^<]+)/g;
1604
1695
 
1605
- html = html.replace(regex, (match, c1, c2) => {
1696
+ html.replace(regex, (match, c1, c2) => {
1606
1697
  if (c1) {
1607
1698
  convert.line.push({ type: "tag", value: match });
1608
1699
  } else if (c2 && c2.trim().length > 0) {
@@ -1613,40 +1704,18 @@
1613
1704
  i++;
1614
1705
  return `\n[#-# : ${i} : ${match} : #-#]\n`
1615
1706
  });
1616
-
1617
- return html
1618
- };
1619
-
1620
- /**
1621
- * Preprocess the HTML.
1622
- *
1623
- * @param {string} html The HTML string to preprocess.
1624
- * @returns {string}
1625
- */
1626
- const preprocess = (html) => {
1627
- html = closify(html);
1628
-
1629
- const { config } = getState();
1630
-
1631
- if (config.trim.length > 0) html = trimify(html, config.trim);
1632
-
1633
- html = minify(html);
1634
- html = enqueue(html);
1635
-
1636
- return html
1637
1707
  };
1638
1708
 
1639
1709
  /**
1640
- *
1641
- * @param {import('htmlfy').Config} config
1710
+ * Process enqueued content.
1711
+ *
1642
1712
  * @returns {string}
1643
1713
  */
1644
- const process = (config) => {
1714
+ const process = () => {
1715
+ const { config, constants } = getState();
1645
1716
  const step = " ".repeat(config.tab_size);
1646
1717
  const tag_wrap = config.tag_wrap;
1647
1718
  const content_wrap = config.content_wrap;
1648
- const ignore_with = config.ignore_with;
1649
- const placeholder_template = `-${ignore_with}`;
1650
1719
  const strict = config.strict;
1651
1720
 
1652
1721
  /* Track current number of indentations needed. */
@@ -1662,12 +1731,7 @@
1662
1731
  let current_line_value = source.value;
1663
1732
 
1664
1733
  const is_ignored_content =
1665
- current_line_value.startsWith(placeholder_template + "lt--") ||
1666
- current_line_value.startsWith(placeholder_template + "gt--") ||
1667
- current_line_value.startsWith(placeholder_template + "nl--") ||
1668
- current_line_value.startsWith(placeholder_template + "cr--") ||
1669
- current_line_value.startsWith(placeholder_template + "ws--") ||
1670
- current_line_value.startsWith(placeholder_template + "tab--");
1734
+ current_line_value.startsWith('___HTMLFY_SPECIAL_IGNORE_MARKER_');
1671
1735
 
1672
1736
  let subtrahend = 0;
1673
1737
  const prev_line_data = convert.line[index - 1];
@@ -1685,8 +1749,12 @@
1685
1749
  if (prev_line_value.trim().startsWith("<!doctype")) subtrahend++;
1686
1750
  /* prevLine is a comment. */
1687
1751
  if (prev_line_value.trim().startsWith("<!--")) subtrahend++;
1688
- /* prevLine is a self-closing tag. */
1689
- if (prev_line_value.trim().endsWith("/>")) subtrahend++;
1752
+ /* prevLine is a void element. */
1753
+ if (
1754
+ prev_line_value.trim().endsWith("/>") // native self-closing
1755
+ ||
1756
+ prev_line_value.trim().endsWith(constants.SELF_CLOSING_PLACEHOLDER) // synthetic self-closing
1757
+ ) subtrahend++;
1690
1758
  /* prevLine is a closing tag. */
1691
1759
  if (prev_line_value.trim().startsWith("</")) subtrahend++;
1692
1760
  /* prevLine is text. */
@@ -1702,8 +1770,6 @@
1702
1770
  /**
1703
1771
  * Starts with a single punctuation character.
1704
1772
  * Add punctuation to end of previous line.
1705
- *
1706
- * TODO - Implement inline groups instead?
1707
1773
  */
1708
1774
  if (source.type === 'text' && /^[!,;\.]/.test(current_line_value)) {
1709
1775
  if (current_line_value.length === 1) {
@@ -1714,6 +1780,9 @@
1714
1780
  output_lines[output_lines.length - 1] =
1715
1781
  output_lines.at(-1) + current_line_value.charAt(0);
1716
1782
  current_line_value = current_line_value.slice(1).trim();
1783
+
1784
+ /* If nothing left after extracting punctuation, skip this line. */
1785
+ if (current_line_value.length === 0) return
1717
1786
  }
1718
1787
  }
1719
1788
 
@@ -1729,6 +1798,9 @@
1729
1798
 
1730
1799
  let result = current_line_value;
1731
1800
 
1801
+ /* Remove self-closing placeholder, if needed. */
1802
+ result = unsetSelfClosing(result);
1803
+
1732
1804
  if (
1733
1805
  source.type === 'text' &&
1734
1806
  content_wrap > 0 &&
@@ -1759,9 +1831,9 @@
1759
1831
 
1760
1832
  const tag_name_match = tag_parts[0].match(/<([A-Za-z_:-]+)/);
1761
1833
  const tag_name = tag_name_match ? tag_name_match[1] : "";
1762
- const is_void = VOID_ELEMENTS.includes(tag_name);
1834
+ const is_self_closing = tag_parts.at(-1)?.endsWith("/>") && VOID_ELEMENTS.includes(tag_name);
1763
1835
  const closing_part = tag_parts[1].trim();
1764
- const closing_padding = padding + (strict && is_void ? " " : ""); // Add space if void/strict
1836
+ const closing_padding = padding + (strict && is_self_closing ? " " : "");
1765
1837
 
1766
1838
  wrapped_tag += closing_padding + closing_part;
1767
1839
 
@@ -1786,13 +1858,20 @@
1786
1858
  if (tag_wrap > 0) final_html = protectAttributes(final_html);
1787
1859
 
1788
1860
  /* Extra preserve wrapped content. */
1789
- if (content_wrap > 0 && /\n[ ]*[^\n]*__!i-£___£%__[^\n]*\n/.test(final_html))
1861
+ if (content_wrap > 0 && new RegExp(`/\\n[ ]*[^\\n]*${constants.CONTENT_IGNORE_PLACEHOLDER}[^\\n]*\\n/`).test(final_html))
1790
1862
  final_html = finalProtectContent(final_html);
1791
1863
 
1792
1864
  /* Remove line returns, tabs, and consecutive spaces within html elements or their content. */
1793
1865
  final_html = final_html.replace(
1794
- /<(?<Element>.+).*>[^<]*?[^><\/\s][^<]*?<\/{1}\k<Element>|<script[^>]*>\s+<\/script>|<(\w+)>\s+<\/(\w+)|<(?:([\w:\._-]+)|([\w:\._-]+)[^>]*[^\/])>\s+<\/([\w:\._-]+)>/g,
1795
- match => match.replace(/\n|\t|\s{2,}/g, '')
1866
+ /<(?<Element>[^>\s]+)[^>]*>[^<]*?[^><\/\s][^<]*?<\/\k<Element>>|<script[^>]*>[\s]*<\/script>|<([\w:\._-]+)([^>]*)><\/\2>|<([\w:\._-]+)([^>]*)>[\s]+<\/\4>/g,
1867
+ match => {
1868
+ // Check if this contains placeholder
1869
+ if (match.includes(constants.SELF_CLOSING_PLACEHOLDER) || match.includes(constants.CONTENT_IGNORE_PLACEHOLDER)) {
1870
+ return match // Don't modify if it contains the placeholder
1871
+ }
1872
+
1873
+ return match.replace(/\n|\t|\s{2,}/g, '')
1874
+ }
1796
1875
  );
1797
1876
 
1798
1877
  /* Revert wrapped content. */
@@ -1825,12 +1904,17 @@
1825
1904
  /* Return content as-is if it does not contain any HTML elements. */
1826
1905
  if (!checked_html && !isHtml(html)) return html
1827
1906
 
1828
- const validated_config = config ? validateConfig(config) : { ...CONFIG };
1907
+ /* Runs setState for config. */
1908
+ const validated_config = validateConfig(config || {});
1909
+
1829
1910
  const ignore = validated_config.ignore.length > 0;
1830
1911
 
1912
+ /* Allows you to trimify before ignoring. */
1913
+ if (validated_config.trim.length > 0) html = trimify(html, validated_config.trim);
1914
+
1831
1915
  /* Extract ignored elements. */
1832
1916
  if (!ignored && ignore) {
1833
- const { html_with_markers, extracted_map } = extractIgnoredBlocks(html, validated_config);
1917
+ const { html_with_markers, extracted_map } = extractIgnoredBlocks(html);
1834
1918
  html = html_with_markers;
1835
1919
  ignore_map = extracted_map;
1836
1920
  reinsert_ignored = true;
@@ -1839,8 +1923,12 @@
1839
1923
  /* Preserve html text within attribute values. */
1840
1924
  html = setIgnoreAttribute(html);
1841
1925
 
1842
- html = preprocess(html);
1843
- html = process(validated_config);
1926
+ /* Insert placeholder for void elements that aren't self-closing. */
1927
+ html = setSelfClosing(html);
1928
+
1929
+ html = minify(html);
1930
+ enqueue(html);
1931
+ html = process();
1844
1932
 
1845
1933
  /* Revert html text within attribute values. */
1846
1934
  html = unsetIgnoreAttribute(html);