vue-highlight.js
Version:
Highlight.js syntax highlighter component for Vue.
443 lines (419 loc) • 14.3 kB
JavaScript
;
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var tslib_1 = require('tslib');
var hljs = _interopDefault(require('highlight.js/lib/highlight'));
var Vue = _interopDefault(require('vue'));
var detectIndent = _interopDefault(require('detect-indent'));
var redent = _interopDefault(require('redent'));
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var vueClassComponent_common = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Vue$1 = _interopDefault(Vue);
var reflectionIsSupported = typeof Reflect !== 'undefined' && Reflect.defineMetadata;
function copyReflectionMetadata(to, from) {
forwardMetadata(to, from);
Object.getOwnPropertyNames(from.prototype).forEach(function (key) {
forwardMetadata(to.prototype, from.prototype, key);
});
Object.getOwnPropertyNames(from).forEach(function (key) {
forwardMetadata(to, from, key);
});
}
function forwardMetadata(to, from, propertyKey) {
var metaKeys = propertyKey
? Reflect.getOwnMetadataKeys(from, propertyKey)
: Reflect.getOwnMetadataKeys(from);
metaKeys.forEach(function (metaKey) {
var metadata = propertyKey
? Reflect.getOwnMetadata(metaKey, from, propertyKey)
: Reflect.getOwnMetadata(metaKey, from);
if (propertyKey) {
Reflect.defineMetadata(metaKey, metadata, to, propertyKey);
}
else {
Reflect.defineMetadata(metaKey, metadata, to);
}
});
}
var fakeArray = { __proto__: [] };
var hasProto = fakeArray instanceof Array;
function createDecorator(factory) {
return function (target, key, index) {
var Ctor = typeof target === 'function'
? target
: target.constructor;
if (!Ctor.__decorators__) {
Ctor.__decorators__ = [];
}
if (typeof index !== 'number') {
index = undefined;
}
Ctor.__decorators__.push(function (options) { return factory(options, key, index); });
};
}
function mixins() {
var Ctors = [];
for (var _i = 0; _i < arguments.length; _i++) {
Ctors[_i] = arguments[_i];
}
return Vue$1.extend({ mixins: Ctors });
}
function isPrimitive(value) {
var type = typeof value;
return value == null || (type !== 'object' && type !== 'function');
}
function collectDataFromConstructor(vm, Component) {
// override _init to prevent to init as Vue instance
var originalInit = Component.prototype._init;
Component.prototype._init = function () {
var _this = this;
// proxy to actual vm
var keys = Object.getOwnPropertyNames(vm);
// 2.2.0 compat (props are no longer exposed as self properties)
if (vm.$options.props) {
for (var key in vm.$options.props) {
if (!vm.hasOwnProperty(key)) {
keys.push(key);
}
}
}
keys.forEach(function (key) {
if (key.charAt(0) !== '_') {
Object.defineProperty(_this, key, {
get: function () { return vm[key]; },
set: function (value) { vm[key] = value; },
configurable: true
});
}
});
};
// should be acquired class property values
var data = new Component();
// restore original _init to avoid memory leak (#209)
Component.prototype._init = originalInit;
// create plain data object
var plainData = {};
Object.keys(data).forEach(function (key) {
if (data[key] !== undefined) {
plainData[key] = data[key];
}
});
return plainData;
}
var $internalHooks = [
'data',
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeDestroy',
'destroyed',
'beforeUpdate',
'updated',
'activated',
'deactivated',
'render',
'errorCaptured' // 2.5
];
function componentFactory(Component, options) {
if (options === void 0) { options = {}; }
options.name = options.name || Component._componentTag || Component.name;
// prototype props.
var proto = Component.prototype;
Object.getOwnPropertyNames(proto).forEach(function (key) {
if (key === 'constructor') {
return;
}
// hooks
if ($internalHooks.indexOf(key) > -1) {
options[key] = proto[key];
return;
}
var descriptor = Object.getOwnPropertyDescriptor(proto, key);
if (descriptor.value !== void 0) {
// methods
if (typeof descriptor.value === 'function') {
(options.methods || (options.methods = {}))[key] = descriptor.value;
}
else {
// typescript decorated data
(options.mixins || (options.mixins = [])).push({
data: function () {
var _a;
return _a = {}, _a[key] = descriptor.value, _a;
}
});
}
}
else if (descriptor.get || descriptor.set) {
// computed properties
(options.computed || (options.computed = {}))[key] = {
get: descriptor.get,
set: descriptor.set
};
}
});
(options.mixins || (options.mixins = [])).push({
data: function () {
return collectDataFromConstructor(this, Component);
}
});
// decorate options
var decorators = Component.__decorators__;
if (decorators) {
decorators.forEach(function (fn) { return fn(options); });
delete Component.__decorators__;
}
// find super
var superProto = Object.getPrototypeOf(Component.prototype);
var Super = superProto instanceof Vue$1
? superProto.constructor
: Vue$1;
var Extended = Super.extend(options);
forwardStaticMembers(Extended, Component, Super);
if (reflectionIsSupported) {
copyReflectionMetadata(Extended, Component);
}
return Extended;
}
function forwardStaticMembers(Extended, Original, Super) {
// We have to use getOwnPropertyNames since Babel registers methods as non-enumerable
Object.getOwnPropertyNames(Original).forEach(function (key) {
// `prototype` should not be overwritten
if (key === 'prototype') {
return;
}
// Some browsers does not allow reconfigure built-in properties
var extendedDescriptor = Object.getOwnPropertyDescriptor(Extended, key);
if (extendedDescriptor && !extendedDescriptor.configurable) {
return;
}
var descriptor = Object.getOwnPropertyDescriptor(Original, key);
// If the user agent does not support `__proto__` or its family (IE <= 10),
// the sub class properties may be inherited properties from the super class in TypeScript.
// We need to exclude such properties to prevent to overwrite
// the component options object which stored on the extended constructor (See #192).
// If the value is a referenced value (object or function),
// we can check equality of them and exclude it if they have the same reference.
// If it is a primitive value, it will be forwarded for safety.
if (!hasProto) {
// Only `cid` is explicitly exluded from property forwarding
// because we cannot detect whether it is a inherited property or not
// on the no `__proto__` environment even though the property is reserved.
if (key === 'cid') {
return;
}
var superDescriptor = Object.getOwnPropertyDescriptor(Super, key);
if (!isPrimitive(descriptor.value) &&
superDescriptor &&
superDescriptor.value === descriptor.value) {
return;
}
}
Object.defineProperty(Extended, key, descriptor);
});
}
function Component(options) {
if (typeof options === 'function') {
return componentFactory(options);
}
return function (Component) {
return componentFactory(Component, options);
};
}
Component.registerHooks = function registerHooks(keys) {
$internalHooks.push.apply($internalHooks, keys);
};
exports.default = Component;
exports.createDecorator = createDecorator;
exports.mixins = mixins;
});
var Component = unwrapExports(vueClassComponent_common);
var vueClassComponent_common_1 = vueClassComponent_common.createDecorator;
var vueClassComponent_common_2 = vueClassComponent_common.mixins;
/** vue-property-decorator verson 7.3.0 MIT LICENSE copyright 2018 kaorun343 */
/**
* decorator of a prop
* @param options the options for the prop
* @return PropertyDecorator | void
*/
function Prop(options) {
if (options === void 0) { options = {}; }
return vueClassComponent_common_1(function (componentOptions, k) {
(componentOptions.props || (componentOptions.props = {}))[k] = options;
});
}
/**
* Escape code.
*
* @export
* @param {string} code Code.
* @returns {string}
*/
function escape(code) {
if (typeof code === 'string') {
return code
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
else {
return code;
}
}
/**
* Deeply get concatenated text from slot.
*
* @export
* @param {VNode[]} slot A slot. (The collection of VNode)
* @returns {string}
*/
function getSlotText(slot) {
if (Array.isArray(slot)) {
return slot
.map(function (node) {
if (Array.isArray(node.children) && node.children.length > 0) {
return getSlotText(node.children);
}
else {
return node.text;
}
})
.join('');
}
else {
return '';
}
}
/**
* Indent code.
*
* @export
* @param {string} code Code.
* @returns {string}
*/
function indentCode(code) {
if (typeof code === 'string') {
var indent = detectIndent(code).indent || '\t';
code = redent(code, 0, indent);
return code.trim();
}
else {
return code;
}
}
/**
* Register Highlight.js languages.
*
* @export
* @param {Record<string, HLJSLang>} languages Highlight.js languages
*/
function registerLanguages(languages) {
if (typeof languages !== 'object') {
return;
}
Object.keys(languages).forEach(function (languageName) {
var language = languages[languageName];
hljs.registerLanguage(languageName, language);
});
}
var inlineStyles = {
display: 'inline !important',
'vertical-align': 'middle'
};
var HighlightCode = /** @class */ (function (_super) {
tslib_1.__extends(HighlightCode, _super);
function HighlightCode() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(HighlightCode.prototype, "hasCode", {
get: function () {
return typeof this.code === 'string' && this.code.length > 0;
},
enumerable: true,
configurable: true
});
HighlightCode.prototype.render = function (h) {
var _a;
var _b = this, hasCode = _b.hasCode, inline = _b.inline, auto = _b.auto;
var lang = this.lang;
var code = hasCode ? this.code : getSlotText(this.$slots.default); // If no `code`, get text from default slot.
// Indent code if not use inline mode.
if (!inline) {
code = indentCode(code);
}
var highlightedCode;
try {
if (auto) {
(_a = hljs.highlightAuto(code), lang = _a.language, highlightedCode = _a.value);
}
else {
highlightedCode = lang
? hljs.highlight(lang, code).value
: escape(code); // If no `lang`, just display plain code.
}
}
catch (err) {
highlightedCode = escape(code);
console.error(err);
}
return h(!inline ? 'pre' : 'span', [
h('code', {
class: ['hljs'].concat((lang ? [lang] : [])),
style: inline ? inlineStyles : {},
domProps: {
innerHTML: highlightedCode
}
})
]);
};
tslib_1.__decorate([
Prop(String)
], HighlightCode.prototype, "lang", void 0);
tslib_1.__decorate([
Prop({ type: Boolean, default: false })
], HighlightCode.prototype, "inline", void 0);
tslib_1.__decorate([
Prop(String)
], HighlightCode.prototype, "code", void 0);
tslib_1.__decorate([
Prop(Boolean)
], HighlightCode.prototype, "auto", void 0);
HighlightCode = tslib_1.__decorate([
Component({
name: 'HighlightCode'
})
], HighlightCode);
return HighlightCode;
}(Vue));
/**
* Install Vue Highlight.js as plugin.
*
* @param {typeof Vue} vue Vue
* @param {Options} [options={ languages: {} }] Options
*/
var install = function (vue, options) {
if (options === void 0) { options = { languages: {} }; }
var languages = options.languages;
{
// Register languages from options in non-web bundle
registerLanguages(languages);
}
vue.component('highlight-code', HighlightCode);
};
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
var index = {
install: install
};
module.exports = index;
//# sourceMappingURL=vue-highlight.cjs.js.map