Skip to content

Instantly share code, notes, and snippets.

@lephuongbg
Last active February 14, 2023 02:15
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save lephuongbg/bf26e0aa24b3c9b0071b7597522ded15 to your computer and use it in GitHub Desktop.
Save lephuongbg/bf26e0aa24b3c9b0071b7597522ded15 to your computer and use it in GitHub Desktop.
Bitbucket Highlighter User Script

Bitbucket Highlighter UserScript

A small UserScript as a stop-gap solution for highlighting Bitbucket Pull Request's code until Bitbucket Cloud implements them natively.

Table of Contents

Install

Maintainers

@lephuongbg

Contributing

Feel free to suggest improvement, as long as it is not too complicated since this script is intended to be small, easy to understand and just a stop-gap solution until the actual implementation made by Bitbucket team. See BCLOUD-8673

License

MIT © Le Phuong

// ==UserScript==
// @name Bitbucket Highlighter
// @namespace https://github.com/lephuongbg
// @version 0.11
// @description Stop-gap solution for highlighting bitbucket pull request
// @author You
// @match https://bitbucket.org/*
// @grant GM_addStyle
// @grant GM_getResourceText
// @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.3.2/highlight.min.js
// @resource style https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.3.2/styles/default.min.css
// ==/UserScript==
(function () {
'use strict'
// Support terraform
hljs.registerLanguage('terraform', hljsDefineTerraform);
const style = GM_getResourceText('style')
GM_addStyle(style)
GM_addStyle(`.hljs {display: inline-block; overflow-x: initial; padding: 0; background: none} pre.hljs.source {display: block;}`)
// An observer callback to act on DOM changes
// So that we can automatically detect when the spans for diff view are added
const callback = function (mutationsList, observer) {
// Ignore all pages that were not pull requests page
// We had to @match all pages instead of only pull requests or branch page because Bitbucket is now a SPA app
if (window.location.pathname.match(/\/[^/]+\/[^/]+\/pull-requests\/\d+/)) {
highlightPullRequestPage(mutationsList)
} else if (window.location.pathname.match(/\/[^/]+\/[^/]+\/branch\//)) {
highlightBranchPage(mutationsList)
}
}
const observer = new MutationObserver(callback)
const config = { childList: true, subtree: true }
const toObserveNode = document.getElementById('compare-tabs') // branch page
|| document.getElementById('root') // PR page
if (!toObserveNode) return
observer.observe(toObserveNode, config)
// Flag that marks that we are highlighting current page
let highlighting = false
function highlightPullRequestPage(mutationsList) {
// Bail early if highlighting is already scheduled
if (highlighting) return
// Check if there is an observed diff article DOM node which has been reused in "load files: individually" mode
let article = mutationsList.find(mutation => mutation.type === 'attributes')?.target
// Also check if there is any non-highlighted article
if (!article) {
article = document.querySelector('article:not([highlighted-for])')
// this node may be reused so we need to detect that
article && observer.observe(article, { attributes: true, attributeFilter: ["aria-label"] })
}
// If user clicks on show more button on top/bottom of an article, the highlight in the article will be reset
if (!article) {
// Detect if show more button was clicked
let showMore = mutationsList.find(mutation => mutation.target.classList.contains('show-more-lines-wrapper'))?.target
// Then find its article
article = showMore?.closest('article')
}
// If there is no article to highlight then bail
if (!article) {
return
}
// Start scheduling highlighting process
highlighting = true
requestIdleCallback(() => {
highlightArticle(article)
// Mark that current iteration finishes
highlighting = false
// Trigger highlightPullRequestPage again to process any article left
requestIdleCallback(() => highlightPullRequestPage([]))
})
}
function highlightArticle(article) {
// Try to get the extension of the file
const ext = article.getAttribute('aria-label').match(/\.(\w+)$/)?.[1]
if (!ext) {
return
} else if (ext === 'vue') {
// allowing hljs to guess the language inside .vue
article.querySelectorAll('[data-qa=code-line] pre > span:last-child').forEach((node) => {
hljs.highlightBlock(node)
})
} else if (!hljs.getLanguage(ext)) {
// quit if this is not a language supported by hljs
return
} else {
// Create a holder to hold all codes from the same file
let code = document.createElement('code')
// set the language so hljs do not have to guess
code.classList.add('language-' + ext)
// Get all lines from the same file and put it into the holder
const nodes = article.querySelectorAll('[data-qa=code-line] pre > span:last-child')
code.textContent = Array.from(nodes).map(node => node.innerText).join('\n')
// Then highlight the holder
hljs.highlightBlock(code)
// After that, split the holder to get the highlighted figments then inject them back
const highlightedNodes = code.innerHTML.split('\n')
nodes.forEach((_node, idx) => {
_node.classList.add('language-' + ext)
_node.classList.add('hljs')
_node.innerHTML = highlightedNodes[idx]
})
}
article.setAttribute('highlighted-for', article.getAttribute('aria-label'))
}
function highlightBranchPage(mutationsList) {
let sourceCodeNode = null
// Find the source code in newly added nodes
for (const mutation of mutationsList) {
for (const addedNode of mutation.addedNodes) {
if (!addedNode.querySelector?.('pre.source')) continue
sourceCodeNode = addedNode
break
}
if (sourceCodeNode) break
}
if (!sourceCodeNode) return
for (const section of sourceCodeNode.querySelectorAll('section.bb-udiff')) {
requestIdleCallback(() => {
const ext = section.getAttribute('data-path').match(/\.(\w+)$/)?.[1]
if (!ext) {
return
}
if (ext === 'vue') {
section.querySelectorAll('pre.source').forEach((node) => hljs.highlightBlock(node))
return
}
if (!hljs.getLanguage(ext)) {
// quit if this is not a language supported by hljs
return
}
// Create a holder to hold all codes from the same file
let code = document.createElement('code')
// set the language so hljs do not have to guess
code.classList.add('language-' + ext)
// Get all lines from the same file and put it into the holder
const nodes = section.querySelectorAll('pre.source')
code.textContent = Array.from(nodes).map(node => node.innerText).join('\n')
// Then highlight the holder
hljs.highlightBlock(code)
// After that, split the holder to get the highlighted figments then inject them back
const highlightedNodes = code.innerHTML.split('\n')
nodes.forEach((_node, idx) => {
_node.classList.add('language-' + ext)
_node.classList.add('hljs')
_node.innerHTML = highlightedNodes[idx]
})
})
}
}
// highlightjs/highlightjs-terraform@73b76da/terraform.js
function hljsDefineTerraform(hljs) {
var NUMBERS = {
className: 'number',
begin: '\\b\\d+(\\.\\d+)?',
relevance: 0
};
var STRINGS = {
className: 'string',
begin: '"',
end: '"',
contains: [{
className: 'variable',
begin: '\\${',
end: '\\}',
relevance: 9,
contains: [{
className: 'string',
begin: '"',
end: '"'
}, {
className: 'meta',
begin: '[A-Za-z_0-9]*' + '\\(',
end: '\\)',
contains: [
NUMBERS, {
className: 'string',
begin: '"',
end: '"',
contains: [{
className: 'variable',
begin: '\\${',
end: '\\}',
contains: [{
className: 'string',
begin: '"',
end: '"',
contains: [{
className: 'variable',
begin: '\\${',
end: '\\}'
}]
}, {
className: 'meta',
begin: '[A-Za-z_0-9]*' + '\\(',
end: '\\)'
}]
}]
},
'self']
}]
}]
};
return {
aliases: ['tf', 'hcl'],
keywords: 'resource variable provider output locals module data terraform|10',
literal: 'false true null',
contains: [
hljs.COMMENT('\\#', '$'),
NUMBERS,
STRINGS
]
}
}
})()
MIT License
Copyright (c) 2020 Le Phuong
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@r4tz52
Copy link

r4tz52 commented Apr 2, 2020

Thanks for your script!
I just have a little remark: the regular expression should be //[\w-]+/[\w-]+/pull-requests/\d+/ because owner and/or repository name may include "-".

@lephuongbg
Copy link
Author

@r4tz52, thanks. Just updated the script to better match URL now.

@dcu
Copy link

dcu commented Jun 9, 2020

hi, can you add support for terraform: https://github.com/highlightjs/highlightjs-terraform please

@lephuongbg
Copy link
Author

@dcu Finally found time to update the script. Please enjoy.

@dcu
Copy link

dcu commented Jul 26, 2020

awesome thanks

@RobertChrist
Copy link

Hi @lephuongbg!

I used your script as the initial basis to implement syntax highlighting in the browser extension Bitbucket Refined. I just opened the PR (See also: current development branch in my repo) and thought you, or anyone else who stumbles across this page might be interested in taking a look, because I made a few changes to your code in my implementation.

1 - The script as it is currently written overwrites word-level comparison highlighting in bitbucket PRs, so it can be hard to see what exact characters changed in a line. I corrected that.
2 - I updated the mutation observer to listen to a smaller portion of the page, to hopefully improve perf a little bit
3 - I added theme support for all Prism.js themes (Bitbucket Refined uses prism, not HLJS, *shrug)
4 - I removed terraform support

Thank you!!!

@lephuongbg
Copy link
Author

I'm glad that this could be merged into Bitbucket Refined. I do use the extension too.

@RobertChrist
Copy link

: )

@lephuongbg
Copy link
Author

@RobertChrist Congrats on your PR, as I noticed that it has been merged recently.

Just want to inform you that I've updated my script to make it work properly on new "Load files: individually" mode (which is a godsend for large PR), since you might also want to port the change to Bitbucket Refined.

The gist is that, in "Load files: individually" mode, the article node can be reused completely without triggering childList type mutation. Fortunately when an article node is reused to show new file, the aria-label will change. We just need to observe article nodes' attributes change then re-highlight them.

@RobertChrist
Copy link

Hey @lephuongbg! I appreciate the update, thank you : D

I opened an issue for ReyReynold, the refined-bitbucket plugin maintainer here: refined-bitbucket/refined-bitbucket#404 .

I'm sure Rey would accept any PR you or I opened, but we'll see what happens next! : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment