diff --git a/README.md b/README.md index 0caac96a..f3f84145 100644 --- a/README.md +++ b/README.md @@ -159,13 +159,23 @@ stickyFileHeaders(): void ### Diff2HtmlUI Configuration - `synchronisedScroll`: scroll both panes in side-by-side mode: `true` or `false`, default is `true` -- `highlight`: syntax highlight the code on the diff: `true` or `false`, default is `true` +- `highlight`: syntax highlight the code in the diff automatically during `draw()`: `true` or `false`, default is + `true`. With `false`, you can still call `highlightCode()` manually. +- `highlightMultiline`: highlight the old and new sides of each hunk in context: `true` or `false`, default is `true` + (also when `undefined`). Use `false` for per-line syntax highlighting, including when calling `highlightCode()` + manually. Multiline highlighting never carries syntax state between hunks. Standalone CLI HTML using this UI bundle + inherits the default; there is no separate CLI flag. - `fileListToggle`: allow the file summary list to be toggled: `true` or `false`, default is `true` - `fileListStartVisible`: choose if the file summary list starts visible: `true` or `false`, default is `false` - `fileContentToggle`: allow each file contents to be toggled: `true` or `false`, default is `true` - `stickyFileHeaders`: make file headers sticky: `true` or `false`, default is `true` - [All the options](#diff2html-configuration) from Diff2Html are also valid configurations in Diff2HtmlUI +For large diffs, the UI switches to per-line highlighting for a file with more than 4,096 rendered code containers, or +for a hunk when either side exceeds 256 lines or 32,768 UTF-16 code units (including separators). The file count +includes blank lines, placeholders, and end-of-file markers. A side-by-side file can reach the limit sooner because it +also renders context on both sides. These are internal limits, not API guarantees; they do not truncate the diff. + ### Diff2HtmlUI Browser #### Mandatory HTML resource imports diff --git a/src/__tests__/multiline-highlighting-tests.ts b/src/__tests__/multiline-highlighting-tests.ts new file mode 100644 index 00000000..c059abe3 --- /dev/null +++ b/src/__tests__/multiline-highlighting-tests.ts @@ -0,0 +1,120 @@ +import { isHighlightMarkup, selectHunkLines, splitHighlightedLines } from '../ui/js/highlight.js-helpers'; +import { shouldHighlightHunks } from '../ui/js/highlight-hunks'; + +it.each([ + [undefined, 4095, true], + [undefined, 4096, true], + [true, 4096, true], + [false, 4, false], + [undefined, 4097, false], + [true, 4097, false], +])('routes highlightMultiline=%s with %d code containers to hunk highlighting: %s', (option, containers, grouped) => { + expect(shouldHighlightHunks(option, containers)).toBe(grouped); +}); + +describe('isHighlightMarkup', () => { + it.each([ + '', + 'text <body> & </span> 😀', + 'const', + 'a\nb', + 'ab', + ])('accepts canonical text and balanced class-only spans: %s', value => { + expect(isHighlightMarkup(value)).toBe(true); + }); + + it.each([ + 'text', + 'text', + 'text', + 'text', + 'text', + 'text', + 'text', + 'text', + 'text', + ])('rejects raw markup the HTML parser could repair or normalize: %s', value => { + expect(isHighlightMarkup(value)).toBe(false); + }); +}); + +const start = (offset: number, node: string) => ({ event: 'start' as const, offset, node }); +const stop = (offset: number, node: string) => ({ event: 'stop' as const, offset, node }); +const text = (value: string): string => value; + +describe('splitHighlightedLines', () => { + it('reopens tokens in nesting order over decoded UTF-16 text, even on blank lines', () => { + const lines = ['\tšŸ˜€& ', '', ' ', '']; + const text = '\tšŸ˜€& \n\n \n'; + const events = [start(0, 'language-js'), start(1, 'comment'), stop(13, 'comment'), stop(15, 'language-js')]; + + expect(splitHighlightedLines(lines, text, events)).toEqual([ + [start(0, 'language-js'), start(1, 'comment'), stop(5, 'comment'), stop(5, 'language-js')], + [start(0, 'language-js'), start(0, 'comment'), stop(0, 'comment'), stop(0, 'language-js')], + [start(0, 'language-js'), start(0, 'comment'), stop(6, 'comment'), stop(8, 'language-js')], + [], + ]); + }); + + it('rejects changed text, line counts and invalid event streams', () => { + expect(splitHighlightedLines(['šŸ˜€&'], 'šŸ˜€<', [])).toBeNull(); + expect(splitHighlightedLines(['x'], 'x\n', [])).toBeNull(); + expect(splitHighlightedLines(['x', ''], 'x', [])).toBeNull(); + expect(splitHighlightedLines(['x'], 'x', [start(1, 'a'), stop(0, 'a')])).toBeNull(); + expect(splitHighlightedLines(['x'], 'x', [start(0, 'a'), stop(2, 'a')])).toBeNull(); + expect(splitHighlightedLines(['x'], 'x', [start(0, 'a'), start(0, 'b'), stop(1, 'a'), stop(1, 'b')])).toBeNull(); + expect(splitHighlightedLines(['x'], 'x', [start(0, 'a')])).toBeNull(); + }); +}); + +describe('selectHunkLines', () => { + it('chooses the new result once for unified context without conflating split targets', () => { + const old = ['deleted', 'shared', 'left context']; + const next = ['inserted', 'shared', 'right context']; + const highlightSide = jest.fn().mockReturnValueOnce(['d', 'old', 'l']).mockReturnValueOnce(['i', 'new', 'r']); + expect(selectHunkLines([old, next], text, highlightSide)).toEqual( + new Map([ + ['deleted', 'd'], + ['shared', 'new'], + ['left context', 'l'], + ['inserted', 'i'], + ['right context', 'r'], + ]), + ); + expect(highlightSide.mock.calls).toEqual([[old], [next]]); + }); + + it('highlights only the present side of a one-sided hunk', () => { + const highlightSide = jest.fn().mockReturnValue(['inserted']); + expect(selectHunkLines([[], ['target']], text, highlightSide)).toEqual(new Map([['target', 'inserted']])); + expect(highlightSide.mock.calls).toEqual([[['target']]]); + }); + + it('declines all results if either side cannot be projected', () => { + const highlightSide = jest.fn().mockReturnValueOnce(['old']).mockReturnValueOnce(null); + expect(selectHunkLines([['target'], ['target']], text, highlightSide)).toBeNull(); + expect(highlightSide).toHaveBeenCalledTimes(2); + highlightSide.mockReturnValueOnce([]); + expect(selectHunkLines([['target'], []], text, highlightSide)).toBeNull(); + }); + + it('declines both sides before highlighting if either exceeds 256 logical lines', () => { + const side = Array(256).fill(''); + const highlightSide = jest.fn((lines: string[]) => lines); + expect(selectHunkLines([['old'], side], text, highlightSide)).not.toBeNull(); + expect(highlightSide).toHaveBeenCalledTimes(2); + highlightSide.mockClear(); + expect(selectHunkLines([['old'], [...side, '']], text, highlightSide)).toBe('over-budget'); + expect(highlightSide).not.toHaveBeenCalled(); + }); + + it('counts snippet separators and UTF-16 code units toward the 32 Ki budget', () => { + const first = 'šŸ˜€'.repeat(16383); + const highlightSide = jest.fn((lines: string[]) => lines); + expect(selectHunkLines([[first, 'x'], []], text, highlightSide)).not.toBeNull(); + expect(highlightSide).toHaveBeenCalledTimes(1); + highlightSide.mockClear(); + expect(selectHunkLines([[first, 'xx'], []], text, highlightSide)).toBe('over-budget'); + expect(highlightSide).not.toHaveBeenCalled(); + }); +}); diff --git a/src/ui/js/diff2html-ui-base.ts b/src/ui/js/diff2html-ui-base.ts index f2379501..9553086a 100644 --- a/src/ui/js/diff2html-ui-base.ts +++ b/src/ui/js/diff2html-ui-base.ts @@ -1,12 +1,21 @@ -import { closeTags, nodeStream, mergeStreams, getLanguage } from './highlight.js-helpers'; +import { + getLanguage, + isHighlightMarkup, + mergeStreams, + nodeStream, + selectHunkLines, + splitHighlightedLines, +} from './highlight.js-helpers'; +import { collectHighlightHunks, isBlankCodeLine, shouldHighlightHunks } from './highlight-hunks'; import { html, Diff2HtmlConfig, defaultDiff2HtmlConfig } from '../../diff2html'; import { DiffFile } from '../../types'; -import { HighlightResult, HLJSApi } from 'highlight.js'; +import { HLJSApi } from 'highlight.js'; export interface Diff2HtmlUIConfig extends Diff2HtmlConfig { synchronisedScroll?: boolean; highlight?: boolean; + highlightMultiline?: boolean; fileListToggle?: boolean; fileListStartVisible?: boolean; highlightLanguages?: Map; @@ -36,12 +45,13 @@ export const defaultDiff2HtmlUIConfig = { }; export class Diff2HtmlUI { - readonly config: typeof defaultDiff2HtmlUIConfig; + readonly config: typeof defaultDiff2HtmlUIConfig & Pick; readonly diffHtml: string; readonly targetElement: HTMLElement; readonly hljs: HLJSApi | null = null; currentSelectionColumnId = -1; + private readonly syntaxNodes = new WeakSet(); constructor(target: HTMLElement, diffInput?: string | DiffFile[], config: Diff2HtmlUIConfig = {}, hljs?: HLJSApi) { this.config = { ...defaultDiff2HtmlUIConfig, ...config }; @@ -163,34 +173,65 @@ export class Diff2HtmlUI { hljsLanguage = 'plaintext'; } - // Collect all the code lines and execute the highlight on them const codeLines = file.querySelectorAll('.d2h-code-line-ctn'); - codeLines.forEach(line => { - const text = line.textContent; - const lineParent = line.parentNode; - - if (text === null || lineParent === null || !this.isElement(lineParent)) return; - - const result: HighlightResult = closeTags( - hljs.highlight(text, { - language: hljsLanguage, - ignoreIllegals: true, - }), - ); - - const originalStream = nodeStream(line); - if (originalStream.length) { - const resultNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); - resultNode.innerHTML = result.value; - result.value = mergeStreams(originalStream, nodeStream(resultNode), text); + const hunks = shouldHighlightHunks(this.config.highlightMultiline, codeLines.length) + ? collectHighlightHunks(file, codeLines.length) + : null; + const template = file.ownerDocument.createElement('template'); + const options = { language: hljsLanguage, ignoreIllegals: true }; + const highlight = (text: string) => { + const result = hljs.highlight(text, options); + if (result.language && /[\t\n\f\r ]/.test(result.language)) return null; + const { value } = result; + if (typeof value !== 'string' || !isHighlightMarkup(value)) return null; + template.innerHTML = value; + return result; + }; + const highlightSide = (lines: string[]) => { + const result = highlight(lines.join('\n')); + if (result === null) return null; + const split = splitHighlightedLines(lines, template.content.textContent!, nodeStream(template.content)); + return split?.map((events, i) => ({ events, text: lines[i], language: result.language })) ?? null; + }; + const prepare = (target: Element, result: NonNullable>[number]) => { + if (isBlankCodeLine(target)) return null; + const fragment = mergeStreams(target, result.events, result.text, this.syntaxNodes); + return { target, fragment, language: result.language }; + }; + const apply = (prepared: ReturnType): void => { + if (prepared === null) return; + const { target, fragment, language } = prepared; + target.replaceChildren(fragment); + markHighlighted(target, language); + }; + const highlightLine = (target: Element): void => { + const first = target.firstChild; + const plain = first?.nodeType === 3 && first === target.lastChild; + if (!plain && isBlankCodeLine(target)) return; + const text = plain ? first.nodeValue! : target.textContent!; + if (text.startsWith(' ') && isEofMarker(target)) return; + const result = highlight(text); + if (result === null || template.content.textContent !== text) return; + if (plain) { + // For a plain source line the validated output already is the final token tree. + ownSyntaxSpans(template.content, this.syntaxNodes); + apply({ target, fragment: template.content, language: result.language }); + } else { + const events = nodeStream(template.content); + apply(prepare(target, { events, text, language: result.language })); } + }; - line.classList.add('hljs'); - if (result.language) { - line.classList.add(result.language); - } - line.innerHTML = result.value; - }); + if (hunks === null) { + codeLines.forEach(highlightLine); + return; + } + for (const sides of hunks) { + const selected = selectHunkLines(sides, line => line.textContent!, highlightSide); + if (selected === null || selected === 'over-budget') { + new Set(sides[0].concat(sides[1])).forEach(highlightLine); + } else Array.from(selected, ([target, result]) => prepare(target, result)).forEach(apply); + } }); } @@ -218,8 +259,27 @@ export class Diff2HtmlUI { return hashTag; } +} - private isElement(arg?: unknown): arg is Element { - return arg !== null && (arg as Element)?.classList !== undefined; +function ownSyntaxSpans(root: ParentNode, emitted: WeakSet): void { + for (let span = root.firstElementChild; span !== null; span = span.nextElementSibling) { + emitted.add(span); + ownSyntaxSpans(span, emitted); } } + +function markHighlighted(target: Element, language?: string): void { + if (language) target.classList.add('hljs', language); + else target.classList.add('hljs'); +} + +function isEofMarker(target: Element): boolean { + const prefix = target.previousElementSibling; + const cell = target.parentElement?.parentElement; + return ( + prefix?.classList.contains('d2h-code-line-prefix') === true && + prefix.textContent === '\\' && + cell?.classList.contains('d2h-cntx') === true && + cell.previousElementSibling?.textContent?.trim() === '' + ); +} diff --git a/src/ui/js/highlight-hunks.ts b/src/ui/js/highlight-hunks.ts new file mode 100644 index 00000000..1ac44a75 --- /dev/null +++ b/src/ui/js/highlight-hunks.ts @@ -0,0 +1,181 @@ +type HunkSides = [Element[], Element[]]; +type Layout = 'unified' | 'split' | 'wrapped'; + +const hunkHeader = /^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(?:\s|$)/; +const tableBody = '> .d2h-code-wrapper > table.d2h-diff-table > tbody.d2h-diff-tbody'; + +const maxFileCodeContainers = 4096; + +export function shouldHighlightHunks(option: boolean | undefined, codeLineCount: number): boolean { + return option !== false && codeLineCount <= maxFileCodeContainers; +} + +export function collectHighlightHunks(file: Element, codeLineCount: number): HunkSides[] | null { + const unified = file.querySelectorAll(`:scope > .d2h-file-diff ${tableBody}`); + const wrapped = file.querySelectorAll(`:scope > .d2h-files-diff.d2h-wrap-lines ${tableBody}`); + const split = file.querySelectorAll(`:scope > .d2h-files-diff > .d2h-file-side-diff ${tableBody}`); + const layout: Layout = unified.length === 1 ? 'unified' : wrapped.length === 1 ? 'wrapped' : 'split'; + const bodies = layout === 'unified' ? unified : layout === 'wrapped' ? wrapped : split; + if ( + bodies.length !== (layout === 'split' ? 2 : 1) || + bodies.length !== unified.length + wrapped.length + split.length + ) { + return null; + } + + const numberClass = layout === 'unified' ? 'd2h-code-linenumber' : 'd2h-code-side-linenumber'; + const contentClass = layout === 'unified' ? 'd2h-code-line' : 'd2h-code-side-line'; + const hunks: { starts: number[]; sides: HunkSides }[] = []; + let seen = 0; + + for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) { + const body = bodies[bodyIndex]; + let index = -1; + for (let row = body.firstElementChild; row !== null; row = row.nextElementSibling) { + if (row.tagName !== 'TR') return null; + const cells = (row as HTMLTableRowElement).cells; + if (cells[0]?.classList.contains('d2h-info')) { + const header = infoHeader(cells, layout, numberClass, contentClass); + if (header === null) return null; + if ( + bodyIndex === 0 && + row === body.firstElementChild && + row.nextElementSibling === null && + header === 'File without changes' + ) + continue; + index++; + if (bodyIndex === 0) { + const starts = header.match(hunkHeader)?.slice(1).map(Number); + if (!starts?.every(Number.isSafeInteger)) return null; + hunks.push({ starts, sides: [[], []] }); + } else if (header !== '' || index >= hunks.length) return null; + continue; + } + + if (index < 0 || cells.length !== (layout === 'wrapped' ? 4 : 2)) return null; + const { starts, sides } = hunks[index]; + for (let column = 0; column < cells.length; column += 2) { + const number = cells[column]; + const code = cells[column + 1]; + if (!isCell(number) || !isCell(code)) return null; + const numbers = readNumbers(number, layout); + const content = code.firstElementChild; + if (!numbers || !content || content.nextElementSibling !== null) return null; + const prefix = content.firstElementChild; + const target = prefix?.nextElementSibling; + if ( + !prefix || + !target || + target.nextElementSibling !== null || + !isSpan(prefix, 'd2h-code-line-prefix') || + !isSpan(target, 'd2h-code-line-ctn') + ) { + return null; + } + seen++; + + const marker = prefix.textContent; + const classes = code.className; + const numberClasses = number.className; + if (numbers[0] === '' && (numbers.length === 1 || numbers[1] === '')) { + if ( + marker === '\\' && + target.textContent?.startsWith(' ') && + classes === 'd2h-cntx' && + numberClasses === `${numberClass} d2h-cntx` && + content.className === contentClass + ) + continue; + if ( + layout !== 'unified' && + classes === 'd2h-cntx d2h-emptyplaceholder' && + numberClasses === `${numberClass} d2h-code-side-emptyplaceholder ${classes}` && + content.className === `${contentClass} d2h-code-side-emptyplaceholder` && + marker === '\u00a0' && + isBlankCodeLine(target) + ) + continue; + return null; + } + const kind = marker === '+' ? 'd2h-ins' : marker === '-' ? 'd2h-del' : marker === '\u00a0' ? 'd2h-cntx' : ''; + if ( + !kind || + (classes !== kind && classes !== `${kind} d2h-change`) || + numberClasses !== `${numberClass} ${classes}` || + content.className !== contentClass + ) + return null; + const firstSide = layout === 'split' ? bodyIndex : column / 2; + for (let i = 0; i < numbers.length; i++) { + const side = firstSide + i; + const belongs = marker !== (side === 0 ? '+' : '-'); + const value = numbers[i]; + if (belongs !== (value !== '')) return null; + if (!belongs) continue; + const expected = starts[side] + sides[side].length; + if (!Number.isSafeInteger(expected) || value !== String(expected)) return null; + sides[side].push(target); + } + } + } + if (bodyIndex === 1 && index + 1 !== hunks.length) return null; + } + return seen === codeLineCount ? hunks.map(hunk => hunk.sides) : null; +} + +function isCell(cell: HTMLTableCellElement, className?: string, colSpan = 1): boolean { + return ( + cell.tagName === 'TD' && + cell.rowSpan === 1 && + cell.colSpan === colSpan && + (className === undefined || cell.classList.contains(className)) + ); +} + +function isSpan(element: Element, className: string): boolean { + return element.tagName === 'SPAN' && element.classList.contains(className); +} + +export function isBlankCodeLine(target: Element): boolean { + return target.childNodes.length === 1 && target.firstElementChild?.tagName === 'BR'; +} + +function readNumbers(cell: Element, layout: Layout): string[] | null { + if (layout !== 'unified') return cell.children.length === 0 ? [cell.textContent!.trim()] : null; + const old = cell.firstElementChild; + const next = old?.nextElementSibling; + if ( + !old || + !next || + next.nextElementSibling !== null || + old.tagName !== 'DIV' || + next.tagName !== 'DIV' || + !old.classList.contains('line-num1') || + !next.classList.contains('line-num2') || + old.children.length || + next.children.length + ) + return null; + return [old.textContent!.trim(), next.textContent!.trim()]; +} + +function infoHeader( + cells: HTMLCollectionOf, + layout: Layout, + numberClass: string, + contentClass: string, +): string | null { + const last = cells[cells.length - 1]; + if (layout === 'wrapped') { + if (cells.length !== 1 || !isCell(last, 'd2h-info', 4)) return null; + } else if ( + !isCell(last, 'd2h-info') || + (cells.length !== 1 && (cells.length !== 2 || !isCell(cells[0], numberClass) || cells[0].childNodes.length !== 0)) + ) + return null; + const header = last.firstElementChild; + if (last.children.length !== 1 || !header?.classList.contains(contentClass)) return null; + const text = header.textContent!.trim(); + return layout !== 'wrapped' && cells.length === 1 && text !== 'File without changes' ? null : text; +} diff --git a/src/ui/js/highlight.js-helpers.ts b/src/ui/js/highlight.js-helpers.ts index 3bedb49b..3f9a6906 100644 --- a/src/ui/js/highlight.js-helpers.ts +++ b/src/ui/js/highlight.js-helpers.ts @@ -3,160 +3,188 @@ * Used to highlight selected html elements using context */ -import { HighlightResult } from 'highlight.js'; +const spanStart = '' || (next !== -1 && next < quote)) return false; + depth++; + } + tag = next; + } + return depth === 0; } -/* Stream merging */ - -type NodeEvent = { - event: 'start' | 'stop'; - offset: number; - node: Node; -}; +type NodeEvent = { event: 'start' | 'stop'; offset: number; node: T }; -export function nodeStream(node: Node): NodeEvent[] { - const result: NodeEvent[] = []; - - const nodeStream = (node: Node, offset: number): number => { - for (let child = node.firstChild; child; child = child.nextSibling) { - if (child.nodeType === 3 && child.nodeValue !== null) { - offset += child.nodeValue.length; - } else if (child.nodeType === 1) { - result.push({ - event: 'start', - offset: offset, - node: child, - }); - offset = nodeStream(child, offset); - // Prevent void elements from having an end tag that would actually - // double them in the output. There are more void elements in HTML - // but we list only those realistically expected in code display. - if (!tag(child).match(/br|hr|img|input/)) { - result.push({ - event: 'stop', - offset: offset, - node: child, - }); - } +export function nodeStream(root: Node, emitted?: WeakSet): NodeEvent[] { + const events: NodeEvent[] = []; + let offset = 0; + function visit(node: Node): void { + for (let child = node.firstChild; child !== null; child = child.nextSibling) { + if (child.nodeType === 3) { + offset += child.nodeValue!.length; + } else { + const authored = !emitted?.has(child); + if (authored) events.push({ event: 'start', offset, node: child }); + visit(child); + if (authored) events.push({ event: 'stop', offset, node: child }); } } - return offset; - }; - - nodeStream(node, 0); - - return result; + } + visit(root); + return events; } -export function mergeStreams(original: NodeEvent[], highlighted: NodeEvent[], value: string): string { - let processed = 0; - let result = ''; - const nodeStack = []; - - function isElement(arg?: unknown): arg is Element { - return arg !== null && (arg as Element)?.attributes !== undefined; +export function splitHighlightedLines( + lines: string[], + text: string, + events: NodeEvent[], +): NodeEvent[][] | null { + if (lines.join('\n') !== text) return null; + const result: NodeEvent[][] = []; + const stack: T[] = []; + let cursor = 0; + let start = 0; + for (const line of lines) { + const end = start + line.length; + const segment = stack.map>(node => ({ event: 'start', offset: 0, node })); + let previous = start; + while (cursor < events.length && events[cursor].offset <= end) { + const { event, node, offset } = events[cursor++]; + if (!Number.isSafeInteger(offset) || offset < previous) return null; + if (event === 'start') stack.push(node); + else if (!stack.length || stack.pop() !== node) return null; + segment.push({ event, node, offset: offset - start }); + previous = offset; + } + for (let i = stack.length - 1; i >= 0; i--) { + segment.push({ event: 'stop', offset: line.length, node: stack[i] }); + } + result.push(segment); + start = end + 1; } + return stack.length === 0 && cursor === events.length ? result : null; +} - function selectStream(): NodeEvent[] { - if (!original.length || !highlighted.length) { - return original.length ? original : highlighted; - } - if (original[0].offset !== highlighted[0].offset) { - return original[0].offset < highlighted[0].offset ? original : highlighted; +// Bound the lexer input and temporary token DOM, including when a few source lines are very long. +const maxHunkSideLines = 256; +const maxHunkSideLength = 32 * 1024; + +export function selectHunkLines( + sides: readonly [T[], T[]], + getText: (target: T) => string, + highlightSide: (lines: string[]) => U[] | null, +): Map | 'over-budget' | null { + if (sides.some(side => side.length > maxHunkSideLines)) return 'over-budget'; + const snippets = sides.map(side => side.map(getText)); + for (const lines of snippets) { + let length = lines.length - 1; + for (const line of lines) { + length += line.length; + if (length > maxHunkSideLength) return 'over-budget'; + if (line.includes('\n')) return null; } + } - /* - To avoid starting the stream just before it should stop the order is - ensured that original always starts first and closes last: - if (event1 == 'start' && event2 == 'start') - return original; - if (event1 == 'start' && event2 == 'stop') - return highlighted; - if (event1 == 'stop' && event2 == 'start') - return original; - if (event1 == 'stop' && event2 == 'stop') - return highlighted; - ... which is collapsed to: - */ - return highlighted[0].event === 'start' ? original : highlighted; + const selected = new Map(); + // The new side overwrites the old side only for targets shared by unified context rows. + for (const [index, side] of sides.entries()) { + if (!side.length) continue; + const tokens = highlightSide(snippets[index]); + if (tokens?.length !== side.length) return null; + side.forEach((target, index) => selected.set(target, tokens[index])); } + return selected; +} - function open(node: Node): void { - if (!isElement(node)) { - throw new Error('Node is not an Element'); - } +export function mergeStreams( + target: Element, + highlighted: NodeEvent[], + value: string, + emitted: WeakSet, +): DocumentFragment { + const original = + target.childNodes.length === 1 && target.firstChild!.nodeType === 3 ? [] : nodeStream(target, emitted); + const fragment = target.ownerDocument.createDocumentFragment(); + const syntax: Node[] = []; + let parent: Node = fragment; + let offset = 0; + let sourceIndex = 0; + let syntaxIndex = 0; - result += `<${tag(node)} ${Array() - .map.call(node.attributes, attr => `${attr.nodeName}="${escapeHTML(attr.value).replace(/"/g, '"')}"`) - .join(' ')}>`; + function appendText(end: number): void { + if (offset < end) parent.appendChild(target.ownerDocument.createTextNode(value.slice(offset, end))); + offset = end; } - function close(node: Node): void { - result += ''; + function open(node: Node, token: boolean): void { + // Template contents, unlike normal authored children, aren't in the text/event stream. + const clone = node.cloneNode(node.nodeName === 'TEMPLATE'); + parent.appendChild(clone); + parent = clone; + if (token) emitted.add(clone); } - function render(event: NodeEvent): void { - (event.event === 'start' ? open : close)(event.node); + function render({ event, node }: NodeEvent, token: boolean): void { + if (event === 'start') open(node, token); + else parent = parent.parentNode!; } - while (original.length || highlighted.length) { - let stream = selectStream(); - result += escapeHTML(value.substring(processed, stream[0].offset)); - processed = stream[0].offset; - if (stream === original) { - /* - On any opening or closing tag of the original markup we first close - the entire highlighted node stack, then render the original tag along - with all the following original tags at the same offset and then - reopen all the tags on the highlighted stack. - */ - nodeStack.reverse().forEach(close); + function originalFirst(): boolean { + const source = original[sourceIndex]; + const token = highlighted[syntaxIndex]; + return ( + source !== undefined && + (token === undefined || + source.offset < token.offset || + (source.offset === token.offset && token.event === 'start')) + ); + } + + while (sourceIndex < original.length || syntaxIndex < highlighted.length) { + if (originalFirst()) { + appendText(original[sourceIndex].offset); + // Original markup stays outside syntax at its boundaries, including when a token crosses it. + for (let i = 0; i < syntax.length; i++) parent = parent.parentNode!; do { - render(stream.splice(0, 1)[0]); - stream = selectStream(); - } while (stream === original && stream.length && stream[0].offset === processed); - nodeStack.reverse().forEach(open); + render(original[sourceIndex++], false); + } while (originalFirst() && original[sourceIndex].offset === offset); + syntax.forEach(node => open(node, true)); } else { - if (stream[0].event === 'start') { - nodeStack.push(stream[0].node); + const token = highlighted[syntaxIndex++]; + appendText(token.offset); + const stop = highlighted[syntaxIndex]; + if ( + original.length === 0 && + token.event === 'start' && + stop?.node === token.node && + token.node.firstChild?.nodeType === 3 && + token.node.firstChild === token.node.lastChild && + token.node.firstChild.nodeValue === value.slice(offset, stop.offset) + ) { + // A whole, unnested token on a plain source line can be moved from the inert parse. + parent.appendChild(token.node); + emitted.add(token.node); + offset = stop.offset; + syntaxIndex++; } else { - nodeStack.pop(); + if (token.event === 'start') syntax.push(token.node); + else syntax.pop(); + render(token, true); } - render(stream.splice(0, 1)[0]); } } - - return result + escapeHTML(value.substr(processed)); -} - -// https://github.com/hexojs/hexo-util/blob/979873b63a725377c2bd6ad834d790023496130d/lib/highlight.js#L123 -export function closeTags(res: HighlightResult): HighlightResult { - const tokenStack = new Array(); - - res.value = res.value - .split('\n') - .map(line => { - const prepend = tokenStack.map(token => ``).join(''); - const matches = line.matchAll(/(|<\/span>)/g); - Array.from(matches).forEach(match => { - if (match[0] === '') tokenStack.shift(); - else tokenStack.unshift(match[2]); - }); - const append = ''.repeat(tokenStack.length); - return prepend + line + append; - }) - .join('\n'); - - return res; + appendText(value.length); + return fragment; } // Sourced from https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md and diff --git a/website/templates/pages/demo/content.handlebars b/website/templates/pages/demo/content.handlebars index b2f7a3cb..99e4f9ae 100644 --- a/website/templates/pages/demo/content.handlebars +++ b/website/templates/pages/demo/content.handlebars @@ -29,8 +29,12 @@
Load +
+

