Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Commit

Permalink
Updates to docsite:
Browse files Browse the repository at this point in the history
1. Enable copy button in code blocks.
2. Add "ShellSession" to lexer that extends "console" lexer.

Signed-off-by: Kevin Putnam <[email protected]>
  • Loading branch information
intelkevinputnam committed May 28, 2020
1 parent cb9b36b commit 313419b
Show file tree
Hide file tree
Showing 8 changed files with 174 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ GEN_DOCS = $(SPHINXBUILD) -M html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O
( ! [ "$$GITHUB_SHA" ] || ! [ "$$GITHUB_REPOSITORY" ] || \
find $(BUILDDIR)/html/ -name '*.html' | \
xargs sed -i -e "s;github.com/intel/pmem-csi/\\(deploy/\\S*\\);github.com/$$GITHUB_REPOSITORY/\\1?ref=$$GITHUB_SHA;g" ) && \
cp docs/html/index.html $(BUILDDIR)/html/index.html
cp docs/html/index.html $(BUILDDIR)/html/index.html && cp docs/js/copybutton.js $(BUILDDIR)/html/_static/copybutton.js
vhtml: _work/venv/.stamp
. _work/venv/bin/activate && $(GEN_DOCS)
html:
Expand Down
4 changes: 3 additions & 1 deletion conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
],
"extensions": [
"recommonmark",
"sphinx_markdown_tables"
"sphinx_markdown_tables",
"sphinx_copybutton"
],
"copybutton_prompt_text": "$ ",
"html_theme": "sphinx_rtd_theme",
"project": "PMEM-CSI",
"templates_path": [
Expand Down
14 changes: 14 additions & 0 deletions conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@
from os.path import isdir, isfile, join, basename, dirname
from os import makedirs, getenv
from shutil import copyfile
#support for modified code block
from pygments.lexers.shell import BashSessionLexer
from sphinx.highlighting import lexers

#############
#
# Add a special lexer to add a class to console lexer
#
#############

class copyAllConsole (BashSessionLexer):
name = 'ShellSession'

lexers['ShellSession'] = copyAllConsole(startinLine=True)

##############################################################################
#
Expand Down
147 changes: 147 additions & 0 deletions docs/js/copybutton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// introduces special behavior for ShellSession

// Localization support
const messages = {
'en': {
'copy': 'Copy',
'copy_to_clipboard': 'Copy to clipboard',
'copy_success': 'Copied!',
'copy_failure': 'Failed to copy',
},
'es' : {
'copy': 'Copiar',
'copy_to_clipboard': 'Copiar al portapapeles',
'copy_success': '¡Copiado!',
'copy_failure': 'Error al copiar',
},
'de' : {
'copy': 'Kopieren',
'copy_to_clipboard': 'In die Zwischenablage kopieren',
'copy_success': 'Kopiert!',
'copy_failure': 'Fehler beim Kopieren',
}
}

let locale = 'en'
if( document.documentElement.lang !== undefined
&& messages[document.documentElement.lang] !== undefined ) {
locale = document.documentElement.lang
}

/**
* Set up copy/paste for code blocks
*/

const runWhenDOMLoaded = cb => {
if (document.readyState != 'loading') {
cb()
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', cb)
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState == 'complete') cb()
})
}
}

const codeCellId = index => `codecell${index}`

// Clears selected text since ClipboardJS will select the text when copying
const clearSelection = () => {
if (window.getSelection) {
window.getSelection().removeAllRanges()
} else if (document.selection) {
document.selection.empty()
}
}

// Changes tooltip text for two seconds, then changes it back
const temporarilyChangeTooltip = (el, newText) => {
const oldText = el.getAttribute('data-tooltip')
el.setAttribute('data-tooltip', newText)
setTimeout(() => el.setAttribute('data-tooltip', oldText), 2000)
}

// Callback when a copy button is clicked. Will be passed the node that was clicked
// should then grab the text and replace pieces of text that shouldn't be used in output
var copyTargetText = (trigger) => {
var target = document.querySelector(trigger.attributes['data-clipboard-target'].value);
var textContent = target.innerText.split('\n');
var copybuttonPromptText = '$ '; // Inserted from config
var onlyCopyPromptLines = true; // Inserted from config
var removePrompts = true; // Inserted from config

grandParent = target.parentElement.parentElement;
blockType = grandParent.classList;
if (blockType[0].includes("ShellSession")) {
onlyCopyPromptLines = false;
}

// Text content line filtering based on prompts (if a prompt text is given)
if (copybuttonPromptText.length > 0) {
// If only copying prompt lines, remove all lines that don't start w/ prompt
if (onlyCopyPromptLines) {
linesWithPrompt = textContent.filter((line) => {
return line.startsWith(copybuttonPromptText) || (line.length == 0); // Keep newlines
});
// Check to make sure we have at least one non-empty line
var nonEmptyLines = linesWithPrompt.filter((line) => {return line.length > 0});
// If we detected lines w/ prompt, then overwrite textContent w/ those lines
if ((linesWithPrompt.length > 0) && (nonEmptyLines.length > 0)) {
textContent = linesWithPrompt;
}
}
// Remove the starting prompt from any remaining lines
if (removePrompts) {
textContent.forEach((line, index) => {
if (line.startsWith(copybuttonPromptText)) {
textContent[index] = line.slice(copybuttonPromptText.length);
}
});
}
}
textContent = textContent.join('\n');
// Remove a trailing newline to avoid auto-running when pasting
if (textContent.endsWith("\n")) {
textContent = textContent.slice(0, -1)
}
return textContent
}

const addCopyButtonToCodeCells = () => {
// If ClipboardJS hasn't loaded, wait a bit and try again. This
// happens because we load ClipboardJS asynchronously.
if (window.ClipboardJS === undefined) {
setTimeout(addCopyButtonToCodeCells, 250)
return
}

// Add copybuttons to all of our code cells
const codeCells = document.querySelectorAll('div.highlight pre')
codeCells.forEach((codeCell, index) => {
const id = codeCellId(index)
codeCell.setAttribute('id', id)
const pre_bg = getComputedStyle(codeCell).backgroundColor;

const clipboardButton = id =>
`<a class="copybtn o-tooltip--left" style="background-color: ${pre_bg}" data-tooltip="${messages[locale]['copy']}" data-clipboard-target="#${id}">
<img src="${DOCUMENTATION_OPTIONS.URL_ROOT}_static/copy-button.svg" alt="${messages[locale]['copy_to_clipboard']}">
</a>`
codeCell.insertAdjacentHTML('afterend', clipboardButton(id))
})

// Initialize with a callback so we can modify the text before copy
const clipboard = new ClipboardJS('.copybtn', {text: copyTargetText})

// Update UI with error/success messages
clipboard.on('success', event => {
clearSelection()
temporarilyChangeTooltip(event.trigger, messages[locale]['copy_success'])
})

clipboard.on('error', event => {
temporarilyChangeTooltip(event.trigger, messages[locale]['copy_failure'])
})
}

runWhenDOMLoaded(addCopyButtonToCodeCells)
3 changes: 2 additions & 1 deletion docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
sphinx
sphinx_rtd_theme
recommonmark
sphinx-markdown-tables
sphinx-markdown-tables
sphinx-copybutton
8 changes: 4 additions & 4 deletions examples/gce.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ and check out the source code with `repo sync`.

Before proceeding, apply the following patch:

```sh
cd src/overlays
patch -p1 <<EOF
```ShellSession
$ cd src/overlays
$ patch -p1 <<EOF
commit 148e1095ba56fcf626d184fd2c427bd192e53a28
Author: Patrick Ohly <[email protected]>
Date: Fri Aug 2 10:46:30 2019 +0200
Expand Down Expand Up @@ -269,7 +269,7 @@ kubectl create -f https://raw.githubusercontent.com/intel/pmem-csi/v0.5.0/deploy
It is expected that `my-csi-app-2` will never start because the COS
kernel lacks support for xfs. But `my-csi-app-1` comes up:

```sh
```console
$ kubectl get pv
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
pvc-0c2ebc68-cd77-4c08-9fbb-f8a5d33440b9 4Gi RWO Delete Bound default/pmem-csi-pvc-ext4 pmem-csi-sc-ext4 2m52s
Expand Down
4 changes: 2 additions & 2 deletions make.bat
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ goto end

:html
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
python.exe .\fix-refs.py
copy index.html %BUILDDIR%\html\index.html
copy docs\html\index.html %BUILDDIR%\html\index.html
copy docs\js\copybutton.js %BUILDDIR%\html\_static\copybutton.js
goto end

:help
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ platform = mylinux: linux
mywindows: win32
whitelist_externals = make.bat
/usr/bin/make
deps = -rrequirements.txt
deps = -rdocs/requirements.txt
commands =
mylinux: make {posargs}
mywindows: make.bat {posargs}
Expand Down

0 comments on commit 313419b

Please sign in to comment.