Browse Source

Docs: Dedent code node content correctly. (#26115)

* dedent

* for loop

* use dedent()
ycw 2 years ago
parent
commit
07bbe50b51
1 changed files with 20 additions and 4 deletions
  1. 20 4
      docs/page.js

+ 20 - 4
docs/page.js

@@ -106,16 +106,32 @@ function onDocumentLoad() {
 
 	// handle code snippets formatting
 
+	function dedent( text ) {
+
+		// ignores singleline text
+		const lines = text.split( '\n' );
+		if ( lines.length <= 1 ) return text;
+
+		// ignores blank text
+		const nonBlankLine = lines.filter( l => l.trim() )[ 0 ];
+		if ( nonBlankLine === undefined ) return text;
+
+		// strips indents if any
+		const m = nonBlankLine.match( /^([\t ]+)/ );
+		if ( m ) text = lines.map( l => l.startsWith( m[ 1 ] ) ? l.substring( m[ 1 ].length ) : l ).join( '\n' );
+
+		// strips leading and trailing whitespaces finally
+		return text.trim();
+
+	}
+
 	const elements = document.getElementsByTagName( 'code' );
 
 	for ( let i = 0; i < elements.length; i ++ ) {
 
 		const element = elements[ i ];
 
-		text = element.textContent.trim();
-		text = text.replace( /^\t\t/gm, '' );
-
-		element.textContent = text;
+		element.textContent = dedent( element.textContent );
 
 	}