In the example diff, find scripts/hulk.js. + Toggle Multiline highlighting to see the changed const templateGlob lines switch between comment and + code colors.

@@ -45,6 +49,10 @@ Wrap lines +
\\n' +", + " ' \\n' +", + "- '\\n';", + "+ '';", + " ", + " assert.equal(expected, fileHtml);", + " });", + "@@ -422,7 +422,6 @@ describe('LineByLinePrinter', function() {", + " '
\\n' +", + " ' \\n' +", + " '\\n' +", + "- '\\n' +", + " ' \\n' +", + " ' \\n' +", + " ' \\n' +", + "diff --git a/test/side-by-side-printer-tests.js b/test/side-by-side-printer-tests.js", + "index 76625f8e..771daaa5 100644", + "--- a/test/side-by-side-printer-tests.js", + "+++ b/test/side-by-side-printer-tests.js", + "@@ -14,7 +14,7 @@ describe('SideBySidePrinter', function() {", + " ' File without changes\\n' +", + " ' \\n' +", + " ' \\n' +", + "- '\\n';", + "+ '';", + " ", + " assert.equal(expectedRight, fileHtml.right);", + " assert.equal(expectedLeft, fileHtml.left);", + "@@ -324,7 +324,6 @@ describe('SideBySidePrinter', function() {", + " ' \\n' +", + " ' \\n' +", + " '\\n' +", + "- '\\n' +", + " ' \\n' +", + " ' \\n' +", + " ' \\n' +", + "" + ] +}