ng-prism
Version:
An Angular2 codeblock highlighting component using Prismjs.
1,636 lines • 60.1 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("@angular/common"), require("@angular/core"), require("@angular/http"), require("rxjs/Observable"), require("rxjs/Subject"), require("rxjs/add/observable/empty"), require("rxjs/add/observable/timer"), require("rxjs/add/operator/catch"), require("rxjs/add/operator/debounce"), require("rxjs/add/operator/distinctUntilChanged"), require("rxjs/add/operator/do"), require("rxjs/add/operator/filter"), require("rxjs/add/operator/map"), require("rxjs/add/operator/retry"), require("rxjs/add/operator/switchMap"));
else if(typeof define === 'function' && define.amd)
define(["@angular/common", "@angular/core", "@angular/http", "rxjs/Observable", "rxjs/Subject", "rxjs/add/observable/empty", "rxjs/add/observable/timer", "rxjs/add/operator/catch", "rxjs/add/operator/debounce", "rxjs/add/operator/distinctUntilChanged", "rxjs/add/operator/do", "rxjs/add/operator/filter", "rxjs/add/operator/map", "rxjs/add/operator/retry", "rxjs/add/operator/switchMap"], factory);
else if(typeof exports === 'object')
exports["ng-prism.umd"] = factory(require("@angular/common"), require("@angular/core"), require("@angular/http"), require("rxjs/Observable"), require("rxjs/Subject"), require("rxjs/add/observable/empty"), require("rxjs/add/observable/timer"), require("rxjs/add/operator/catch"), require("rxjs/add/operator/debounce"), require("rxjs/add/operator/distinctUntilChanged"), require("rxjs/add/operator/do"), require("rxjs/add/operator/filter"), require("rxjs/add/operator/map"), require("rxjs/add/operator/retry"), require("rxjs/add/operator/switchMap"));
else
root["ng-prism.umd"] = factory(root["@angular/common"], root["@angular/core"], root["@angular/http"], root["rxjs/Observable"], root["rxjs/Subject"], root["rxjs/add/observable/empty"], root["rxjs/add/observable/timer"], root["rxjs/add/operator/catch"], root["rxjs/add/operator/debounce"], root["rxjs/add/operator/distinctUntilChanged"], root["rxjs/add/operator/do"], root["rxjs/add/operator/filter"], root["rxjs/add/operator/map"], root["rxjs/add/operator/retry"], root["rxjs/add/operator/switchMap"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__, __WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_16__, __WEBPACK_EXTERNAL_MODULE_17__, __WEBPACK_EXTERNAL_MODULE_18__, __WEBPACK_EXTERNAL_MODULE_19__, __WEBPACK_EXTERNAL_MODULE_20__, __WEBPACK_EXTERNAL_MODULE_21__, __WEBPACK_EXTERNAL_MODULE_22__, __WEBPACK_EXTERNAL_MODULE_23__, __WEBPACK_EXTERNAL_MODULE_24__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmory imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmory exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 25);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_0__;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = __webpack_require__(0);
__webpack_require__(5);
__webpack_require__(7);
__webpack_require__(6);
__webpack_require__(9);
__webpack_require__(8);
__webpack_require__(10);
/**
* Represent template tags added by angular structural directives
*/
var TEMPLATE_REGEX = /<!--template\sbindings={[^\}]*}-->/g;
/**
* Code highlighting component
*
* Used internally by a codeblock to perform the actual highlighting.
*/
var CodeRendererComponent = (function () {
function CodeRendererComponent(_renderer) {
this._renderer = _renderer;
}
CodeRendererComponent.prototype.render = function () {
this._replaceCode();
this._highlight();
};
/**
* Clear the code.
*/
CodeRendererComponent.prototype.empty = function () {
if (this._pre) {
this._pre.nativeElement.innerHTML = '';
}
};
/**
* Place the new code element in the template
*/
CodeRendererComponent.prototype._replaceCode = function () {
this._renderer.setElementProperty(this._pre.nativeElement, 'innerHTML', this._buildCodeElement());
};
/**
* Perform the actual highlighting
*/
CodeRendererComponent.prototype._highlight = function () {
// this._truncateLargeFiles();
Prism.highlightElement(this._pre.nativeElement.querySelector('code'), false, null);
if (this.shell && this.outputLines) {
this._fixPromptOutputPadding();
}
};
Object.defineProperty(CodeRendererComponent.prototype, "_processedCode", {
/**
* Code prepared for highlighting and display
*/
get: function () {
return this._isMarkup(this.language)
? this._processMarkup(this.code)
: this.code;
},
enumerable: true,
configurable: true
});
/**
* Format markup for display.
*/
CodeRendererComponent.prototype._processMarkup = function (text) {
return this._replaceTags(this._removeAngularMarkup(text));
};
/**
* Change all opening < changed to < to render markup correctly inside pre
* tags
*/
CodeRendererComponent.prototype._replaceTags = function (text) {
return text.replace(/(<)([!\/A-Za-z](.|[\n\r])*?>)/g, '<$2');
};
/**
* Remove both template tags and styling attributes added by the angular2
* parser and fix indentation within code elements created by structural
* directives.
*/
CodeRendererComponent.prototype._removeAngularMarkup = function (html) {
// remove styling attributes (_ngcontent etc.)
html = html.replace(/\s_ng[^-]+-[^-]+-[^=]+="[^"]*"/g, '');
var lines = this._fixIndentation(html);
// remove empty <!--template--> lines
lines = lines.filter(function (line) {
if (line.trim() === '') {
return true;
}
var replaced = line.replace(TEMPLATE_REGEX, '')
.trim();
return replaced !== '';
});
html = lines.join('\n');
// remove <!--template--> tags on lines with code
return html.replace(TEMPLATE_REGEX, '');
};
/**
* Is the language given a markup language?
*/
CodeRendererComponent.prototype._isMarkup = function (language) {
return language === 'markup' || language === 'markdown';
};
/**
* Create a <code> element with the proper classes and formatted code
*/
CodeRendererComponent.prototype._buildCodeElement = function () {
return "<code class=\"" + this.codeClasses + "\">" + this._processedCode + "</code>";
};
Object.defineProperty(CodeRendererComponent.prototype, "languageClass", {
/**
* Styling classes
*/
get: function () {
return 'language-' + this.language;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeRendererComponent.prototype, "lineNumbersClass", {
get: function () {
return this.lineNumbers ? 'line-numbers' : '';
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeRendererComponent.prototype, "shellClass", {
get: function () {
return this.shell ? 'command-line' : '';
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeRendererComponent.prototype, "codeClasses", {
get: function () {
return this.languageClass + ' ' + this.language;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeRendererComponent.prototype, "preClasses", {
get: function () {
return this.lineNumbersClass + ' ' + this.languageClass + ' ' + this.shellClass;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeRendererComponent.prototype, "_codeEl", {
/* Code Styling **/
/**
* The code element within <pre>
*/
get: function () {
return this._pre.nativeElement.querySelector('code');
},
enumerable: true,
configurable: true
});
/**
* Adds back padding on output shells because of floated left prompt
*/
CodeRendererComponent.prototype._fixPromptOutputPadding = function () {
if (this._codeEl) {
var clp = this._codeEl.querySelector('.command-line-prompt');
if (clp) {
var promptWidth = this._codeEl.querySelector('.command-line-prompt').clientWidth;
var prePadding = parseInt(this._getStyle(this._pre.nativeElement, 'padding-left')
.replace('px', ''), 10);
this._pre.nativeElement.style.paddingRight = (2 * prePadding + promptWidth / 2) + 'px';
}
}
};
/**
* Get the actually applied style of an element
*/
CodeRendererComponent.prototype._getStyle = function (oElm, strCssRule) {
var strValue = '';
if (document.defaultView && document.defaultView.getComputedStyle) {
strValue = document.defaultView.getComputedStyle(oElm, '')
.getPropertyValue(strCssRule);
}
else if (oElm.currentStyle) {
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
};
// _truncateLargeFiles() {
// if (this._codeEl.innerHTML.length > this.truncationSize) {
// this._codeEl.innerHTML = this._codeEl.innerHTML.slice(0,
// this.truncationSize) + "\n" + this.truncationMessage + "\n"; } }
/**
* Remove extra indentation in ngSwitches
*/
CodeRendererComponent.prototype._fixIndentation = function (html) {
var indent = 0;
var diff = 0;
var removeLines = [];
var lines = html.split('\n')
.map(function (line, index) {
if (line.trim() === '') {
if (indent > 0) {
removeLines.push(index);
}
indent = 0;
return '';
}
var a = line.replace(TEMPLATE_REGEX, '')
.trim();
if (a === '') {
indent = line.match(/^\s*/)[0].length;
return line;
}
else if (indent > 0) {
length = line.match(/^\s*/)[0].length;
if (diff === 0) {
diff = length - indent;
}
if (length >= indent) {
return line.slice(diff);
}
else {
indent = 0;
}
}
return line;
});
// remove empty lines added by ngSwitch
removeLines.forEach(function (removalIndex) {
lines.splice(removalIndex, 1);
});
return lines;
};
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeRendererComponent.prototype, "code", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeRendererComponent.prototype, "language", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', Boolean)
], CodeRendererComponent.prototype, "lineNumbers", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeRendererComponent.prototype, "shell", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeRendererComponent.prototype, "prompt", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeRendererComponent.prototype, "outputLines", void 0);
__decorate([
core_1.ViewChild('preEl'),
__metadata('design:type', Object)
], CodeRendererComponent.prototype, "_pre", void 0);
CodeRendererComponent = __decorate([
core_1.Component({
selector: 'code-renderer',
template: "\n<pre #preEl [class]=\"preClasses\" [attr.data-prompt]=\"prompt\" [attr.data-output]=\"outputLines\"></pre>\n "
}),
__metadata('design:paramtypes', [core_1.Renderer])
], CodeRendererComponent);
return CodeRendererComponent;
}());
exports.CodeRendererComponent = CodeRendererComponent;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
// tslint:disable:max-file-line-count
var core_1 = __webpack_require__(0);
var code_renderer_component_1 = __webpack_require__(1);
var CodeblockComponent = (function () {
function CodeblockComponent(_elementRef) {
this.DEFAULT_THEME = 'standard';
this.DEFAULT_SHELL_THEME = 'okaidia';
/**
* The prompt to display in a shell codeblock. Default is $.
*
* Example:
* ```
* <codeblock shell="bash" prompt="#">
* cd ..
* </codeblock>
* ```
* Result:
* ```
* # cd ..
* ```
*/
this.prompt = '$';
this._code = '';
this._showingMessage = false;
this._languageSet = false;
this._lineNumbers = true;
this._changed = false;
this._shellType = null;
this._elementRef = _elementRef;
}
Object.defineProperty(CodeblockComponent.prototype, "lineNumbers", {
get: function () {
return this._lineNumbers;
},
/* Inputs */
/**
* Display line numbers for the codeblock. The numbers start at 1 and are
* not selected when selecting the main code text.
*
* Example:
* ```
* <codeblock [lineNumbers]="true" markup>
* <h1>Hello</h1>
* <h1>Hi</h1>
* <h1>Aloha</h1>
* </codeblock>
* ```
*
* Result:
* ```
* 1 <h1>Hello</h1>
* 2 <h1>Hi</h1>
* 3 <h1>Aloha</h1>
* ```
*
* @param {boolean} value - whether or not to show line numbers
*/
set: function (value) {
if (this._lineNumbers !== value) {
this._changed = true;
this._lineNumbers = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeblockComponent.prototype, "language", {
get: function () {
return this._showingMessage ? undefined : this._language;
},
/**
* Set the language used to highlight the code within the codeblock.
* Consider using a language directive instead if the language is not
* going to change dynamically.
*
* Example:
* <codeblock language="markup">
* <h1>This is HTML</h1>
* </codeblock>
*
* @param lang
*/
set: function (lang) {
if (this.isShell()) {
return;
}
this._languageSet = !!(lang && lang.length > 0);
this._language = Prism.languages[lang] ? lang : undefined;
this._changed = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeblockComponent.prototype, "theme", {
get: function () {
if (this._theme) {
return this._theme;
}
return this.isShell() ? this.DEFAULT_SHELL_THEME : this.DEFAULT_THEME;
},
/**
* The theme for styling the codeblock. All prismjs themes are available.
*
* @param {string} theme - A prismjs theme. Defaults to 'standard'.
*/
set: function (theme) {
this._theme = theme;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeblockComponent.prototype, "shell", {
get: function () {
return this._shellType;
},
/**
* Turn this codeblock into a shell display with a prompt.
*
* Example:
* ```
* <codeblock shell="bash">
* cd ..
* mkdir project
* </codeblock>
* ```
* Result:
* ```
* $ cd ..
* $ mkdir project
* ```
*
* @param {string} shellType - One of CodeblockComponent.SHELL_TYPES
*/
set: function (shellType) {
if (shellType && CodeblockComponent.SHELL_TYPES.indexOf(shellType) !== -1) {
this._language = shellType;
this._languageSet = true;
this._shellType = shellType;
this.lineNumbers = false;
this._changed = true;
}
else {
this._shellType = null;
}
},
enumerable: true,
configurable: true
});
/* Lifecycle Events **/
/**
* Update code when content changes
*/
CodeblockComponent.prototype.ngAfterContentChecked = function () {
if (!this._sourced && !this._showingMessage) {
this.code = this.content;
}
};
/**
* Render code when any input changes
*/
CodeblockComponent.prototype.ngAfterViewChecked = function () {
if (this._changed) {
this._changed = false;
this.codeRenderer.render();
}
};
Object.defineProperty(CodeblockComponent.prototype, "content", {
/* Attributes */
/**
* The current content of the codeblock.
*
* Example:
* ```
* <codeblock javascript>
* // Inside the codeblock
* </codeblock>
* ```
* Result:
* ```
* // Inside the codeblock
* ```
*
* @return {string} - innerHTML of this codeblock's nativeElement
*/
get: function () {
return this.contentEl ? this.contentEl.nativeElement.innerHTML : '';
},
enumerable: true,
configurable: true
});
Object.defineProperty(CodeblockComponent.prototype, "code", {
get: function () {
return this._code;
},
/**
* The code to display in the codeblock. Automatically set to this.content
* unless a src attribute is present.
*/
set: function (code) {
if (this._code !== code) {
this._changed = true;
// this._showingMessage = false;
this._code = code;
}
},
enumerable: true,
configurable: true
});
/**
* The source has been changed
*/
CodeblockComponent.prototype.sourceChanged = function (url) {
this.message('Loading ...');
};
/**
* Given the downloaded source, set the language and code to match it.
*
* @param {Response} res
*/
CodeblockComponent.prototype.sourceReceived = function (res) {
var ext = res.url.match(/\.(\w+)$/)[1];
var fileLang = CodeblockComponent.EXTENSION_MAP[ext] || ext;
var text = res.text();
if (!this._languageSet) {
this._language = fileLang;
if (fileLang === 'typescript') {
text = this._replaceTagsInMultiline(res.text());
}
}
this.code = text;
this._showingMessage = false;
this._sourced = true;
};
/**
* An error occured while downloading from the src url
*
* @param {Error} error
*/
CodeblockComponent.prototype.sourceError = function (error) {
this._sourced = false;
this.message(error.message ? error.message : 'An error occured.');
};
/**
* Is this displayed as a shell?
*/
CodeblockComponent.prototype.isShell = function () {
return this._shellType !== null;
};
/**
* @return {boolean} - whether or not lineNumbers should be displayed
*/
CodeblockComponent.prototype.shouldDisplayLineNumbers = function () {
return this.lineNumbers && !this._showingMessage;
};
/*** Truncation ***/
// @Input() truncationSize: number = 100000;
// @Input() truncationMessage: string = "\n--- File Truncated ---\n";
/*** Methods ***/
/**
* Display the text inside the codeblock instead of code. Used for errors
* and warnings during file loading. The language of the codeblock will
* be set to undefined when displaying a message.
*
* @param {string} text - The message to display.
*/
CodeblockComponent.prototype.message = function (text) {
this._showingMessage = true;
this.code = text;
};
/**
* Returns a double curly-braced version of the input string.
* Use this inside a template to display a binding.
*
* Example:
* ```
* <codeblock markup #cb><span>{{cb.bind('name')}}</span></codeblock>
* ```
* Result:
* ```
* <span>{{name}}</span>
* ```
*
* @param {string} text - the text to wrap in curly braces
*/
CodeblockComponent.prototype.bind = function (text) {
return "{{" + text + "}}";
};
/************ Private **************/
/**
* Use html < for leading < tags in multiline typescript strings
*
* @param {string} text - the code
* @return {string} - the code with < replaced by < inside ``s
*/
CodeblockComponent.prototype._replaceTagsInMultiline = function (text) {
return text.replace(/`((.|[\r\n])*?)`/g, function (match) {
return match.replace(/(<)([!\/A-Za-z].*?>)/g, '<$2');
});
};
/**
* Map of file extensions to highlighting languages
*/
CodeblockComponent.EXTENSION_MAP = {
js: 'javascript',
ts: 'typescript',
html: 'markup',
svg: 'markup',
xml: 'markup',
md: 'markdown',
py: 'python',
rb: 'ruby',
ps1: 'powershell',
psm1: 'powershell'
};
/**
* Possible shell types
*/
CodeblockComponent.SHELL_TYPES = ['bash', 'powershell'];
/**
* A list of the valid codeblock themes.
*
* Example:
* ```
* <select name="select" [(ngModel)]="selectedTheme">
* <option *ngFor="#theme of CodeblockComponent.THEMES"
* value="{{theme}}">{{theme}}</option>
* </select>
* ```
*/
CodeblockComponent.THEMES = [
'standard',
'coy',
'dark',
'funky',
'okaidia',
'solarizedlight',
'tomorrow',
'twilight'
];
__decorate([
core_1.Input(),
__metadata('design:type', Boolean),
__metadata('design:paramtypes', [Boolean])
], CodeblockComponent.prototype, "lineNumbers", null);
__decorate([
core_1.Input(),
__metadata('design:type', String),
__metadata('design:paramtypes', [String])
], CodeblockComponent.prototype, "language", null);
__decorate([
core_1.Input(),
__metadata('design:type', String),
__metadata('design:paramtypes', [String])
], CodeblockComponent.prototype, "theme", null);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeblockComponent.prototype, "prompt", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], CodeblockComponent.prototype, "outputLines", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String),
__metadata('design:paramtypes', [String])
], CodeblockComponent.prototype, "shell", null);
__decorate([
core_1.ViewChild('contentEl'),
__metadata('design:type', Object)
], CodeblockComponent.prototype, "contentEl", void 0);
__decorate([
core_1.ViewChild(code_renderer_component_1.CodeRendererComponent),
__metadata('design:type', Object)
], CodeblockComponent.prototype, "codeRenderer", void 0);
CodeblockComponent = __decorate([
core_1.Component({
selector: 'codeblock',
template: "\n <div #contentEl class=\"codeblock-content\" style=\"display: none\"><ng-content></ng-content></div>\n <div class=\"codeblock {{theme}}\">\n <code-renderer\n [code]=\"code\"\n [language]=\"language\"\n [lineNumbers]=\"shouldDisplayLineNumbers()\"\n [shell]=\"shell\"\n [prompt]=\"prompt\"\n [outputLines]=\"outputLines\">\n </code-renderer>\n </div>\n ",
// necessary to make component styles apply because unique ng attributes
// aren't applied to elements added by Prism.highlight
encapsulation: core_1.ViewEncapsulation.None
}),
__metadata('design:paramtypes', [core_1.ElementRef])
], CodeblockComponent);
return CodeblockComponent;
}());
exports.CodeblockComponent = CodeblockComponent;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var core_1 = __webpack_require__(0);
var http_1 = __webpack_require__(12);
// import { Sourcable } from './sourcable';
var Observable_1 = __webpack_require__(13);
var Subject_1 = __webpack_require__(14);
__webpack_require__(15);
__webpack_require__(16);
__webpack_require__(22);
__webpack_require__(21);
__webpack_require__(19);
__webpack_require__(18);
__webpack_require__(20);
__webpack_require__(23);
__webpack_require__(17);
__webpack_require__(24);
exports.SourceDebounceTime = 300;
var SrcDirective = (function () {
function SrcDirective(_element, _http, _renderer, _sourceDebounceTime) {
this.sourceChanged = new Subject_1.Subject();
this._debounceTime = 300;
this._firstRequest = true;
this._element = _element;
this._http = _http;
this._renderer = _renderer;
this._sourceDebounceTime = _sourceDebounceTime;
}
Object.defineProperty(SrcDirective.prototype, "src", {
set: function (source) {
this._src = source;
this.sourceChanged.next(source);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SrcDirective.prototype, "debounceTime", {
get: function () {
return this._debounceTime;
},
/**
* Set the amount of time in ms to wait before processing changes to the src
* input.
*
* This can prevent unnecessary http requests. The default is 300ms.
*/
set: function (time) {
var parsed = parseInt(time, 10);
if (!isNaN(parsed) && parsed >= 0) {
this._debounceTime = parsed;
}
},
enumerable: true,
configurable: true
});
SrcDirective.prototype.ngOnInit = function () {
// this.host = this._element as Sourcable;
this.host = this._element;
if (this.host === this) {
this.host = this._element;
}
if (this._sourceDebounceTime) {
this.debounceTime = this._sourceDebounceTime;
}
this._handleSourceChanges();
if (this._src) {
this.sourceChanged.next(this._src);
}
};
SrcDirective.prototype.ngOnDestroy = function () {
if (this._subscription) {
this._subscription.unsubscribe();
}
};
SrcDirective.prototype._handleSourceChanges = function () {
var _this = this;
this._subscription = this.sourceChanged
.do(function (source) {
if (_this.host.sourceChanged) {
_this.host.sourceChanged(source);
}
})
.filter(function (source) {
return _this._emptySources(source);
})
.map(function (source) {
return _this._addExtensionMatches(source);
})
.filter(function (req) {
return _this._nonFiles(req);
})
.distinctUntilChanged()
.do(function (req) {
if (_this.host.sourceLoading) {
_this.host.sourceLoading(req.source);
}
})
.debounce(function () { return Observable_1.Observable.timer(_this._firstRequest
? 0
: _this.debounceTime); })
.do(function () { return _this._firstRequest = false; })
.switchMap(function (req) {
return _this._fetchSrc(req);
})
.catch(function (error) {
if (_this.host.sourceError) {
_this.host.sourceError(error);
}
console.error(error);
return Observable_1.Observable.empty();
})
.subscribe(function (res) {
if (_this.host.sourceReceived) {
_this.host.sourceReceived(res);
}
else {
_this._renderer.setElementProperty(_this._element.nativeElement, 'innerHTML', res.text());
}
}, function (error) {
if (_this.host.sourceError) {
_this.host.sourceError(error);
}
console.error(error);
});
};
SrcDirective.prototype._emptySources = function (source) {
return !(source === undefined || source === null || source === '');
};
SrcDirective.prototype._addExtensionMatches = function (source) {
return { source: source, extMatches: source.match(/\.(\w+)$/) };
};
SrcDirective.prototype._nonFiles = function (req) {
if (!req.extMatches) {
if (req.source && req.source.length > 0) {
if (this.host.sourceError) {
this.host.sourceError({ message: req.source + " is not a file." });
}
}
else {
if (this.host.sourceError) {
this.host.sourceError({ message: "No source file given." });
}
}
return false;
}
return true;
};
SrcDirective.prototype._fetchSrc = function (req) {
var _this = this;
return this._http
.get(req.source)
.catch(function (error) {
if (_this.host.sourceError) {
_this.host.sourceError({ message: req.source + " not found." });
}
return Observable_1.Observable.empty();
});
};
__decorate([
core_1.Input(),
__metadata('design:type', String),
__metadata('design:paramtypes', [String])
], SrcDirective.prototype, "src", null);
__decorate([
core_1.Input(),
__metadata('design:type', Object),
__metadata('design:paramtypes', [Object])
], SrcDirective.prototype, "debounceTime", null);
SrcDirective = __decorate([
core_1.Directive({ selector: '[src]' }),
__param(3, core_1.Optional()),
__param(3, core_1.Inject(exports.SourceDebounceTime)),
__metadata('design:paramtypes', [core_1.ElementRef, http_1.Http, core_1.Renderer, Number])
], SrcDirective);
return SrcDirective;
}());
exports.SrcDirective = SrcDirective;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = __webpack_require__(0);
var common_1 = __webpack_require__(11);
var codeblock_component_1 = __webpack_require__(2);
var code_renderer_component_1 = __webpack_require__(1);
var src_directive_1 = __webpack_require__(3);
var COMP_DIRECTIVES = [code_renderer_component_1.CodeRendererComponent, codeblock_component_1.CodeblockComponent, src_directive_1.SrcDirective];
var CodeblockModule = (function () {
function CodeblockModule() {
}
CodeblockModule = __decorate([
core_1.NgModule({
imports: [common_1.CommonModule],
declarations: COMP_DIRECTIVES.slice(),
exports: COMP_DIRECTIVES.slice()
}),
__metadata('design:paramtypes', [])
], CodeblockModule);
return CodeblockModule;
}());
exports.CodeblockModule = CodeblockModule;
/***/ },
/* 5 */
/***/ function(module, exports) {
(function(Prism) {
var insideString = {
variable: [
// Arithmetic Environment
{
pattern: /\$?\(\([\w\W]+?\)\)/,
inside: {
// If there is a $ sign at the beginning highlight $(( and )) as variable
variable: [{
pattern: /(^\$\(\([\w\W]+)\)\)/,
lookbehind: true
},
/^\$\(\(/,
],
number: /\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee]-?\d+)?)\b/,
// Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
operator: /--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/,
// If there is no $ sign at the beginning highlight (( and )) as punctuation
punctuation: /\(\(?|\)\)?|,|;/
}
},
// Command Substitution
{
pattern: /\$\([^)]+\)|`[^`]+`/,
inside: {
variable: /^\$\(|^`|\)$|`$/
}
},
/\$(?:[a-z0-9_#\?\*!@]+|\{[^}]+\})/i
],
};
Prism.languages.bash = {
'shebang': {
pattern: /^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/,
alias: 'important'
},
'comment': {
pattern: /(^|[^"{\\])#.*/,
lookbehind: true
},
'string': [
//Support for Here-Documents https://en.wikipedia.org/wiki/Here_document
{
pattern: /((?:^|[^<])<<\s*)(?:"|')?(\w+?)(?:"|')?\s*\r?\n(?:[\s\S])*?\r?\n\2/g,
lookbehind: true,
greedy: true,
inside: insideString
},
{
pattern: /(["'])(?:\\\\|\\?[^\\])*?\1/g,
greedy: true,
inside: insideString
}
],
'variable': insideString.variable,
// Originally based on http://ss64.com/bash/
'function': {
pattern: /(^|\s|;|\||&)(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|\s|;|\||&)/,
lookbehind: true
},
'keyword': {
pattern: /(^|\s|;|\||&)(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|\s|;|\||&)/,
lookbehind: true
},
'boolean': {
pattern: /(^|\s|;|\||&)(?:true|false)(?=$|\s|;|\||&)/,
lookbehind: true
},
'operator': /&&?|\|\|?|==?|!=?|<<<?|>>|<=?|>=?|=~/,
'punctuation': /\$?\(\(?|\)\)?|\.\.|[{}[\];]/
};
var inside = insideString.variable[1].inside;
inside['function'] = Prism.languages.bash['function'];
inside.keyword = Prism.languages.bash.keyword;
inside.boolean = Prism.languages.bash.boolean;
inside.operator = Prism.languages.bash.operator;
inside.punctuation = Prism.languages.bash.punctuation;
})(Prism);
/***/ },
/* 6 */
/***/ function(module, exports) {
Prism.languages.javascript = Prism.languages.extend('clike', {
'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,
'number': /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,
// Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
'function': /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i,
'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*\*?|\/|~|\^|%|\.{3}/
});
Prism.languages.insertBefore('javascript', 'keyword', {
'regex': {
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,
lookbehind: true,
greedy: true
}
});
Prism.languages.insertBefore('javascript', 'string', {
'template-string': {
pattern: /`(?:\\\\|\\?[^\\])*?`/,
greedy: true,
inside: {
'interpolation': {
pattern: /\$\{[^}]+\}/,
inside: {
'interpolation-punctuation': {
pattern: /^\$\{|\}$/,
alias: 'punctuation'
},
rest: Prism.languages.javascript
}
},
'string': /[\s\S]+/
}
}
});
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
'script': {
pattern: /(<script[\w\W]*?>)[\w\W]*?(?=<\/script>)/i,
lookbehind: true,
inside: Prism.languages.javascript,
alias: 'language-javascript'
}
});
}
Prism.languages.js = Prism.languages.javascript;
/***/ },
/* 7 */
/***/ function(module, exports) {
Prism.languages.powershell = {
'comment': [
{
pattern: /(^|[^`])<#[\w\W]*?#>/,
lookbehind: true
},
{
pattern: /(^|[^`])#.*/,
lookbehind: true
}
],
'string': [
{
pattern: /"(`?[\w\W])*?"/,
greedy: true,
inside: {
'function': {
pattern: /[^`]\$\(.*?\)/,
// Populated at end of file
inside: {}
}
}
},
{
pattern: /'([^']|'')*'/,
greedy: true
}
],
// Matches name spaces as well as casts, attribute decorators. Force starting with letter to avoid matching array indices
'namespace': /\[[a-z][\w\W]*?\]/i,
'boolean': /\$(true|false)\b/i,
'variable': /\$\w+\b/i,
// Cmdlets and aliases. Aliases should come last, otherwise "write" gets preferred over "write-host" for example
// Get-Command | ?{ $_.ModuleName -match "Microsoft.PowerShell.(Util|Core|Management)" }
// Get-Alias | ?{ $_.ReferencedCommand.Module.Name -match "Microsoft.PowerShell.(Util|Core|Management)" }
'function': [
/\b(Add-(Computer|Content|History|Member|PSSnapin|Type)|Checkpoint-Computer|Clear-(Content|EventLog|History|Item|ItemProperty|Variable)|Compare-Object|Complete-Transaction|Connect-PSSession|ConvertFrom-(Csv|Json|StringData)|Convert-Path|ConvertTo-(Csv|Html|Json|Xml)|Copy-(Item|ItemProperty)|Debug-Process|Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Disconnect-PSSession|Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Enter-PSSession|Exit-PSSession|Export-(Alias|Clixml|Console|Csv|FormatData|ModuleMember|PSSession)|ForEach-Object|Format-(Custom|List|Table|Wide)|Get-(Alias|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Culture|Date|Event|EventLog|EventSubscriber|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job|Location|Member|Module|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|WmiObject)|Group-Object|Import-(Alias|Clixml|Csv|LocalizedData|Module|PSSession)|Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)|Join-Path|Limit-EventLog|Measure-(Command|Object)|Move-(Item|ItemProperty)|New-(Alias|Event|EventLog|Item|ItemProperty|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy)|Out-(Default|File|GridView|Host|Null|Printer|String)|Pop-Location|Push-Location|Read-Host|Receive-(Job|PSSession)|Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)|Remove-(Computer|Event|EventLog|Item|ItemProperty|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)|Rename-(Computer|Item|ItemProperty)|Reset-ComputerMachinePassword|Resolve-Path|Restart-(Computer|Service)|Restore-Computer|Resume-(Job|Service)|Save-Help|Select-(Object|String|Xml)|Send-MailMessage|Set-(Alias|Content|Date|Item|ItemProperty|Location|PSBreakpoint|PSDebug|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)|Show-(Command|ControlPanelItem|EventLog)|Sort-Object|Split-Path|Start-(Job|Process|Service|Sleep|Transaction)|Stop-(Computer|Job|Process|Service)|Suspend-(Job|Service)|Tee-Object|Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)|Trace-Command|Unblock-File|Undo-Transaction|Unregister-(Event|PSSessionConfiguration)|Update-(FormatData|Help|List|TypeData)|Use-Transaction|Wait-(Event|Job|Process)|Where-Object|Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning))\b/i,
/\b(ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i
],
// per http://technet.microsoft.com/en-us/library/hh847744.aspx
'keyword': /\b(Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,
'operator': {
pattern: /(\W?)(!|-(eq|ne|gt|ge|lt|le|sh[lr]|not|b?(and|x?or)|(Not)?(Like|Match|Contains|In)|Replace|Join|is(Not)?|as)\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,
lookbehind: true
},
'punctuation': /[|{}[\];(),.]/
};
// Variable interpolation inside strings, and nested expressions
Prism.languages.powershell.string[0].inside.boolean = Prism.languages.powershell.boolean;
Prism.languages.powershell.string[0].inside.variable = Prism.languages.powershell.variable;
Prism.languages.powershell.string[0].inside.function.inside = Prism.util.clone(Prism.languages.powershell);
/***/ },
/* 8 */
/***/ function(module, exports) {
(function() {
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
Prism.hooks.add('complete', function (env) {
if (!env.code) {
return;
}
// Works only for <code> wrapped inside <pre> (not inline).
var pre = env.element.parentNode;
var clsReg = /\s*\bcommand-line\b\s*/;
if (
!pre || !/pre/i.test(pre.nodeName) ||
// Abort only if neither the <pre> nor the <code> have the class
(!clsReg.test(pre.className) && !clsReg.test(env.element.className))
) {
return;
}
if (env.element.querySelector('.command-line-prompt')) {
// Abort if prompt already exists.
return;
}
if (clsReg.test(env.element.className)) {
// Remove the class "command-line" from the <code>
env.element.className = env.element.className.replace(clsReg, '');
}
if (!clsReg.test(pre.className)) {
// Add the class "command-line" to the <pre>
pre.className += ' command-line';
}
var getAttribute = function(key, defaultValue) {
return (pre.getAttribute(key) || defaultValue).replace(/"/g, '"');
};
// Create the "rows" that will become the command-line prompts. -- cwells
var lines = new Array(1 + env.code.split('\n').length);
var promptText = getAttribute('data-prompt', '');
if (promptText !== '') {
lines = lines.join('<span data-prompt="' + promptText + '"></span>');
} else {
var user = getAttribute('data-user', 'user');
var host = getAttribute('data-host', 'localhost');
lines = lines.join('<span data-user="' + user + '" data-host="' + host + '"></span>');
}
// Create the wrapper element. -- cwells
var prompt = document.createElement('span');
prompt.className = 'command-line-prompt';
prompt.innerHTML = lines;
// Mark the output lines so they can be styled differently (no prompt). -- cwells
var outputSections = pre.getAttribute('data-output') || '';
outputSections = outputSections.split(',');
for (var i = 0; i < outputSections.length; i++) {
var outputRange = outputSections[i].split('-');
var outputStart = parseInt(outputRange[0]);
var outputEnd = outputStart; // Default: end at the first line when it's not an actual range. -- cwells
if (outputRange.length === 2) {
outputEnd = parseInt(outputRange[1]);
}
if (!isNaN(outputStart) && !isNaN(outputEnd)) {
for (var j = outputStart; j <= outputEnd && j <= prompt.children.length; j++) {
var node = prompt.children[j - 1];
node.removeAttribute('data-user');
node.removeAttribute('data-host');
node.removeAttribute('data-prompt');
}
}
}
env.element.innerHTML = prompt.outerHTML + env.element.innerHTML;
});
}());
/***/ },
/* 9 */
/***/ function(module, exports) {
(function() {
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
Prism.hooks.add('complete', function (env) {
if (!env.code) {
return;
}
// works only for <code> wrapped inside <pre> (not inline)
var pre = env.element.parentNode;
var clsReg = /\s*\bline-numbers\b\s*/;
if (
!pre || !/pre/i.test(pre.nodeName) ||
// Abort only if nor the <pre> nor the <code> have the class
(!clsReg.test(pre.className) && !clsReg.test(env.element.className))
) {
return;
}
if (env.element.querySelector(".line-numbers-rows")) {
// Abort if line numbers already exists
return;
}
if (clsReg.test(env.element.className)) {
// Remove the class "line-numbers" from the <code>
env.element.className = env.element.className.replace(clsReg, '');
}
if (!clsReg.test(pre.className)) {
// Add the class "line-numbers" to the <pre>
pre.className += ' line-numbers';
}
var match = env.code.match(/\n(?!$)/g);
var linesNum = match ? match.length + 1 : 1;
var lineNumbersWrapper;
var lines = new Array(linesNum + 1);
lines = lines.join('<span></span>');
lineNumbersWrapper = document.createElement('span');
lineNumbersWrapper.setAttribute('aria-hidden', 'true');
lineNumbersWrapper.className = 'line-numbers-rows';
lineNumbersWrapper.innerHTML = lines;
if (pre.hasAttribute('data-start')) {
pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1);
}
env.element.appendChild(lineNumbersWrapper);
});
}());
/***/ },
/* 10 */
/***/ function(module, exports) {
(function() {
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
var assign = Object.assign || function (obj1, obj2) {
for (var name in obj2) {
if (obj2.hasOwnProperty(name))
obj1[name] = obj2[name];
}
return obj1;
}
function NormalizeWhitespace(defaults) {
this.defaults = assign({}, defaults);
}
function toCamelCase(value) {
return value.replace(/-(\w)/g, function(match, firstChar) {
return firstChar.toUpperCase();
});
}
function tabLen(str) {
var res = 0;
for (var i = 0; i < str.length; ++i) {
if (str.charCodeAt(i) == '\t'.charCodeAt(0))
res += 3;
}
return str.length + res;
}
NormalizeWhitespace.prototype = {
setDefaults: function (defaults) {
this.defaults = assign(this.defaults, defaults);
},
normalize: function (input, settings) {
settings = assign(this.defaults, settings);
for (var name in settings) {
var methodName = toCamelCase(name);
if (name !== "normalize" && methodName !== 'setDefaults' &&
settings[name] && this[methodName]) {
input = this[methodName].call(this, input, settings[name]);
}
}
return input;
},
/*
* Normalization methods
*/
leftTrim: function (input) {
return input.replace(/^\s+/, '');
},
rightTrim: function (input) {
return input.replace(/\s+$/, '');
},
tabsToSpaces: function (input, spaces) {
spaces = spaces|0 || 4;
return input.replace(/\t/g, new Array(++spaces).join(' '));
},
spacesToTabs: function (input, spaces) {
spaces = spaces|0 || 4;
return input.replace(new RegExp(' {' + spaces + '}', 'g'), '\t');
},
removeTrailing: function (input) {
return input.replace(/\s*?$/gm, '');
},
// Support for deprecated plugin remove-initial-line-feed
removeInitialLineFeed: function (input) {
return input.replace(/^(?:\r?\n|\r)/, '');
},
removeIndent: function (input) {
var indents = input.match(/^[^\S\n\r]*(?=\S)/gm);
if (!indents || !indents[0].length)
return input;
indents.sort(function(a, b){return a.length - b.length; });
if (!indents[0].length)
return input;
return input.replace(new RegExp('^' + indents[0], 'gm'), '');
},
indent: function (input, tabs) {
return input.replace(/^[^\S\n\r]*(?=\S)/gm, new Array(++tabs).join('\t') + '$&');
},
breakLines: function (input, characters) {
characters = (characters === true) ? 80 : characters|0 || 80;
var lines = input.split('\n');
for (var i = 0; i < lines.length; ++i) {
if (tabLen(lines[i]) <= characters)
continue;
var line = lines[i].split(/(\s+)/g),
len = 0;
for (var j = 0; j < line.length; ++j) {
var tl = tabLen(line[j]);
len += tl;
if (len > characters) {
line[j] = '\n' + line[j];
len = tl;
}
}
lines[i] = line.join('');
}
return lines.join('\n');
}
};
Prism.plugins.NormalizeWhitespace = new NormalizeWhitespace({
'remove-trailing': true,
'remove-indent': true,
'left-trim': true,
'right-trim': true,
/*'break-lines': 80,
'indent': 2,
'remove-initial-line-feed': false,
'tabs-to-spaces': 4,
'spaces-to-tabs': 4*/
});
Prism.hooks.add('before-sanity-check', function (env) {
var pre = env.element.parentNode;
var clsReg = /\bno-whitespace-normalization\b/;
if (!env.code || !pre || pre.nodeName.toLowerCase() !== 'pre' ||
(env.settings && env.settings['whitespace-normalization'] === false) ||
clsReg.test(pre.className) || clsReg.test(env.element.className))
return;
var children = pre.childNodes,
before = '',
after = '',
codeFound = false,
Normalizer = Prism.plugins.NormalizeWhitespace;
// Move surrounding whitespace from the <pre> tag into the <code> tag
for (var i = 0; i < children.length; ++i) {
var node = children[i];
if (node == env.element) {
codeFound = true;
} else if (node.nodeName === "#text") {
if (codeFound) {
after += node.nodeValue;
} else {
before += node.nodeValue;
}
pre.removeChild(node);
--i;
}
}
if (!env.element.children.length || !Prism.plugins.KeepMarkup) {
env.code = before + env.code + after;
env.code = Normalizer.normalize(env.code, env.settings);
} else {
// Preserve markup for keep-markup plugin
var html = before + env.element.innerHTML + after;
env.element.innerHTML = Normalizer.normalize(html, env.settings);
env.code = env.element.textContent;
}
});
}());
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_11__;
/***/ },
/* 12 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_12__;
/***/ },
/* 13 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_13__;
/***/ },
/* 14 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_14__;
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_15__;
/***/ },
/* 16 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_16__;
/***/ },
/* 17 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_17__;
/***/ },
/* 18 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_18__;
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_19__;
/***/ },
/* 20 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_20__;
/***/ },
/* 21 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_21__;
/***/ },
/* 22 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_22__;
/***/ },
/* 23 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_23__;
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_24__;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
"use strict";
var src_directive_1 = __webpack_require__(3);
exports.SourceDebounceTime = src_directive_1.SourceDebounceTime;
exports.SrcDirective = src_directive_1.SrcDirective;
var code_renderer_component_1 = __webpack_require__(1);
exports.CodeRendererComponent = code_renderer_component_1.CodeRendererComponent;
var codeblock_component_1 = __webpack_require__(2);
exports.CodeblockComponent = codeblock_component_1.CodeblockComponent;
var codeblock_module_1 = __webpack_require__(4);
exports.CodeblockModule = codeblock_module_1.CodeblockModule;
/***/ }
/******/ ])
});
;
//# sourceMappingURL=ng-prism.umd.js.map