1
+ // ``function*`` denotes a generator in JavaScript, see
2
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
3
+ function * getHideableCopyButtonElements ( rootElement ) {
4
+ // yield all elements with the "go" (Generic.Output),
5
+ // "gp" (Generic.Prompt), or "gt" (Generic.Traceback) CSS class
6
+ for ( const el of rootElement . querySelectorAll ( '.go, .gp, .gt' ) ) {
7
+ yield el
8
+ }
9
+ // tracebacks (.gt) contain bare text elements that need to be
10
+ // wrapped in a span to hide or show the element
11
+ for ( let el of rootElement . querySelectorAll ( '.gt' ) ) {
12
+ while ( ( el = el . nextSibling ) && el . nodeType !== Node . DOCUMENT_NODE ) {
13
+ // stop wrapping text nodes when we hit the next output or
14
+ // prompt element
15
+ if ( el . nodeType === Node . ELEMENT_NODE && el . matches ( ".gp, .go" ) ) {
16
+ break
17
+ }
18
+ // if the node is a text node with content, wrap it in a
19
+ // span element so that we can control visibility
20
+ if ( el . nodeType === Node . TEXT_NODE && el . textContent . trim ( ) ) {
21
+ const wrapper = document . createElement ( "span" )
22
+ el . after ( wrapper )
23
+ wrapper . appendChild ( el )
24
+ el = wrapper
25
+ }
26
+ yield el
27
+ }
28
+ }
29
+ }
30
+
1
31
2
32
const loadCopyButton = ( ) => {
3
- /* Add a [>>>] button on the top-right corner of code samples to hide
33
+ /* Add a [>>>] button in the top-right corner of code samples to hide
4
34
* the >>> and ... prompts and the output and thus make the code
5
35
* copyable. */
6
36
const hide_text = "Hide the prompts and output"
@@ -18,24 +48,16 @@ const loadCopyButton = () => {
18
48
const codeEl = buttonEl . nextElementSibling
19
49
if ( buttonEl . dataset . hidden === "false" ) {
20
50
// hide the code output
21
- codeEl . querySelectorAll ( '.go, .gp, .gt' ) . forEach ( el => el . hidden = true )
22
- codeEl . querySelectorAll ( '.gt' ) . forEach ( el => {
23
- while ( ( el = el . nextSibling ) && el . nodeType !== Node . DOCUMENT_NODE ) {
24
- if ( el . nodeType === Node . ELEMENT_NODE && el . matches ( ".gp, .go" ) ) break ;
25
- if ( el . nodeType === Node . TEXT_NODE && el . textContent . trim ( ) ) {
26
- const wrapper = document . createElement ( 'span' ) ;
27
- el . after ( wrapper ) ;
28
- wrapper . appendChild ( el ) ;
29
- el = wrapper
30
- }
31
- el . hidden = true
32
- }
33
- } )
51
+ for ( const el of getHideableCopyButtonElements ( codeEl ) ) {
52
+ el . hidden = true
53
+ }
34
54
buttonEl . title = show_text
35
55
buttonEl . dataset . hidden = "true"
36
56
} else {
37
57
// show the code output
38
- codeEl . childNodes . forEach ( el => el . hidden = false )
58
+ for ( const el of getHideableCopyButtonElements ( codeEl ) ) {
59
+ el . hidden = false
60
+ }
39
61
buttonEl . title = hide_text
40
62
buttonEl . dataset . hidden = "false"
41
63
}
0 commit comments