From 117a7fd33621f1e04c12cab71258067c52ac2cb4 Mon Sep 17 00:00:00 2001 From: Rodrigo Fernandes Date: Mon, 30 Nov 2026 21:30:08 +0000 Subject: [PATCH 1/6] fix: preserve multiline syntax highlighting within diff hunks Signed-off-by: Rodrigo Fernandes --- README.md | 12 +- src/__tests__/multiline-highlighting-tests.ts | 94 +++++++ src/ui/js/diff2html-ui-base.ts | 145 ++++++++-- src/ui/js/highlight-hunks.ts | 181 ++++++++++++ src/ui/js/highlight.js-helpers.ts | 266 +++++++++--------- 5 files changed, 538 insertions(+), 160 deletions(-) create mode 100644 src/__tests__/multiline-highlighting-tests.ts create mode 100644 src/ui/js/highlight-hunks.ts 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..ac2e6203 --- /dev/null +++ b/src/__tests__/multiline-highlighting-tests.ts @@ -0,0 +1,94 @@ +import { 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); +}); + +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..2f2b0a24 100644 --- a/src/ui/js/diff2html-ui-base.ts +++ b/src/ui/js/diff2html-ui-base.ts @@ -1,12 +1,14 @@ -import { closeTags, nodeStream, mergeStreams, getLanguage } from './highlight.js-helpers'; +import { getLanguage, 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 +38,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 +166,74 @@ 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); + return result.language && /[\t\n\f\r ]/.test(result.language) ? null : result; + }; + const parse = (value: string, text: string): boolean => { + template.innerHTML = value; + return template.content.textContent === text; + }; + const syntaxEvents = () => { + const events = nodeStream(template.content); + return events.some(({ event, node }) => event === 'start' && !isSyntaxSpan(node)) ? null : events; + }; + const highlightSide = (lines: string[]) => { + const result = highlight(lines.join('\n')); + if (result === null) return null; + template.innerHTML = result.value; + const events = syntaxEvents(); + if (events === null) return null; + const split = splitHighlightedLines(lines, template.content.textContent!, events); + 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) return; + if (!parse(result.value, text)) return; + if (plain) { + // For a plain source line the validated output already is the final token tree. + if (!nonSyntaxMarkup.test(result.value)) ownCanonicalSpans(template.content, this.syntaxNodes); + else if (!ownSyntaxSpans(template.content, this.syntaxNodes)) return; + apply({ target, fragment: template.content, language: result.language }); + } else { + const events = syntaxEvents(); + if (events !== null) 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 +261,50 @@ export class Diff2HtmlUI { return hashTag; } +} + +// Canonical engine HTML uses only text and spans with one quoted class attribute. +const nonSyntaxMarkup = /<(?!\/span>|span class="[^"<]*">)/; - private isElement(arg?: unknown): arg is Element { - return arg !== null && (arg as Element)?.classList !== undefined; +function ownCanonicalSpans(root: ParentNode, emitted: WeakSet): void { + for (let span = root.firstElementChild; span !== null; span = span.nextElementSibling) { + emitted.add(span); + ownCanonicalSpans(span, emitted); } } + +function markHighlighted(target: Element, language?: string): void { + if (language) target.classList.add('hljs', language); + else target.classList.add('hljs'); +} + +function ownSyntaxSpans(root: Node, emitted: WeakSet): boolean { + for (let child = root.firstChild; child !== null; child = child.nextSibling) { + if (child.nodeType === 3) continue; + if (!isSyntaxSpan(child) || !ownSyntaxSpans(child, emitted)) return false; + emitted.add(child); + } + return true; +} + +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() === '' + ); +} + +function isSyntaxSpan(node: Node): boolean { + if (node.nodeType !== 1) return false; + const element = node as Element; + return ( + element.namespaceURI === 'http://www.w3.org/1999/xhtml' && + element.localName === 'span' && + element.attributes.length === 1 && + element.hasAttribute('class') + ); +} 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..90d5db73 100644 --- a/src/ui/js/highlight.js-helpers.ts +++ b/src/ui/js/highlight.js-helpers.ts @@ -3,160 +3,168 @@ * Used to highlight selected html elements using context */ -import { HighlightResult } from 'highlight.js'; +type NodeEvent = { event: 'start' | 'stop'; offset: number; node: T }; -/* Utility functions */ - -function escapeHTML(value: string): string { - return value.replace(/&/gm, '&').replace(//gm, '>'); +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 }); + } + } + } + visit(root); + return events; } -function tag(node: Node): string { - return node.nodeName.toLowerCase(); +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; } -/* Stream merging */ - -type NodeEvent = { - event: 'start' | 'stop'; - offset: number; - node: Node; -}; - -export function nodeStream(node: Node): NodeEvent[] { - const result: NodeEvent[] = []; +// Bound the lexer input and temporary token DOM, including when a few source lines are very long. +const maxHunkSideLines = 256; +const maxHunkSideLength = 32 * 1024; - 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 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; } - return offset; - }; - - nodeStream(node, 0); - - return result; -} - -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; + 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 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; - } +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; - /* - 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; + function appendText(end: number): void { + if (offset < end) parent.appendChild(target.ownerDocument.createTextNode(value.slice(offset, end))); + offset = end; } - function open(node: Node): void { - if (!isElement(node)) { - throw new Error('Node is not an Element'); - } - - result += `<${tag(node)} ${Array() - .map.call(node.attributes, attr => `${attr.nodeName}="${escapeHTML(attr.value).replace(/"/g, '"')}"`) - .join(' ')}>`; + 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 close(node: Node): void { - result += ''; + function render({ event, node }: NodeEvent, token: boolean): void { + if (event === 'start') open(node, token); + else parent = parent.parentNode!; } - function render(event: NodeEvent): void { - (event.event === 'start' ? open : close)(event.node); + 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 (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); + 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 From 8be323bf9bc0551dea7eed55eb605f782dcfa598 Mon Sep 17 00:00:00 2001 From: Rodrigo Fernandes Date: Mon, 30 Nov 2026 21:43:22 +0000 Subject: [PATCH 2/6] fix: reject malformed syntax highlighting markup Require canonical balanced token markup before the HTML parser can discard or repair invalid output. Preserve detached text validation and test accepted and rejected token streams. Signed-off-by: Rodrigo Fernandes --- src/__tests__/multiline-highlighting-tests.ts | 28 ++++++++- src/ui/js/diff2html-ui-base.ts | 63 ++++++------------- src/ui/js/highlight.js-helpers.ts | 20 ++++++ 3 files changed, 66 insertions(+), 45 deletions(-) diff --git a/src/__tests__/multiline-highlighting-tests.ts b/src/__tests__/multiline-highlighting-tests.ts index ac2e6203..c059abe3 100644 --- a/src/__tests__/multiline-highlighting-tests.ts +++ b/src/__tests__/multiline-highlighting-tests.ts @@ -1,4 +1,4 @@ -import { selectHunkLines, splitHighlightedLines } from '../ui/js/highlight.js-helpers'; +import { isHighlightMarkup, selectHunkLines, splitHighlightedLines } from '../ui/js/highlight.js-helpers'; import { shouldHighlightHunks } from '../ui/js/highlight-hunks'; it.each([ @@ -12,6 +12,32 @@ it.each([ 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; diff --git a/src/ui/js/diff2html-ui-base.ts b/src/ui/js/diff2html-ui-base.ts index 2f2b0a24..9553086a 100644 --- a/src/ui/js/diff2html-ui-base.ts +++ b/src/ui/js/diff2html-ui-base.ts @@ -1,4 +1,11 @@ -import { getLanguage, mergeStreams, nodeStream, selectHunkLines, splitHighlightedLines } 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'; @@ -174,23 +181,16 @@ export class Diff2HtmlUI { const options = { language: hljsLanguage, ignoreIllegals: true }; const highlight = (text: string) => { const result = hljs.highlight(text, options); - return result.language && /[\t\n\f\r ]/.test(result.language) ? null : result; - }; - const parse = (value: string, text: string): boolean => { + 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 template.content.textContent === text; - }; - const syntaxEvents = () => { - const events = nodeStream(template.content); - return events.some(({ event, node }) => event === 'start' && !isSyntaxSpan(node)) ? null : events; + return result; }; const highlightSide = (lines: string[]) => { const result = highlight(lines.join('\n')); if (result === null) return null; - template.innerHTML = result.value; - const events = syntaxEvents(); - if (events === null) return null; - const split = splitHighlightedLines(lines, template.content.textContent!, events); + 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]) => { @@ -211,16 +211,14 @@ export class Diff2HtmlUI { const text = plain ? first.nodeValue! : target.textContent!; if (text.startsWith(' ') && isEofMarker(target)) return; const result = highlight(text); - if (result === null) return; - if (!parse(result.value, text)) return; + if (result === null || template.content.textContent !== text) return; if (plain) { // For a plain source line the validated output already is the final token tree. - if (!nonSyntaxMarkup.test(result.value)) ownCanonicalSpans(template.content, this.syntaxNodes); - else if (!ownSyntaxSpans(template.content, this.syntaxNodes)) return; + ownSyntaxSpans(template.content, this.syntaxNodes); apply({ target, fragment: template.content, language: result.language }); } else { - const events = syntaxEvents(); - if (events !== null) apply(prepare(target, { events, text, language: result.language })); + const events = nodeStream(template.content); + apply(prepare(target, { events, text, language: result.language })); } }; @@ -263,13 +261,10 @@ export class Diff2HtmlUI { } } -// Canonical engine HTML uses only text and spans with one quoted class attribute. -const nonSyntaxMarkup = /<(?!\/span>|span class="[^"<]*">)/; - -function ownCanonicalSpans(root: ParentNode, emitted: WeakSet): void { +function ownSyntaxSpans(root: ParentNode, emitted: WeakSet): void { for (let span = root.firstElementChild; span !== null; span = span.nextElementSibling) { emitted.add(span); - ownCanonicalSpans(span, emitted); + ownSyntaxSpans(span, emitted); } } @@ -278,15 +273,6 @@ function markHighlighted(target: Element, language?: string): void { else target.classList.add('hljs'); } -function ownSyntaxSpans(root: Node, emitted: WeakSet): boolean { - for (let child = root.firstChild; child !== null; child = child.nextSibling) { - if (child.nodeType === 3) continue; - if (!isSyntaxSpan(child) || !ownSyntaxSpans(child, emitted)) return false; - emitted.add(child); - } - return true; -} - function isEofMarker(target: Element): boolean { const prefix = target.previousElementSibling; const cell = target.parentElement?.parentElement; @@ -297,14 +283,3 @@ function isEofMarker(target: Element): boolean { cell.previousElementSibling?.textContent?.trim() === '' ); } - -function isSyntaxSpan(node: Node): boolean { - if (node.nodeType !== 1) return false; - const element = node as Element; - return ( - element.namespaceURI === 'http://www.w3.org/1999/xhtml' && - element.localName === 'span' && - element.attributes.length === 1 && - element.hasAttribute('class') - ); -} diff --git a/src/ui/js/highlight.js-helpers.ts b/src/ui/js/highlight.js-helpers.ts index 90d5db73..3f9a6906 100644 --- a/src/ui/js/highlight.js-helpers.ts +++ b/src/ui/js/highlight.js-helpers.ts @@ -3,6 +3,26 @@ * Used to highlight selected html elements using context */ +const spanStart = '' || (next !== -1 && next < quote)) return false; + depth++; + } + tag = next; + } + return depth === 0; +} + type NodeEvent = { event: 'start' | 'stop'; offset: number; node: T }; export function nodeStream(root: Node, emitted?: WeakSet): NodeEvent[] { From 85a83abdd775039843e7cabc528b482925a6c252 Mon Sep 17 00:00:00 2001 From: Rodrigo Fernandes Date: Mon, 30 Nov 2026 22:00:39 +0000 Subject: [PATCH 3/6] feat(demo): showcase multiline syntax highlighting Add a shareable built-in example and a default-on checkbox to compare hunk-aware syntax highlighting with per-line highlighting. Signed-off-by: Rodrigo Fernandes --- .../templates/pages/demo/content.handlebars | 7 +++ website/templates/pages/demo/demo.ts | 54 +++++++++++++++---- 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/website/templates/pages/demo/content.handlebars b/website/templates/pages/demo/content.handlebars index b2f7a3cb..c9e5f0f2 100644 --- a/website/templates/pages/demo/content.handlebars +++ b/website/templates/pages/demo/content.handlebars @@ -29,8 +29,11 @@
Load +
+

In the multiline example, toggle Multiline highlighting and watch how const + inside the block comment is colored.

@@ -45,6 +48,10 @@ Wrap lines +
-

In the multiline example, toggle Multiline highlighting and watch how const - inside the block comment is colored.

+

The demo opens with a hulk.js example. + Toggle Multiline highlighting to see the changed const templates lines switch between comment and + code colors.

@@ -133,7 +134,7 @@

Just copy the url from the page, which should contain all the customizations and reference for the diff you introduced.

Open an example diff + href="demo.html?matching=none&matchWordsThreshold=0.25&maxLineLengthHighlight=10000&diffStyle=word&renderNothingWhenEmpty=0&matchingMaxComparisons=2500&maxLineSizeInBlockForComparison=200&outputFormat=line-by-line&drawFileList=1&synchronisedScroll=1&highlight=1&fileListToggle=1&fileListStartVisible=0&diff=https://github.com/rtfpessoa/diff2html/pull/106">Open a GitHub pull request diff

  • diff --git a/website/templates/pages/demo/demo.ts b/website/templates/pages/demo/demo.ts index c81aecaf..a68f6d7d 100644 --- a/website/templates/pages/demo/demo.ts +++ b/website/templates/pages/demo/demo.ts @@ -30,16 +30,16 @@ type URLParams = { const searchParam = 'diff'; const multilineExampleInput = 'example:multiline-highlighting'; const multilineExampleDiff = [ - 'diff --git a/settings.js b/settings.js', - '--- a/settings.js', - '+++ b/settings.js', + 'diff --git a/hulk.js b/hulk.js', + '--- a/hulk.js', + '+++ b/hulk.js', '@@ -1,5 +1,5 @@', ' /*', - '-const requestTimeout = 1000;', - '+const requestTimeout = 2000;', + "-const templates = extractFiles('*.mustache');", + "+const templates = extractFiles('*.hbs');", ' */', ' ', - ' const active = true;', + " const encoding = 'utf8';", '', ].join('\n'); @@ -316,7 +316,7 @@ document.addEventListener('DOMContentLoaded', async () => { rawDiff === `${searchParam}=${multilineExampleInput}` || urlParams.diff === multilineExampleInput ? rawDiff?.slice(searchParam.length + 1) : urlParams.diff; - elements.url.input.value = savedDiff || 'https://github.com/rtfpessoa/diff2html/pull/106'; + elements.url.input.value = savedDiff || multilineExampleInput; let config = getConfiguration(urlParams); // Update HTML inputs from any changes in URL From f9ec777c1ca347f19158fb3287e0a35da55abf20 Mon Sep 17 00:00:00 2001 From: Rodrigo Fernandes Date: Mon, 30 Nov 2026 23:02:52 +0000 Subject: [PATCH 6/6] fix(demo): keep the full diff in the multiline example Bundle the historical 12-file example and adapt only its scripts/hulk.js patch to show comment highlighting. Leave the original GitHub example unchanged. Signed-off-by: Rodrigo Fernandes --- .../templates/pages/demo/content.handlebars | 4 +- website/templates/pages/demo/demo.ts | 15 +- .../templates/pages/demo/example-diff.json | 371 ++++++++++++++++++ 3 files changed, 375 insertions(+), 15 deletions(-) create mode 100644 website/templates/pages/demo/example-diff.json diff --git a/website/templates/pages/demo/content.handlebars b/website/templates/pages/demo/content.handlebars index f5809e84..99e4f9ae 100644 --- a/website/templates/pages/demo/content.handlebars +++ b/website/templates/pages/demo/content.handlebars @@ -32,8 +32,8 @@
  • -

    The demo opens with a hulk.js example. - Toggle Multiline highlighting to see the changed const templates lines switch between comment and +

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

    diff --git a/website/templates/pages/demo/demo.ts b/website/templates/pages/demo/demo.ts index a68f6d7d..e3b6bd4e 100644 --- a/website/templates/pages/demo/demo.ts +++ b/website/templates/pages/demo/demo.ts @@ -5,6 +5,7 @@ import '../../../main.css'; import './github-highlights.css'; import '../../../../src/ui/css/diff2html.css'; import './demo.css'; +import exampleDiff from './example-diff.json'; import { colorSchemeToCss } from '../../../../src/render-utils'; import { ColorSchemeType } from '../../../../src/types'; @@ -29,19 +30,7 @@ type URLParams = { const searchParam = 'diff'; const multilineExampleInput = 'example:multiline-highlighting'; -const multilineExampleDiff = [ - 'diff --git a/hulk.js b/hulk.js', - '--- a/hulk.js', - '+++ b/hulk.js', - '@@ -1,5 +1,5 @@', - ' /*', - "-const templates = extractFiles('*.mustache');", - "+const templates = extractFiles('*.hbs');", - ' */', - ' ', - " const encoding = 'utf8';", - '', -].join('\n'); +const multilineExampleDiff = exampleDiff.lines.join('\n'); // Preserve the full last field, including any extra '=' or '?' in its value. function getLastRawParameter(name: string): string | undefined { diff --git a/website/templates/pages/demo/example-diff.json b/website/templates/pages/demo/example-diff.json new file mode 100644 index 00000000..640ce16b --- /dev/null +++ b/website/templates/pages/demo/example-diff.json @@ -0,0 +1,371 @@ +{ + "source": "https://github.com/rtfpessoa/diff2html/pull/106", + "note": "Only scripts/hulk.js is adapted to demonstrate multiline syntax highlighting.", + "lines": [ + "diff --git a/README.md b/README.md", + "index 132c8a28..46909f25 100644", + "--- a/README.md", + "+++ b/README.md", + "@@ -98,6 +98,9 @@ The HTML output accepts a Javascript object with configuration. Possible options", + " - `synchronisedScroll`: scroll both panes in side-by-side mode: `true` or `false`, default is `false`", + " - `matchWordsThreshold`: similarity threshold for word matching, default is 0.25", + " - `matchingMaxComparisons`: perform at most this much comparisons for line matching a block of changes, default is `2500`", + "+ - `templates`: object with previously compiled templates to replace parts of the html", + "+ - `rawTemplates`: object with raw not compiled templates to replace parts of the html", + "+ > For more information regarding the possible templates look into [src/templates](https://github.com/rtfpessoa/diff2html/tree/master/src/templates)", + " ", + " ## Diff2HtmlUI Helper", + " ", + "diff --git a/scripts/hulk.js b/scripts/hulk.js", + "index 779b073f..ad23dd91 100755", + "--- a/scripts/hulk.js", + "+++ b/scripts/hulk.js", + "@@ -171,16 +171,16 @@ function namespace(name) {", + " }", + " ", + " /* Example: choose which templates to load.", + "-const templateGlob = '*.mustache';", + "+const templateGlob = '*.hbs';", + " */", + " // write a template foreach file that matches template extension", + " templates = extractFiles(options.argv.remain)", + " .map(function(file) {", + "- var openedFile = fs.readFileSync(file, 'utf-8');", + "+ var openedFile = fs.readFileSync(file, 'utf-8').trim();", + " var name;", + " if (!openedFile) return;", + " name = namespace(path.basename(file).replace(/\\..*$/, ''));", + "- openedFile = removeByteOrderMark(openedFile.trim());", + "+ openedFile = removeByteOrderMark(openedFile);", + " openedFile = wrap(file, name, openedFile);", + " if (!options.outputdir) return openedFile;", + " fs.writeFileSync(path.join(options.outputdir, name + '.js')", + "diff --git a/src/diff2html.js b/src/diff2html.js", + "index 21b0119e..64e138f5 100644", + "--- a/src/diff2html.js", + "+++ b/src/diff2html.js", + "@@ -7,7 +7,6 @@", + " ", + " (function() {", + " var diffParser = require('./diff-parser.js').DiffParser;", + "- var fileLister = require('./file-list-printer.js').FileListPrinter;", + " var htmlPrinter = require('./html-printer.js').HtmlPrinter;", + " ", + " function Diff2Html() {", + "@@ -43,7 +42,7 @@", + " ", + " var fileList = '';", + " if (configOrEmpty.showFiles === true) {", + "- fileList = fileLister.generateFileList(diffJson, configOrEmpty);", + "+ fileList = htmlPrinter.generateFileListSummary(diffJson, configOrEmpty);", + " }", + " ", + " var diffOutput = '';", + "diff --git a/src/file-list-printer.js b/src/file-list-printer.js", + "index e408d9b2..1e0a2c61 100644", + "--- a/src/file-list-printer.js", + "+++ b/src/file-list-printer.js", + "@@ -8,11 +8,16 @@", + " (function() {", + " var printerUtils = require('./printer-utils.js').PrinterUtils;", + " ", + "- var hoganUtils = require('./hoganjs-utils.js').HoganJsUtils;", + "+ var hoganUtils;", + "+", + " var baseTemplatesPath = 'file-summary';", + " var iconsBaseTemplatesPath = 'icon';", + " ", + "- function FileListPrinter() {", + "+ function FileListPrinter(config) {", + "+ this.config = config;", + "+", + "+ var HoganJsUtils = require('./hoganjs-utils.js').HoganJsUtils;", + "+ hoganUtils = new HoganJsUtils(config);", + " }", + " ", + " FileListPrinter.prototype.generateFileList = function(diffFiles) {", + "@@ -38,5 +43,5 @@", + " });", + " };", + " ", + "- module.exports.FileListPrinter = new FileListPrinter();", + "+ module.exports.FileListPrinter = FileListPrinter;", + " })();", + "diff --git a/src/hoganjs-utils.js b/src/hoganjs-utils.js", + "index 9949e5fa..b2e9c275 100644", + "--- a/src/hoganjs-utils.js", + "+++ b/src/hoganjs-utils.js", + "@@ -8,18 +8,26 @@", + " (function() {", + " var fs = require('fs');", + " var path = require('path');", + "-", + " var hogan = require('hogan.js');", + " ", + " var hoganTemplates = require('./templates/diff2html-templates.js');", + " ", + "- var templatesPath = path.resolve(__dirname, 'templates');", + "+ var extraTemplates;", + "+", + "+ function HoganJsUtils(configuration) {", + "+ this.config = configuration || {};", + "+ extraTemplates = this.config.templates || {};", + " ", + "- function HoganJsUtils() {", + "+ var rawTemplates = this.config.rawTemplates || {};", + "+ for (var templateName in rawTemplates) {", + "+ if (rawTemplates.hasOwnProperty(templateName)) {", + "+ if (!extraTemplates[templateName]) extraTemplates[templateName] = this.compile(rawTemplates[templateName]);", + "+ }", + "+ }", + " }", + " ", + "- HoganJsUtils.prototype.render = function(namespace, view, params, configuration) {", + "- var template = this.template(namespace, view, configuration);", + "+ HoganJsUtils.prototype.render = function(namespace, view, params) {", + "+ var template = this.template(namespace, view);", + " if (template) {", + " return template.render(params);", + " }", + "@@ -27,17 +35,16 @@", + " return null;", + " };", + " ", + "- HoganJsUtils.prototype.template = function(namespace, view, configuration) {", + "- var config = configuration || {};", + "+ HoganJsUtils.prototype.template = function(namespace, view) {", + " var templateKey = this._templateKey(namespace, view);", + " ", + "- return this._getTemplate(templateKey, config);", + "+ return this._getTemplate(templateKey);", + " };", + " ", + "- HoganJsUtils.prototype._getTemplate = function(templateKey, config) {", + "+ HoganJsUtils.prototype._getTemplate = function(templateKey) {", + " var template;", + " ", + "- if (!config.noCache) {", + "+ if (!this.config.noCache) {", + " template = this._readFromCache(templateKey);", + " }", + " ", + "@@ -53,6 +60,7 @@", + " ", + " try {", + " if (fs.readFileSync) {", + "+ var templatesPath = path.resolve(__dirname, 'templates');", + " var templatePath = path.join(templatesPath, templateKey);", + " var templateContent = fs.readFileSync(templatePath + '.mustache', 'utf8');", + " template = hogan.compile(templateContent);", + "@@ -66,12 +74,16 @@", + " };", + " ", + " HoganJsUtils.prototype._readFromCache = function(templateKey) {", + "- return hoganTemplates[templateKey];", + "+ return extraTemplates[templateKey] || hoganTemplates[templateKey];", + " };", + " ", + " HoganJsUtils.prototype._templateKey = function(namespace, view) {", + " return namespace + '-' + view;", + " };", + " ", + "- module.exports.HoganJsUtils = new HoganJsUtils();", + "+ HoganJsUtils.prototype.compile = function(templateStr) {", + "+ return hogan.compile(templateStr);", + "+ };", + "+", + "+ module.exports.HoganJsUtils = HoganJsUtils;", + " })();", + "diff --git a/src/html-printer.js b/src/html-printer.js", + "index 585d5b66..13f83047 100644", + "--- a/src/html-printer.js", + "+++ b/src/html-printer.js", + "@@ -8,6 +8,7 @@", + " (function() {", + " var LineByLinePrinter = require('./line-by-line-printer.js').LineByLinePrinter;", + " var SideBySidePrinter = require('./side-by-side-printer.js').SideBySidePrinter;", + "+ var FileListPrinter = require('./file-list-printer.js').FileListPrinter;", + " ", + " function HtmlPrinter() {", + " }", + "@@ -22,5 +23,10 @@", + " return sideBySidePrinter.generateSideBySideJsonHtml(diffFiles);", + " };", + " ", + "+ HtmlPrinter.prototype.generateFileListSummary = function(diffJson, config) {", + "+ var fileListPrinter = new FileListPrinter(config);", + "+ return fileListPrinter.generateFileList(diffJson);", + "+ };", + "+", + " module.exports.HtmlPrinter = new HtmlPrinter();", + " })();", + "diff --git a/src/line-by-line-printer.js b/src/line-by-line-printer.js", + "index b07eb53c..d230bedd 100644", + "--- a/src/line-by-line-printer.js", + "+++ b/src/line-by-line-printer.js", + "@@ -11,7 +11,8 @@", + " var utils = require('./utils.js').Utils;", + " var Rematch = require('./rematch.js').Rematch;", + " ", + "- var hoganUtils = require('./hoganjs-utils.js').HoganJsUtils;", + "+ var hoganUtils;", + "+", + " var genericTemplatesPath = 'generic';", + " var baseTemplatesPath = 'line-by-line';", + " var iconsBaseTemplatesPath = 'icon';", + "@@ -19,6 +20,9 @@", + " ", + " function LineByLinePrinter(config) {", + " this.config = config;", + "+", + "+ var HoganJsUtils = require('./hoganjs-utils.js').HoganJsUtils;", + "+ hoganUtils = new HoganJsUtils(config);", + " }", + " ", + " LineByLinePrinter.prototype.makeFileDiffHtml = function(file, diffs) {", + "diff --git a/src/side-by-side-printer.js b/src/side-by-side-printer.js", + "index bbf1dc8d..5e3033b3 100644", + "--- a/src/side-by-side-printer.js", + "+++ b/src/side-by-side-printer.js", + "@@ -11,7 +11,8 @@", + " var utils = require('./utils.js').Utils;", + " var Rematch = require('./rematch.js').Rematch;", + " ", + "- var hoganUtils = require('./hoganjs-utils.js').HoganJsUtils;", + "+ var hoganUtils;", + "+", + " var genericTemplatesPath = 'generic';", + " var baseTemplatesPath = 'side-by-side';", + " var iconsBaseTemplatesPath = 'icon';", + "@@ -26,6 +27,9 @@", + " ", + " function SideBySidePrinter(config) {", + " this.config = config;", + "+", + "+ var HoganJsUtils = require('./hoganjs-utils.js').HoganJsUtils;", + "+ hoganUtils = new HoganJsUtils(config);", + " }", + " ", + " SideBySidePrinter.prototype.makeDiffHtml = function(file, diffs) {", + "diff --git a/test/file-list-printer-tests.js b/test/file-list-printer-tests.js", + "index a502a46f..60ea3208 100644", + "--- a/test/file-list-printer-tests.js", + "+++ b/test/file-list-printer-tests.js", + "@@ -1,6 +1,6 @@", + " var assert = require('assert');", + " ", + "-var fileListPrinter = require('../src/file-list-printer.js').FileListPrinter;", + "+var fileListPrinter = new (require('../src/file-list-printer.js').FileListPrinter)();", + " ", + " describe('FileListPrinter', function() {", + " describe('generateFileList', function() {", + "diff --git a/test/hogan-cache-tests.js b/test/hogan-cache-tests.js", + "index 190bf6f8..a34839c0 100644", + "--- a/test/hogan-cache-tests.js", + "+++ b/test/hogan-cache-tests.js", + "@@ -1,6 +1,6 @@", + " var assert = require('assert');", + " ", + "-var HoganJsUtils = require('../src/hoganjs-utils.js').HoganJsUtils;", + "+var HoganJsUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)();", + " var diffParser = require('../src/diff-parser.js').DiffParser;", + " ", + " describe('HoganJsUtils', function() {", + "@@ -21,16 +21,50 @@ describe('HoganJsUtils', function() {", + " });", + " assert.equal(emptyDiffHtml, result);", + " });", + "+", + " it('should render view without cache', function() {", + " var result = HoganJsUtils.render('generic', 'empty-diff', {", + " contentClass: 'd2h-code-line',", + " diffParser: diffParser", + " }, {noCache: true});", + "- assert.equal(emptyDiffHtml + '\\n', result);", + "+ assert.equal(emptyDiffHtml, result);", + " });", + "+", + " it('should return null if template is missing', function() {", + "- var result = HoganJsUtils.render('generic', 'missing-template', {}, {noCache: true});", + "+ var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)({noCache: true});", + "+ var result = hoganUtils.render('generic', 'missing-template', {});", + " assert.equal(null, result);", + " });", + "+", + "+ it('should allow templates to be overridden with compiled templates', function() {", + "+ var emptyDiffTemplate = HoganJsUtils.compile('

    {{myName}}

    ');", + "+", + "+ var config = {templates: {'generic-empty-diff': emptyDiffTemplate}};", + "+ var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)(config);", + "+ var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});", + "+ assert.equal('

    Rodrigo Fernandes

    ', result);", + "+ });", + "+", + "+ it('should allow templates to be overridden with uncompiled templates', function() {", + "+ var emptyDiffTemplate = '

    {{myName}}

    ';", + "+", + "+ var config = {rawTemplates: {'generic-empty-diff': emptyDiffTemplate}};", + "+ var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)(config);", + "+ var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});", + "+ assert.equal('

    Rodrigo Fernandes

    ', result);", + "+ });", + "+", + "+ it('should allow templates to be overridden giving priority to compiled templates', function() {", + "+ var emptyDiffTemplate = HoganJsUtils.compile('

    {{myName}}

    ');", + "+ var emptyDiffTemplateUncompiled = '

    Not used!

    ';", + "+", + "+ var config = {", + "+ templates: {'generic-empty-diff': emptyDiffTemplate},", + "+ rawTemplates: {'generic-empty-diff': emptyDiffTemplateUncompiled}", + "+ };", + "+ var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)(config);", + "+ var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});", + "+ assert.equal('

    Rodrigo Fernandes

    ', result);", + "+ });", + " });", + " });", + "diff --git a/test/line-by-line-tests.js b/test/line-by-line-tests.js", + "index 1cd92073..8869b3df 100644", + "--- a/test/line-by-line-tests.js", + "+++ b/test/line-by-line-tests.js", + "@@ -14,7 +14,7 @@ describe('LineByLinePrinter', function() {", + " ' File without changes\\n' +", + " '
    \\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' +", + "" + ] +}