Commit 90e75c88 authored by Vadym Gidulian's avatar Vadym Gidulian

Initial commit

parents
/test/dist/
# Dependency directories
node_modules/
# Logs
logs/
*.log
npm-debug.log*
# Optional npm cache directory
.npm/
# Optional REPL history
.node_repl_history/
MIT License
Copyright (c) 2018 Vadym Gidulian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# vue-test-directive
A Vue directive to help test code and other directives
## Usage
### `.directive`
```js
const TestDirective = require(...);
Vue.directive('test', TestDirective.directive(options));
```
#### Options
- `disabled` (`boolean`) - disable the directive. Set via `directiveValue.disabled` or `options.disabled` (ordered by precedence)
- `hooks` (`object`) - hooks to handle by the directive. Set via `directiveValue.hooks` or modifiers or `options.hooks` (ordered by precedence)
- `label` (`string`) - directive label shown in console. Set via `directiveValue.label` or argument or `options.label` (ordered by precedence)
- `style` (`string`) - styles of console output. Set via `directiveValue.style` or `options.style` (ordered by precedence)
#### Examples
```vue
<div v-test></div>
```
```vue
<div v-test:label></div>
```
```vue
<div v-test.bind.unbind></div>
```
```vue
<div v-test:label.bind.unbind></div>
```
```vue
<div v-test="{
disabled: true,
hooks: {bind: true},
label: 'label',
style: 'color: #f00'
}"></div>
```
### `.wrap`
```js
const TestDirective = require(...);
Vue.directive('wrapped', TestDirective.wrap(directive, options));
```
#### Options
- `disabled` (`boolean`) - disable the directive. Set via `directiveValue.test.disabled` or `options.disabled` (ordered by precedence)
- `hooks` (`object`) - hooks to handle by the directive. Set via `directiveValue.test.hooks` or modifiers starting with `test:` or `options.hooks` (ordered by precedence)
- `label` (`string`) - directive label shown in console. Set via `directiveValue.test.label` or argument (after `test:` or `:test:`) or `options.label` (ordered by precedence)
- `style` (`string`) - styles of console output. Set via `directiveValue.test.style` or `options.style` (ordered by precedence)
##### Notes
- binding passed to wrapped directive will be filtered from test directive options
- if non-object value should be passed to wrapped directive and it's necessary to use `directiveValue.test.*` options, the value for wrapped directive may be set via `directiveValue.test.value`
#### Examples
```vue
<div v-wrapped></div>
```
```vue
<div v-wrapped="..."></div>
```
```vue
<div v-wrapped:arg:test:label></div>
```
```vue
<div v-wrapped.test:bind.test:unbind></div>
```
```vue
<div v-wrapped:test:label.test:bind.test:unbind></div>
```
```vue
<div v-wrapped="{
...,
test: {
disabled: true,
hooks: {bind: true},
label: 'label',
style: 'color: #f00'
}
}"></div>
```
```vue
<div v-wrapped="{
test: {
disabled: true,
hooks: {bind: true},
label: 'label',
style: 'color: #f00',
value: ...
}
}"></div>
```
{
"name": "@gviagroup/vue-test-directive",
"version": "1.0.0",
"description": "A Vue directive to help test code and other directives",
"license": "MIT",
"main": "src/index.js",
"scripts": {
"prestart": "yarn",
"start": "cd test && gulp && concurrently \"gulp watch\" \"lite-server\""
},
"devDependencies": {
"browserify": "^14.4.0",
"concurrently": "^3.4.0",
"lite-server": "^2.3.0",
"gulp-streamify": "^1.0.2",
"vinyl-source-stream": "^1.1.0",
"gulp": "^3.9.1",
"gulp-cssnano": "^2.1.2",
"gulp-htmlmin": "^3.0.0",
"gulp-inject-string": "^1.1.0",
"gulp-less": "^3.3.0",
"gulp-pug": "^3.3.0",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^2.1.0",
"gulp-util": "^3.0.8",
"vue": "^2.5.22",
"vueify": "^9.4.1",
"envify": "^4.1.0"
},
"peerDependencies": {
"vue": ">=2"
}
}
'use strict';
module.exports = {
directive: function (options) {
return {
bind: fd('bind', options),
inserted: fd('inserted', options),
update: fd('update', options),
componentUpdated: fd('componentUpdated', options),
unbind: fd('unbind', options)
};
},
wrap: function (directive, options) {
if (!directive) return;
options = options || {};
var originalDef;
if (typeof directive === 'function') {
originalDef = {
bind: directive,
update: directive
};
options.hooks = options.hooks || {bind: true, update: true};
} else if (typeof directive === 'object') {
originalDef = directive;
options.hooks = options.hooks || Object.keys(directive).reduce(function (hooks, hookName) {
hooks[hookName] = true;
return hooks;
}, {});
}
return {
bind: _wrap('bind'),
inserted: _wrap('inserted'),
update: _wrap('update'),
componentUpdated: _wrap('componentUpdated'),
unbind: _wrap('unbind')
};
function _wrap(hook) {
var d = (typeof directive === 'object') ? directive[hook] : directive;
return function (el, binding, vnode, oldVnode) {
var filteredBinding = getFilteredBinding(binding, originalDef);
fw(hook, options)(el, filteredBinding, vnode, oldVnode, binding);
if (originalDef[hook]) d(el, filteredBinding, vnode, oldVnode);
}
}
}
};
function fd(hook, options) {
options = options || {};
return function (el, binding, vnode, oldVnode) {
if ((binding.value && binding.value.disabled) || options.disabled) return;
var hasModifiers = Object.keys(binding.modifiers).length;
var hooks = (binding.value && binding.value.hooks) || (hasModifiers && binding.modifiers) || options.hooks || {};
var label = (binding.value && binding.value.label) || binding.arg || options.label || '';
var name = binding.name;
var style = (binding.value && binding.value.style) || options.style || '';
if (Object.keys(hooks).length && !hooks[hook]) return;
log(el, binding, vnode, oldVnode, {
hook: hook,
label: label,
name: name,
style: style
});
}
}
function fw(hook, options) {
options = options || {};
return function (el, binding, vnode, oldVnode, rawBinding) {
if ((rawBinding.value && rawBinding.value.test && rawBinding.value.test.disabled) || options.disabled) return;
var testModifiers = Object.keys(rawBinding.modifiers).filter(function (modifier) {
return /^test:/.test(modifier);
});
var hasModifiers = testModifiers.length;
var modifiers = testModifiers.reduce(function (modifiers, modifier) {
modifiers[modifier.slice(5)] = rawBinding.modifiers[modifier];
return modifiers;
}, {});
var argLabel = rawBinding.arg && rawBinding.arg.split(/:?test:/)[1] || '';
var hooks = (rawBinding.value && rawBinding.value.test && rawBinding.value.test.hooks) || (hasModifiers && modifiers) || options.hooks || {};
var label = (rawBinding.value && rawBinding.value.test && rawBinding.value.test.label) || argLabel || options.label || '';
var name = rawBinding.name;
var style = (rawBinding.value && rawBinding.value.test && rawBinding.value.test.style) || options.style || '';
if (Object.keys(hooks).length && !hooks[hook]) return;
log(el, binding, vnode, oldVnode, {
hook: hook,
label: label,
name: name,
style: style
});
}
}
function getFilteredBinding(rawBinding, def) {
var binding = {
arg: !rawBinding.arg ? rawBinding.arg : rawBinding.arg.split(/:?test:/)[0],
def: def,
modifiers: getFilteredModifiers(rawBinding.modifiers),
name: rawBinding.name,
rawBinding: rawBinding,
rawName: getFilteredRawName(rawBinding.rawName),
value: rawBinding.value && rawBinding.value.test && rawBinding.value.test.value || getFilteredValue(rawBinding.value)
};
if (!binding.arg) delete binding.arg;
return binding;
function getFilteredModifiers(modifiers) {
return Object.keys(modifiers).filter(function (mod) {
return !/^test:/.test(mod);
}).reduce(function (mods, mod) {
mods[mod] = rawBinding[mod];
return mods;
}, {});
}
function getFilteredRawName(rawName) {
var modifiers = rawName.split('.');
var nameAndArg = modifiers.shift();
modifiers = modifiers.filter(function (modifier) {
return !/^test:/.test(modifier);
});
var groups = /^([A-Za-z0-9-]+)(:([A-Za-z0-9:-]*?)(:test:([A-Za-z0-9]+))?)?$/.exec(nameAndArg);
var name = groups[1];
var arg = groups[3];
return name + (arg ? (':' + arg) : '') + (modifiers.length ? ('.' + modifiers.join('.')) : '');
}
function getFilteredValue(value) {
if (!value || (typeof value !== 'object')) return value;
var copy = Object.assign({}, value);
delete copy.test;
return copy;
}
}
function log(el, binding, vnode, oldVnode, params) {
console.groupCollapsed('%c' + (params.label ? '['+params.label+'] ' : '') + 'v-' + params.name + ': ' + params.hook, params.style);
console.log(el);
console.log(binding);
console.log(vnode);
if (~['update', 'componentUpdated'].indexOf(params.hook)) console.log(oldVnode);
console.groupEnd();
}
{
"files": [
"./dist/**/*.{css,html,htm,js}"
],
"reloadDebounce": 500,
"server": {
"baseDir": "dist"
}
}
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var vueify = require('vueify');
var envify = require('envify/custom');
var gulp = require('gulp');
var nano = require('gulp-cssnano');
var htmlMin = require('gulp-htmlmin');
var inject = require('gulp-inject-string');
var less = require('gulp-less');
var pug = require('gulp-pug');
var rename = require('gulp-rename');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var failsafe = false;
function isLocal() {
return !gutil.env.env;
}
function isTesting() {
return gutil.env.env === 'testing';
}
function isStaging() {
return gutil.env.env === 'staging';
}
function isProduction() {
return gutil.env.env === 'production';
}
function failsafePipe(pipe, callback) {
return failsafe
? pipe.on('error', shallow(callback))
: pipe;
}
function shallow(callback) {
return function (error) {
callback(error);
};
}
var paths = new function() {
this.srcDir = 'src';
this.distDir = 'dist';
// Files to be copied to `distDir`
this.files = [
// this.srcDir + '/folder/**/*' // Copy whole folder with subfolders
// this.srcDir + '/file.txt' // Copy specified file
];
this.cssDir = this.srcDir + '/css';
this.cssFiles = this.cssDir + '/**/*.css';
this.htmlDir = this.srcDir;
this.html = this.htmlDir + '/**/*.html';
this.htmlFiles = this.html;
this.htmlOut = this.distDir;
this.imgDir = this.srcDir + '/img';
this.imgFiles = this.imgDir + '/**/*';
this.imgOut = this.distDir + '/img';
this.jsDir = this.srcDir + '/js';
this.js = this.jsDir + '/index.js';
this.jsFiles = [
this.jsDir + '/**/*.js',
this.srcDir + '/vue/**/*',
'../src/**/*'
];
this.jsOut = this.distDir + '/js';
this.lessDir = this.srcDir + '/less';
this.less = this.lessDir + '/index.less';
this.lessFiles = this.lessDir + '/**/*.less';
this.lessOut = this.distDir + '/css';
this.pugDir = this.srcDir + '/pug';
this.pug = [
this.pugDir + '/**/*.pug',
'!' + this.pugDir + '/includes/**/*'
];
this.pugFiles = this.pugDir + '/**/*';
this.pugOut = this.distDir;
};
// Files
gulp.task('files-copy', function () {
return gulp.src(paths.files, {
base: paths.srcDir
})
.pipe(gulp.dest(paths.distDir));
});
gulp.task('files', ['files-copy']);
// Images
gulp.task('img-copy', function () {
return gulp.src(paths.imgFiles)
.pipe(gulp.dest(paths.imgOut));
});
gulp.task('images', ['img-copy']);
// Markup
gulp.task('html-min', function (callback) {
return gulp.src(paths.html)
.pipe(isLocal() || isTesting()
? inject.replace('<!--\\s*?weinre\\s*?-->', '<script async src="http://weinre.dev.gvia.group/target/target-script-min.js"></script>')
: gutil.noop())
.pipe(isStaging()
? inject.replace('<!--\\s*?weinre\\s*?-->', '<script async src="http://weinre.dev.gvia.group/target/target-script-min.js#staging"></script>')
: gutil.noop())
.pipe(isProduction()
? inject.replace('<!--\\s*?weinre\\s*?-->', '')
: gutil.noop())
.pipe(failsafePipe(htmlMin({
collapseWhitespace: true,
conservativeCollapse: true
}), callback))
.pipe(gulp.dest(paths.htmlOut));
});
gulp.task('pug-compile', function (callback) {
return gulp.src(paths.pug)
.pipe(isLocal() || isTesting()
? inject.replace('//-?\\s*?weinre', 'script(async src="http://weinre.dev.gvia.group/target/target-script-min.js")')
: gutil.noop())
.pipe(isStaging()
? inject.replace('//-?\\s*?weinre', 'script(async src="http://weinre.dev.gvia.group/target/target-script-min.js#staging")')
: gutil.noop())
.pipe(isProduction()
? inject.replace('//-?\\s*?weinre', '')
: gutil.noop())
.pipe(failsafePipe(pug(), callback))
.pipe(gulp.dest(paths.pugOut));
});
gulp.task('markup', ['html-min', 'pug-compile']);
// Scripts
gulp.task('js-browserify', function (callback) {
return failsafePipe(
browserify(paths.js, {
debug: isLocal(),
transform: [
vueify
]
})
.transform(
{global: !isLocal()},
envify(!isLocal() ? {NODE_ENV: 'production'} : {}))
.bundle(),
callback)
.pipe(source('script.all.min.js'))
.pipe(!isLocal() ? streamify(failsafePipe(uglify(), callback)) : gutil.noop())
.pipe(gulp.dest(paths.jsOut));
});
gulp.task('scripts', ['js-browserify']);
// Styles
gulp.task('less-compile', function (callback) {
return gulp.src(paths.less)
.pipe(failsafePipe(less(), callback))
.pipe(!isLocal() ? failsafePipe(nano(), callback) : gutil.noop())
.pipe(rename('style.all.min.css'))
.pipe(gulp.dest(paths.lessOut));
});
gulp.task('styles', ['less-compile']);
// Stages
gulp.task('watch', function () {
failsafe = true;
gulp.watch(paths.files, ['files']);
gulp.watch(paths.imgFiles, ['images']);
gulp.watch([paths.htmlFiles, paths.pugFiles], ['markup']);
gulp.watch(paths.jsFiles, ['scripts']);
gulp.watch([paths.cssFiles, paths.lessFiles], ['styles']);
});
gulp.task('build', ['files', 'images', 'markup', 'scripts', 'styles']);
gulp.task('default', ['build']);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-test-directive</title>
<script defer src="/js/script.all.min.js"></script>
<link rel="stylesheet" href="/css/style.all.min.css">
</head>
<body>
<!-- weinre -->
<h1>vue-test-directive</h1>
<div id="app"></div>
</body>
</html>
'use strict';
module.exports = require('../../../src/index');
'use strict';
var Vue = require('vue/dist/vue.runtime.common');
Vue.directive('test', require('./directive').directive({style: 'color: #050'}));
var app = new Vue({
el: '#app',
render: function (h) { return h(require('../vue/index.vue')); }
});
if (process.env.NODE_ENV !== 'production') {
window.app = app;
}
<template lang="pug">
div
div(v-test:div.bind="")
h2 directive
test-component-directive(title="Root" :level="0" v-test:component="")
div(v-test-wrapped:test:div.test:bind="")
h2 wrap
test-component-wrap(title="Root" :level="0" v-test-wrapped:test:component="")
</template>
<script>
module.exports = {
components: {
'test-component-directive': require('./test-component-directive.vue'),
'test-component-wrap': require('./test-component-wrap.vue')
},
directives: {
'test-wrapped': require('../js/directive').wrap(function () {}, {
style: 'color: #005'
})
}
};
</script>
<template lang="pug">
div(:style="{paddingLeft: (level * 20) + 'px'}" v-test="{label: 'root ' + level}")
h3 {{title}}
test-component(:title="c.title" :level="level + 1" v-for="(c, index) in children" :key="index")
button(@click="addChild") Add child
</template>
<script>
module.exports = {
name: 'test-component',
props: ['title', 'level'],
data: function () {
return {
children: []
};
},
methods: {
addChild: function () {
this.children.push({title: this.children.length + 1});
}
},
mounted: function () {
setInterval(function () {
this.children.forEach(function (item) {
item.title++;
});
}.bind(this), 2000);
}
};
</script>
<template lang="pug">
div(:style="{paddingLeft: (level * 20) + 'px'}" v-test-wrapped.test:bind.test:inserted="{test: {label: 'root ' + level, value: '#ffc'}}")
h3 {{title}}
test-component(:title="c.title" :level="level + 1" v-for="(c, index) in children" :key="index")
button(@click="addChild") Add child
</template>
<script>
module.exports = {
name: 'test-component',
directives: {
'test-wrapped': require('../js/directive').wrap(function (el, binding) {
el.style.backgroundColor = binding.value;
}, {
style: 'color: #005'
})
},
props: ['title', 'level'],
data: function () {
return {
children: []
};
},
methods: {
addChild: function () {
this.children.push({title: this.children.length + 1});
}
},
mounted: function () {
setInterval(function () {
this.children.forEach(function (item) {
item.title++;
});
}.bind(this), 2000);
}
};
</script>
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment