Add specs for syntax_highlight JS
Also makes it work when given a parent element containing a `.js-syntax-highlight` element so for dynamically-added things like notes or Markdown previews, we can more accurately target just the element we care about.
This commit is contained in:
parent
7cbf5e4d18
commit
404a01ab14
2 changed files with 51 additions and 1 deletions
|
@ -1,3 +1,5 @@
|
|||
# Syntax Highlighter
|
||||
#
|
||||
# Applies a syntax highlighting color scheme CSS class to any element with the
|
||||
# `js-syntax-highlight` class
|
||||
#
|
||||
|
@ -6,7 +8,13 @@
|
|||
# <div class="js-syntax-highlight"></div>
|
||||
#
|
||||
$.fn.syntaxHighlight = ->
|
||||
$(this).addClass(gon.user_color_scheme)
|
||||
if $(this).hasClass('js-syntax-highlight')
|
||||
# Given the element itself, apply highlighting
|
||||
$(this).addClass(gon.user_color_scheme)
|
||||
else
|
||||
# Given a parent element, recurse to any of its applicable children
|
||||
$children = $(this).find('.js-syntax-highlight')
|
||||
$children.syntaxHighlight() if $children.length
|
||||
|
||||
$(document).on 'ready page:load', ->
|
||||
$('.js-syntax-highlight').syntaxHighlight()
|
||||
|
|
42
spec/javascripts/syntax_highlight_spec.js.coffee
Normal file
42
spec/javascripts/syntax_highlight_spec.js.coffee
Normal file
|
@ -0,0 +1,42 @@
|
|||
#= require syntax_highlight
|
||||
|
||||
describe 'Syntax Highlighter', ->
|
||||
stubUserColorScheme = (value) ->
|
||||
window.gon ?= {}
|
||||
window.gon.user_color_scheme = value
|
||||
|
||||
describe 'on a js-syntax-highlight element', ->
|
||||
beforeEach ->
|
||||
fixture.set('<div class="js-syntax-highlight"></div>')
|
||||
|
||||
it 'applies syntax highlighting', ->
|
||||
stubUserColorScheme('monokai')
|
||||
|
||||
$('.js-syntax-highlight').syntaxHighlight()
|
||||
|
||||
expect($('.js-syntax-highlight')).toHaveClass('monokai')
|
||||
|
||||
describe 'on a parent element', ->
|
||||
beforeEach ->
|
||||
fixture.set """
|
||||
<div class="parent">
|
||||
<div class="js-syntax-highlight"></div>
|
||||
<div class="foo"></div>
|
||||
<div class="js-syntax-highlight"></div>
|
||||
</div>
|
||||
"""
|
||||
|
||||
it 'applies highlighting to all applicable children', ->
|
||||
stubUserColorScheme('monokai')
|
||||
|
||||
$('.parent').syntaxHighlight()
|
||||
|
||||
expect($('.parent, .foo')).not.toHaveClass('monokai')
|
||||
expect($('.monokai').length).toBe(2)
|
||||
|
||||
it 'prevents an infinite loop when no matches exist', ->
|
||||
fixture.set('<div></div>')
|
||||
|
||||
highlight = -> $('div').syntaxHighlight()
|
||||
|
||||
expect(highlight).not.toThrow()
|
Loading…
Reference in a new issue