Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(getSegments): custom highlighter #57

Merged
merged 6 commits into from
Aug 8, 2022
Merged
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
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,41 @@ The following options may be passed to the `highlight` function.
}
```

**Get segments for custom highlighter**
```js
const { getSegments } = require('sql-highlight')

const sqlString = "SELECT `id`, `username` FROM `users` WHERE `email` = 'test@example.com'"

const segments = getSegments(sqlString)

console.log(segments)
```

**Output:**
```js
[
{ name: 'keyword', content: 'SELECT' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`id`' },
{ name: 'special', content: ',' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`username`' },
{ name: 'default', content: ' ' },
{ name: 'keyword', content: 'FROM' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`users`' },
{ name: 'default', content: ' ' },
{ name: 'keyword', content: 'WHERE' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`email`' },
{ name: 'default', content: ' ' },
{ name: 'special', content: '=' },
{ name: 'default', content: ' ' },
{ name: 'string', content: "'test@example.com'" }
]
```

## Contributing

See the [contribution guidelines](CONTRIBUTING.md).
Expand Down
48 changes: 47 additions & 1 deletion index.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { highlight } = require('./lib')
const { highlight, getSegments } = require('./lib')

const OPTIONS = {
colors: {
Expand Down Expand Up @@ -182,3 +182,49 @@ describe('html', () => {
.toBe('<span class="sql-hl-keyword">SELECT</span> id <span class="sql-hl-keyword">FROM</span> users')
})
})

describe('getSegments', () => {
it('complex query', () => {
expect(getSegments("SELECT COUNT(id), `id`, `username` FROM `users` WHERE `email` = 'test@example.com' AND `foo` = 'BAR' OR 1=1"))
.toStrictEqual([
{ name: 'keyword', content: 'SELECT' },
{ name: 'default', content: ' ' },
{ name: 'function', content: 'COUNT' },
{ name: 'bracket', content: '(' },
{ name: 'default', content: 'id' },
{ name: 'bracket', content: ')' },
{ name: 'special', content: ',' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`id`' },
{ name: 'special', content: ',' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`username`' },
{ name: 'default', content: ' ' },
{ name: 'keyword', content: 'FROM' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`users`' },
{ name: 'default', content: ' ' },
{ name: 'keyword', content: 'WHERE' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`email`' },
{ name: 'default', content: ' ' },
{ name: 'special', content: '=' },
{ name: 'default', content: ' ' },
{ name: 'string', content: "'test@example.com'" },
{ name: 'default', content: ' ' },
{ name: 'keyword', content: 'AND' },
{ name: 'default', content: ' ' },
{ name: 'string', content: '`foo`' },
{ name: 'default', content: ' ' },
{ name: 'special', content: '=' },
{ name: 'default', content: ' ' },
{ name: 'string', content: "'BAR'" },
{ name: 'default', content: ' ' },
{ name: 'keyword', content: 'OR' },
{ name: 'default', content: ' ' },
{ name: 'number', content: '1' },
{ name: 'special', content: '=' },
{ name: 'number', content: '1' }
])
})
})
6 changes: 6 additions & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ declare module 'sql-highlight' {
clear: string;
};
}

export interface Segment {
name: string;
content: string;
}

export function getSegments(sqlString: string): Array<Segment>;
export function highlight(sqlString: string, options?: HighlightOptions): string;
}
81 changes: 50 additions & 31 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ const DEFAULT_OPTIONS = {

const SPLIT_CHARS = '[^a-zA-Z_]'

const DEFAULT_KEYWORD = 'default'
scriptcoded marked this conversation as resolved.
Show resolved Hide resolved

const highlighters = [
{
name: 'keyword',
Expand Down Expand Up @@ -47,9 +49,7 @@ const highlighters = [
}
]

function highlight (sqlString, options) {
options = Object.assign({}, DEFAULT_OPTIONS, options)

function getSegments (sqlString) {
const matches = []

for (const hl of highlighters) {
Expand All @@ -70,53 +70,72 @@ function highlight (sqlString, options) {
}
}

const trimmedText = hl.trimEnd
? text.substring(0, text.length - hl.trimEnd)
: text
matches.push({
name: hl.name,
start: match.index + boringLength,
length: (hl.trimEnd ? text.substr(0, text.length - hl.trimEnd) : text).length
length: trimmedText.length
})
}
}

const sortedMatches = matches.slice().sort((a, b) => a.start - b.start)

// filter/exclude nested matches (matches within the last match)
const filteredMatches = []
const segments = []
let upperBound = 0
for (let i = 0; i < sortedMatches.length; i++) {
if (sortedMatches[i].start >= upperBound) {
filteredMatches.push(sortedMatches[i])
upperBound = sortedMatches[i].start + sortedMatches[i].length
}
}

let highlighted = ''
if (sortedMatches[i].start < upperBound) { break }

for (let i = 0; i < filteredMatches.length; i++) {
const match = filteredMatches[i]
const nextMatch = filteredMatches[i + 1]
// If no match, add a default segment
if (sortedMatches[i].start > upperBound) {
segments.push({
name: DEFAULT_KEYWORD,
content: sqlString.substring(upperBound, sortedMatches[i].start)
})
}

const stringMatch = sqlString.substr(match.start, match.length)
segments.push({
name: sortedMatches[i].name,
content: sqlString.substring(
sortedMatches[i].start,
sortedMatches[i].start + sortedMatches[i].length
)
})
upperBound = sortedMatches[i].start + sortedMatches[i].length
}

if (options.html) {
highlighted += `<span class="${options.classPrefix}${match.name}">`
highlighted += stringMatch
highlighted += '</span>'
} else {
highlighted += options.colors[match.name]
highlighted += stringMatch
highlighted += options.colors.clear
}
if (nextMatch) {
highlighted += sqlString.substr(match.start + match.length, nextMatch.start - (match.start + match.length))
} else if (sqlString.length > (match.start + match.length)) {
highlighted += sqlString.substr(match.start + match.length)
}
if (upperBound < sqlString.length - 1) {
segments.push({
name: DEFAULT_KEYWORD,
content: sqlString.substring(
upperBound,
upperBound + sqlString.length + 1
)
})
}
return segments
}

return highlighted
function highlight (sqlString, options) {
options = Object.assign({}, DEFAULT_OPTIONS, options)

return getSegments(sqlString)
.map(({ name, content }) => {
if (name === DEFAULT_KEYWORD) {
return content
}
scriptcoded marked this conversation as resolved.
Show resolved Hide resolved
if (options.html) {
return `<span class="${options.classPrefix}${name}">${content}</span>`
}
return options.colors[name] + content + options.colors.clear
})
.join('')
}

module.exports = {
getSegments,
highlight
}