1
- import { html } from 'lit' ;
1
+ import { LitElement , html } from 'lit' ;
2
2
import { customElement } from 'lit/decorators/custom-element.js' ;
3
3
import { property } from 'lit/decorators/property.js' ;
4
4
import { classMap } from 'lit/directives/class-map.js' ;
5
- import { BaseCodeBlock } from './BaseCodeBlock.js' ;
6
5
import styles from './pf-code-block.css' ;
7
6
8
7
/**
@@ -28,20 +27,34 @@ import styles from './pf-code-block.css';
28
27
* @cssprop {<string>} --pf-c-code-block__pre--FontFamily {@default `"Liberation Mono", consolas, "SFMono-Regular", menlo, monaco, "Courier New", monospace`}
29
28
*/
30
29
30
+ function dedent ( str : string ) : string {
31
+ const stripped = str . replace ( / ^ \n / , '' ) ;
32
+ const match = stripped . match ( / ^ \s + / ) ;
33
+ return match ? stripped . replace ( new RegExp ( `^${ match [ 0 ] } ` , 'gm' ) , '' ) : str ;
34
+ }
35
+
31
36
@customElement ( 'pf-code-block' )
32
- export class PfCodeBlock extends BaseCodeBlock {
33
- static readonly styles = [ ... BaseCodeBlock . styles , styles ] ;
37
+ export class PfCodeBlock extends LitElement {
38
+ static readonly styles = [ styles ] ;
34
39
40
+ /** Flag for whether the code block is expanded */
35
41
@property ( { type : Boolean , reflect : true } ) expanded = false ;
36
42
37
- #toggle( ) {
38
- this . expanded = ! this . expanded ;
39
- }
40
-
41
43
get #expandedContent( ) : string {
42
44
return this . querySelector ( 'script[data-expand]' ) ?. textContent ?? '' ;
43
45
}
44
46
47
+ get #content( ) {
48
+ const script = this . querySelector < HTMLScriptElement > ( 'script[type]' ) ;
49
+ if (
50
+ script ?. type !== 'text/javascript-sample' &&
51
+ ! ! script ?. type . match ( / ( j ( a v a ) ? | e c m a | l i v e ) s c r i p t / ) ) {
52
+ return '' ;
53
+ } else {
54
+ return dedent ( script ?. textContent ?? '' ) ;
55
+ }
56
+ }
57
+
45
58
override render ( ) {
46
59
const { expanded } = this ;
47
60
return html `
@@ -51,8 +64,8 @@ export class PfCodeBlock extends BaseCodeBlock {
51
64
</ div >
52
65
</ div >
53
66
< div id ="container " class ="${ classMap ( { expanded } ) } ">
54
- < pre > < code id ="content "> ${ this . content } </ code > < code id ="code-block-expand "
55
- ?hidden ="${ ! expanded } "> ${ this . #expandedContent} </ code > </ pre >
67
+ < pre > < code id ="content "> ${ this . # content} </ code > < code id ="code-block-expand "
68
+ ?hidden ="${ ! expanded } "> ${ this . #expandedContent} </ code > </ pre >
56
69
< button ?hidden ="${ ! this . #expandedContent} "
57
70
@click =${ this . #toggle}
58
71
aria-expanded =${ this . expanded }
@@ -63,6 +76,10 @@ export class PfCodeBlock extends BaseCodeBlock {
63
76
</ div >
64
77
` ;
65
78
}
79
+
80
+ #toggle( ) {
81
+ this . expanded = ! this . expanded ;
82
+ }
66
83
}
67
84
68
85
declare global {
0 commit comments