|
| 1 | +// reference: https://github.com/showdownjs/showdown/blob/fc7ac1e1ca90d1849d120025105d1f45c9d4f8f6/src/subParsers/makehtml/headers.js#L58 |
| 2 | +/* istanbul ignore next */ |
| 3 | +import showdown, { ShowdownOptions } from 'showdown'; |
| 4 | + |
| 5 | +export function headerId( |
| 6 | + m: string, |
| 7 | + options: ShowdownOptions, |
| 8 | + hashLinkCounts: { [key: string]: number }, |
| 9 | +) { |
| 10 | + let title; |
| 11 | + let prefix; |
| 12 | + |
| 13 | + // It is separate from other options to allow combining prefix and customized |
| 14 | + if (options.customizedHeaderId) { |
| 15 | + const match = m.match(/\{([^{]+?)}\s*$/); |
| 16 | + if (match && match[1]) { |
| 17 | + m = match[1]; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + title = m; |
| 22 | + |
| 23 | + // Prefix id to prevent causing inadvertent pre-existing style matches. |
| 24 | + if (showdown.helper.isString(options.prefixHeaderId)) { |
| 25 | + prefix = options.prefixHeaderId; |
| 26 | + } else if (options.prefixHeaderId === true) { |
| 27 | + prefix = 'section-'; |
| 28 | + } else { |
| 29 | + prefix = ''; |
| 30 | + } |
| 31 | + |
| 32 | + if (!options.rawPrefixHeaderId) { |
| 33 | + title = prefix + title; |
| 34 | + } |
| 35 | + |
| 36 | + if (options.ghCompatibleHeaderId) { |
| 37 | + title = title |
| 38 | + .replace(/ /g, '-') |
| 39 | + // replace previously escaped chars (&, ¨ and $) |
| 40 | + .replace(/&/g, '') |
| 41 | + .replace(/¨T/g, '') |
| 42 | + .replace(/¨D/g, '') |
| 43 | + // replace rest of the chars (&~$ are repeated as they might have been escaped) |
| 44 | + // borrowed from github's redcarpet (some they should produce similar results) |
| 45 | + .replace(/[&+$,/:;=?@"#{}|^¨~[\]`\\*)(%.!'<>]/g, '') |
| 46 | + .toLowerCase(); |
| 47 | + } else if (options.rawHeaderId) { |
| 48 | + title = title |
| 49 | + .replace(/ /g, '-') |
| 50 | + // replace previously escaped chars (&, ¨ and $) |
| 51 | + .replace(/&/g, '&') |
| 52 | + .replace(/¨T/g, '¨') |
| 53 | + .replace(/¨D/g, '$') |
| 54 | + // replace " and ' |
| 55 | + .replace(/["']/g, '-') |
| 56 | + .toLowerCase(); |
| 57 | + } else { |
| 58 | + title = title.replace(/[^\w]/g, '').toLowerCase(); |
| 59 | + } |
| 60 | + |
| 61 | + if (options.rawPrefixHeaderId) { |
| 62 | + title = prefix + title; |
| 63 | + } |
| 64 | + |
| 65 | + if (hashLinkCounts[title]) { |
| 66 | + title = `${title}-${hashLinkCounts[title]++}`; |
| 67 | + } else { |
| 68 | + hashLinkCounts[title] = 1; |
| 69 | + } |
| 70 | + return title; |
| 71 | +} |
0 commit comments