Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
/**
* @typedef {Object} ShjOptions
* @property {Boolean} [hideLineNumbers=false] Indicates whether to hide line numbers
* @property {Boolean} [wrap=false] Wrap long lines instead of scrolling horizontally
*/

/**
Expand Down Expand Up @@ -125,12 +126,20 @@ export async function tokenize(src, lang, token) {
* @returns {Promise<string>} The highlighted string
*/
export async function highlightText(src, lang, multiline = true, opt = {}) {
let tmp = ''
await tokenize(src, lang, (str, type) => tmp += toSpan(sanitize(str), type))

return multiline
? `<div><div class="shj-numbers">${'<div></div>'.repeat(!opt.hideLineNumbers && src.split('\n').length)}</div><div>${tmp}</div></div>`
: tmp;
// numbering a wrapped line needs its own grid row, so each line gets its own cell
let rows = multiline && opt.wrap && !opt.hideLineNumbers,
tmp = rows ? [''] : '';
await tokenize(src, lang, (str, type) => rows
? sanitize(str).split('\n').forEach((line, i) => i
? tmp.push(toSpan(line, type))
: tmp[tmp.length - 1] += toSpan(line, type))
: tmp += toSpan(sanitize(str), type))

return rows
? `<div class="shj-wrap">${tmp.map(line => `<div class="shj-numbers"><div></div></div><div>${line}</div>`).join('')}</div>`
: multiline
? `<div${opt.wrap ? ' class="shj-wrap"' : ''}><div class="shj-numbers">${'<div></div>'.repeat(!opt.hideLineNumbers && src.split('\n').length)}</div><div>${tmp}</div></div>`
: tmp;
}

/**
Expand Down
13 changes: 9 additions & 4 deletions src/themes/default.css
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,21 @@
[class*="shj-lang-"] ::selection {background: #bdf5}
[class*="shj-lang-"] > div {
display: flex;
overflow: auto
overflow: auto;
counter-reset: line
}
[class*="shj-lang-"] > div :last-child {
flex: 1;
outline: none
}
.shj-numbers {
padding-left: 5px;
counter-reset: line
[class*="shj-lang-"] > .shj-wrap {
display: grid;
grid-template-columns: auto 1fr;
overflow: visible;
white-space: pre-wrap;
overflow-wrap: break-word
}
.shj-numbers {padding-left: 5px}
.shj-numbers div {padding-right: 5px}
.shj-numbers div::before {
color: #999;
Expand Down