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