This repository has been archived on 2023-08-30. You can view files and clone it, but cannot push or open issues/pull-requests.
bytedo
/
wcui
Archived
1
0
Fork 0

修改组件颜色配置方式;修复clickoutside的逻辑判断

old
yutent 2023-02-27 17:53:27 +08:00
parent d3a3e48feb
commit 87fa2397f0
9 changed files with 924 additions and 1099 deletions

1
.gitignore vendored
View File

@ -2,6 +2,7 @@
*.min.css *.min.css
.httpserver .httpserver
index.html index.html
test.js
.vscode .vscode
node_modules/ node_modules/
dist/ dist/

View File

@ -3,7 +3,7 @@
import 'es.shim' import 'es.shim'
import fs from 'iofs' import fs from 'iofs'
import { parse, resolve } from 'path' import { parse, resolve } from 'path'
import scss from 'sass' import scss from '@bytedo/sass'
import chalk from 'chalk' import chalk from 'chalk'
import { transform } from 'esbuild' import { transform } from 'esbuild'
import chokidar from 'chokidar' import chokidar from 'chokidar'
@ -37,7 +37,10 @@ function parseName(str) {
function fixImport(str) { function fixImport(str) {
return str return str
.replace(/import '([\w-/_.]*)'/g, 'import "$1.js"') .replace(/import '([\w-/_.]*)'/g, 'import "$1.js"')
.replace(/import ([\w\s,{}$]*) from '([a-z0-9\/\.\-_]*)'/g, 'import $1 from "$2.js"') .replace(
/import ([\w\s,{}$]*) from '([a-z0-9\/\.\-_]*)'/g,
'import $1 from "$2.js"'
)
} }
function compileJs(entry, output) { function compileJs(entry, output) {
@ -47,7 +50,11 @@ function compileJs(entry, output) {
buf = fixImport(buf) buf = fixImport(buf)
transform(buf, ESBUILD_OPTIONS).then(res => { transform(buf, ESBUILD_OPTIONS).then(res => {
log('编译JS: %s, 耗时 %s ms', chalk.green(entry), chalk.yellow(Date.now() - t1)) log(
'编译JS: %s, 耗时 %s ms',
chalk.green(entry),
chalk.yellow(Date.now() - t1)
)
fs.echo(res.code, output) fs.echo(res.code, output)
}) })
} }
@ -55,7 +62,7 @@ function compileJs(entry, output) {
// 编译样式 // 编译样式
function compileScss(code = '') { function compileScss(code = '') {
try { try {
return scss.renderSync({ data: BASE_SCSS + code }).css return scss.compileString(BASE_SCSS + code).css
} catch (err) { } catch (err) {
log(err) log(err)
} }
@ -105,7 +112,10 @@ function mkWCFile({ style, html, js }) {
) )
.replace('mounted()', 'connectedCallback()') .replace('mounted()', 'connectedCallback()')
.replace('unmounted()', 'disconnectedCallback()') .replace('unmounted()', 'disconnectedCallback()')
.replace('watch() {', 'attributeChangedCallback(name, old, val) {\nif (old === val) {return}') .replace(
'watch() {',
'attributeChangedCallback(name, old, val) {\nif (old === val) {return}'
)
.replace('adopted()', 'adoptedCallback()') .replace('adopted()', 'adoptedCallback()')
js += `if(!customElements.get('wc-${parseName(name)}')){ js += `if(!customElements.get('wc-${parseName(name)}')){
@ -138,7 +148,11 @@ const compileWC = (entry, output) => {
js = js ? js[1] : '' js = js ? js[1] : ''
mkWCFile({ style, html, js }).then(txt => { mkWCFile({ style, html, js }).then(txt => {
log('编译WC: %s, 耗时 %s ms', chalk.green(entry), chalk.yellow(Date.now() - t1)) log(
'编译WC: %s, 耗时 %s ms',
chalk.green(entry),
chalk.yellow(Date.now() - t1)
)
fs.echo(txt, output) fs.echo(txt, output)
}) })
} }

View File

@ -3,7 +3,7 @@
import 'es.shim' import 'es.shim'
import fs from 'iofs' import fs from 'iofs'
import { parse, resolve } from 'path' import { parse, resolve } from 'path'
import scss from 'sass' import scss from '@bytedo/sass'
import chalk from 'chalk' import chalk from 'chalk'
import { transform } from 'esbuild' import { transform } from 'esbuild'
@ -37,7 +37,10 @@ function parseName(str) {
function fixImport(str) { function fixImport(str) {
return str return str
.replace(/import '([\w-/_.]*)'/g, 'import "$1.js"') .replace(/import '([\w-/_.]*)'/g, 'import "$1.js"')
.replace(/import ([\w\s,{}$]*) from '([a-z0-9\/\.\-_]*)'/g, 'import $1 from "$2.js"') .replace(
/import ([\w\s,{}$]*) from '([a-z0-9\/\.\-_]*)'/g,
'import $1 from "$2.js"'
)
} }
function compileJs(entry, output) { function compileJs(entry, output) {
@ -47,7 +50,11 @@ function compileJs(entry, output) {
buf = fixImport(buf) buf = fixImport(buf)
transform(buf, ESBUILD_OPTIONS).then(res => { transform(buf, ESBUILD_OPTIONS).then(res => {
log('编译JS: %s, 耗时 %s ms', chalk.green(entry), chalk.yellow(Date.now() - t1)) log(
'编译JS: %s, 耗时 %s ms',
chalk.green(entry),
chalk.yellow(Date.now() - t1)
)
fs.echo(res.code, output) fs.echo(res.code, output)
}) })
} }
@ -56,9 +63,8 @@ function compileJs(entry, output) {
function compileScss(code = '') { function compileScss(code = '') {
try { try {
return ( return (
scss.renderSync({ scss.compileString(BASE_SCSS + code, {
data: BASE_SCSS + code, style: 'compressed'
outputStyle: 'compressed'
}).css + '' }).css + ''
).trim() ).trim()
} catch (err) { } catch (err) {
@ -112,7 +118,10 @@ function mkWCFile({ style, html, js }) {
) )
.replace('mounted()', 'connectedCallback()') .replace('mounted()', 'connectedCallback()')
.replace('unmounted()', 'disconnectedCallback()') .replace('unmounted()', 'disconnectedCallback()')
.replace('watch() {', 'attributeChangedCallback(name, old, val) {\nif (old === val) {return}') .replace(
'watch() {',
'attributeChangedCallback(name, old, val) {\nif (old === val) {return}'
)
.replace('adopted()', 'adoptedCallback()') .replace('adopted()', 'adoptedCallback()')
js += `if(!customElements.get('wc-${parseName(name)}')){ js += `if(!customElements.get('wc-${parseName(name)}')){
@ -145,7 +154,11 @@ const compileWC = (entry, output) => {
js = js ? js[1] : '' js = js ? js[1] : ''
mkWCFile({ style, html, js }).then(txt => { mkWCFile({ style, html, js }).then(txt => {
log('编译WC: %s, 耗时 %s ms', chalk.green(entry), chalk.yellow(Date.now() - t1)) log(
'编译WC: %s, 耗时 %s ms',
chalk.green(entry),
chalk.yellow(Date.now() - t1)
)
fs.echo(txt, output) fs.echo(txt, output)
}) })
} }

View File

@ -25,7 +25,7 @@
"chokidar": "^3.5.2", "chokidar": "^3.5.2",
"es.shim": "^2.0.2", "es.shim": "^2.0.2",
"iofs": "^1.5.2", "iofs": "^1.5.2",
"sass": "^1.43.4", "@bytedo/sass": "^1.58.3",
"esbuild": "^0.13.15" "esbuild": "^0.13.15"
} }
} }

View File

@ -5,266 +5,6 @@
</button> </button>
</template> </template>
<style lang="scss">
:host {
overflow: hidden;
display: inline-flex;
min-width: 128px;
height: 36px;
border-radius: 3px;
user-select: none;
-moz-user-select: none;
color: var(--color-dark-1);
font-size: 14px;
cursor: pointer;
transition: box-shadow 0.15s linear;
button {
display: flex;
justify-content: space-evenly;
align-items: center;
width: 100%;
height: inherit;
padding: var(--padding, 0 14px);
line-height: 1;
border: 1px solid var(--color-grey-2);
border-radius: inherit;
white-space: nowrap;
background: #fff;
font-size: inherit;
font-family: inherit;
outline: none;
color: inherit;
cursor: inherit;
transition: background 0.15s linear;
&::-moz-focus-inner {
border: none;
}
}
.icon {
--size: var(--icon-size, 18px);
}
}
:host([size='large']) {
min-width: 212px;
height: 52px;
font-size: 18px;
button {
padding: 0 24px;
}
.icon {
--size: 26px;
}
}
:host([size='large'][circle]) {
min-width: 52px;
width: 52px;
height: 52px;
button {
padding: 0;
}
}
:host([size='medium']) {
min-width: 160px;
height: 44px;
button {
padding: 0 18px;
}
}
:host([size='medium'][circle]) {
min-width: 44px;
width: 44px;
}
:host([size='small']) {
min-width: 96px;
height: 32px;
}
:host([size='small'][circle]) {
min-width: 32px;
width: 32px;
}
:host([size='mini']) {
min-width: 72px;
height: 26px;
font-size: 12px;
button {
padding: 0 6px;
}
.icon {
--size: 14px;
}
}
:host([size='mini'][circle]) {
min-width: 26px;
width: 26px;
}
:host([round]) {
border-radius: 26px;
}
:host([circle]) {
min-width: 36px;
width: 36px;
border-radius: 50%;
button {
padding: 0;
}
.icon {
margin-right: 0;
}
slot {
display: none;
}
}
:host([type]) {
color: #fff;
button {
border: 0;
}
}
:host(:not([disabled]):not([loading])) button {
&:hover {
border-color: var(--color-grey-1);
}
&:active {
border-color: var(--color-grey-3);
}
}
:host(:focus-within) {
box-shadow: 0 0 0 2px var(--color-plain-a);
}
// -------------
:host([type='danger']) button {
background: var(--color-red-2);
}
:host([type='danger']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-red-1);
}
&:active {
background: var(--color-red-3);
}
}
:host([type='danger']:focus-within) {
box-shadow: 0 0 0 2px var(--color-red-a);
}
// -------------
:host([type='info']) button {
background: var(--color-blue-2);
}
:host([type='info']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-blue-1);
}
&:active {
background: var(--color-blue-3);
}
}
:host([type='info']:focus-within) {
box-shadow: 0 0 0 2px var(--color-blue-a);
}
// --------
:host([type='success']) button {
background: var(--color-green-2);
}
:host([type='success']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-green-1);
}
&:active {
background: var(--color-green-3);
}
}
:host([type='success']:focus-within) {
box-shadow: 0 0 0 2px var(--color-green-a);
}
// ---------
:host([type='primary']) button {
background: var(--color-teal-2);
}
:host([type='primary']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-teal-1);
}
&:active {
background: var(--color-teal-3);
}
}
:host([type='primary']:focus-within) {
box-shadow: 0 0 0 2px var(--color-teal-a);
}
// ----------
:host([type='warning']) button {
background: var(--color-orange-2);
}
:host([type='warning']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-orange-1);
}
&:active {
background: var(--color-orange-3);
}
}
:host([type='warning']:focus-within) {
box-shadow: 0 0 0 2px var(--color-orange-a);
}
// -------
:host([type='inverse']) button {
background: var(--color-dark-2);
}
:host([type='inverse']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-dark-1);
}
&:active {
background: var(--color-dark-3);
}
}
:host([type='inverse']:focus-within) {
box-shadow: 0 0 0 2px var(--color-dark-a);
}
// -------
:host([type='help']) button {
background: var(--color-grey-2);
}
:host([type='help']:not([disabled]):not([loading])) button {
&:hover {
background: var(--color-grey-1);
}
&:active {
background: var(--color-grey-3);
}
}
:host([type='help']:focus-within) {
box-shadow: 0 0 0 2px var(--color-grey-a);
}
:host([loading]),
:host([disabled]) {
cursor: not-allowed;
opacity: 0.6;
}
</style>
<script> <script>
import '../icon/index' import '../icon/index'
import $ from '../utils' import $ from '../utils'
@ -396,3 +136,179 @@ export default class Button {
} }
} }
</script> </script>
<style lang="scss">
:host {
overflow: hidden;
display: inline-flex;
min-width: 128px;
height: 36px;
border-radius: 3px;
user-select: none;
-moz-user-select: none;
color: var(--color-dark-1);
font-size: 14px;
cursor: pointer;
transition: box-shadow 0.15s linear;
button {
display: flex;
justify-content: space-evenly;
align-items: center;
width: 100%;
height: inherit;
padding: var(--padding, 0 14px);
line-height: 1;
border: 1px solid var(--color-grey-2);
border-radius: inherit;
white-space: nowrap;
background: #fff;
font-size: inherit;
font-family: inherit;
outline: none;
color: inherit;
cursor: inherit;
transition: background 0.15s linear;
&::-moz-focus-inner {
border: none;
}
}
.icon {
--size: var(--icon-size, 18px);
}
}
:host([size='large']) {
min-width: 212px;
height: 52px;
font-size: 18px;
button {
padding: 0 24px;
}
.icon {
--size: 26px;
}
}
:host([size='large'][circle]) {
min-width: 52px;
width: 52px;
height: 52px;
button {
padding: 0;
}
}
:host([size='medium']) {
min-width: 160px;
height: 44px;
button {
padding: 0 18px;
}
}
:host([size='medium'][circle]) {
min-width: 44px;
width: 44px;
}
:host([size='small']) {
min-width: 96px;
height: 32px;
}
:host([size='small'][circle]) {
min-width: 32px;
width: 32px;
}
:host([size='mini']) {
min-width: 72px;
height: 26px;
font-size: 12px;
button {
padding: 0 6px;
}
.icon {
--size: 14px;
}
}
:host([size='mini'][circle]) {
min-width: 26px;
width: 26px;
}
:host([round]) {
border-radius: 26px;
}
:host([circle]) {
min-width: 36px;
width: 36px;
border-radius: 50%;
button {
padding: 0;
}
.icon {
margin-right: 0;
}
slot {
display: none;
}
}
:host(:focus-within) {
box-shadow: 0 0 0 2px var(--color-plain-a);
}
$colors: 'teal', 'blue', 'green', 'orange', 'red', 'dark', 'grey';
@each $c in $colors {
:host([#{$c}]) {
button {
color: var(--color-#{$c}-2);
border: 1px solid var(--color-#{$c}-2);
&:hover {
color: var(--color-#{$c}-1);
border-color: var(--color-#{$c}-1);
}
&:active {
color: var(--color-#{$c}-3);
}
&:disabled {
color: var(--color-#{$c}-2);
}
}
&:host([solid]) button {
border: 0;
color: #fff;
background: var(--color-#{$c}-2);
&:hover {
background: var(--color-#{$c}-1);
}
&:active {
background: var(--color-#{$c}-3);
}
&:disabled {
background: var(--color-#{$c}-2);
}
}
&:host(:focus-within) {
box-shadow: 0 0 0 2px var(--color-#{$c}-a);
}
}
}
:host([loading]),
:host([disabled]) {
cursor: not-allowed;
opacity: 0.6;
}
</style>

View File

@ -13,6 +13,322 @@
</div> </div>
</template> </template>
<script>
import '../scroll/index'
import '../icon/index'
import $ from '../utils'
export default class Input {
props = {
value: '',
placeholder: '',
maxlength: 0,
minlength: 0,
clearable: false,
autofocus: false,
readonly: false,
disabled: false,
lazy: 0 // 输入建议并发拦截时间, 单位毫秒
}
state = {
list: [], // 补全列表
mvidx: null //下拉列表光标的索引ID
}
__init__() {
/* render */
this.__OUTER__ = this.root.children[1]
this.__PREPEND__ = this.__OUTER__.children[0]
this.__INPUT__ = this.__OUTER__.children[1]
this.__CLOSE__ = this.__OUTER__.children[2]
this.__APPEND__ = this.__OUTER__.children[3]
this.__LIST__ = this.__OUTER__.children[4]
}
get readOnly() {
return this.props.readonly
}
set readOnly(val) {
var type = typeof val
if (val === this.props.readonly) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.readonly = true
this.setAttribute('readonly', '')
this.__INPUT__.setAttribute('readonly', '')
} else {
this.props.readonly = false
this.removeAttribute('readonly')
this.__INPUT__.removeAttribute('readonly')
}
}
get disabled() {
return this.props.disabled
}
set disabled(val) {
var type = typeof val
if (val === this.props.disabled) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.disabled = true
this.setAttribute('disabled', '')
this.__INPUT__.setAttribute('disabled', '')
} else {
this.props.disabled = false
this.removeAttribute('disabled')
this.__INPUT__.removeAttribute('disabled')
}
}
get value() {
return this.__INPUT__.value
}
set value(val) {
this.__INPUT__.value = val
}
// 移动光标选择下拉选项
_moveSelect(ev) {
var { list } = this.state
if (list && list.length) {
ev.preventDefault()
var step = ev.keyCode === 38 ? -1 : 1
var items = Array.from(
this.__LIST__.firstElementChild.firstElementChild.children
)
if (this.state.mvidx === null) {
this.state.mvidx = 0
} else {
this.state.mvidx += step
}
if (this.state.mvidx < 0) {
this.state.mvidx = 0
} else if (this.state.mvidx > items.length - 1) {
this.state.mvidx = items.length - 1
}
items.forEach((it, i) => {
if (i === this.state.mvidx) {
this.__LIST__.firstElementChild.scrollTop = it.offsetTop - 150
it.setAttribute('focus', '')
} else {
it.removeAttribute('focus')
}
})
}
}
// 触发列表选择
_fetchSelect(idx, ev) {
var item = this.state.list[idx]
this.value = item.value
$.fire(this, 'select')
this._handleInput(ev)
this.__LIST__.classList.remove('show')
this.state.mvidx = null
}
mounted() {
var prepend = this.__PREPEND__.assignedNodes()
var append = this.__APPEND__.assignedNodes()
this.stamp = 0
// 相同插槽, 只允许1个
while (prepend.length > 1) {
this.removeChild(prepend.pop())
}
while (append.length > 1) {
this.removeChild(append.pop())
}
if (prepend.length) {
this.__OUTER__.setAttribute('prepend', '')
}
if (append.length) {
this.__OUTER__.setAttribute('append', '')
}
// 键盘事件
this._handleSubmit = $.catch(this.__INPUT__, 'keydown', ev => {
let { minlength, lazy } = this.props
let val = this.value
if (this.disabled || this.readOnly) {
return
}
// up: 38, down: 40
if (ev.keyCode === 38 || ev.keyCode === 40) {
return this._moveSelect(ev)
}
// 回车触发submit事件
if (ev.keyCode === 13) {
ev.preventDefault()
let now = Date.now()
// 如果是输入建议存在,则第1次回车的时候, 不触发提交
if (this.state.mvidx !== null) {
return this._fetchSelect(this.state.mvidx, ev)
}
// 并发拦截 intercept
if (lazy && now - this.stamp < lazy) {
// $.fire(this, 'intercept')
return
}
// 长度不够,拦截submit
if (minlength && minlength > 0) {
if (val.length < minlength) {
return
}
}
this.stamp = now
$.fire(this, 'submit')
}
})
// 输入状态事件
this._handleInput = $.bind(this.__INPUT__, 'input', ev => {
let now = Date.now()
let { lazy } = this.props
// 并发拦截
if (lazy && now - this.stamp < lazy) {
return
}
this.stamp = now
this.__CLOSE__.classList.toggle('show', this.value.length > 0)
$.fire(this, 'fetch-suggest', {
value: this.value,
send: list => {
this.state.list = list
this._parseSuggestion()
}
})
})
this._handleChange = $.bind(this.__INPUT__, 'change', ev => {
this.__CLOSE__.classList.toggle('show', this.value.length > 0)
$.fire(this, 'change')
})
// 渲染建议列表
this._parseSuggestion = $.bind(this.__INPUT__, 'click', ev => {
var { list } = this.state
let { x, y, width, height } = this.getBoundingClientRect()
if (list && list.length) {
var html = list
.map((it, i) => `<li data-idx="${i}">${it.value}</li>`)
.join('')
this.__LIST__.firstElementChild.firstElementChild.innerHTML = html
this.__LIST__.classList.toggle('show', true)
this.__LIST__.style.cssText = `left:${x}px;top:${
y + height + 5
}px;width:${width}px;`
} else {
this.__LIST__.classList.toggle('show', false)
}
})
this._inactiveFn = $.outside(this, ev => {
this.__LIST__.classList.remove('show')
})
// 选择建议
this._handleSelect = $.bind(this.__LIST__, 'click', ev => {
if (ev.target.tagName === 'LI') {
this._fetchSelect(ev.target.dataset.idx, ev)
$.fire(this, 'input')
$.fire(this, 'change')
}
})
this._clearFn = $.bind(this.__CLOSE__, 'click', ev => {
this.value = ''
this.__CLOSE__.classList.toggle('show', false)
$.fire(this, 'input')
$.fire(this, 'change')
})
}
unmounted() {
$.unbind(this.__INPUT__, 'keydown', this._handleSubmit)
$.unbind(this.__INPUT__, 'input', this._handleInput)
$.unbind(this.__INPUT__, 'change', this._handleChange)
$.unbind(this.__INPUT__, 'click', this._parseSuggestion)
$.unbind(this.__LIST__, 'click', this._handleSelect)
$.unbind(this.__CLOSE__, 'click', this._clearFn)
$.clearOutside(this._inactiveFn)
}
watch() {
switch (name) {
case 'autofocus':
this.__INPUT__.setAttribute('autofocus', '')
// 辣鸡火狐, 要触发一下focus, 才能聚焦
setTimeout(_ => {
this.__INPUT__.focus()
}, 10)
break
case 'placeholder':
this.__INPUT__.setAttribute('placeholder', val)
break
case 'value':
this.value = val || ''
break
case 'maxlength':
if (val === null) {
this.__INPUT__.removeAttribute(name)
} else {
let n = +val
if (n > 0) {
this.__INPUT__.setAttribute(name, n)
} else {
this.removeAttribute(name)
}
}
break
case 'lazy':
this.props.lazy = val >> 0
break
case 'clearable':
this.props.lazy = val !== null
break
case 'readonly':
case 'disabled':
var k = name
if (k === 'readonly') {
k = 'readOnly'
}
this[k] = val !== null
break
}
}
}
</script>
<style lang="scss"> <style lang="scss">
ul, ul,
li { li {
@ -104,18 +420,16 @@ li {
&:hover { &:hover {
background: var(--color-plain-1); background: var(--color-plain-1);
} }
}
}
:host([clearable]) { &.show {
.label .close {
display: block; display: block;
} }
}
} }
.suggestion { .suggestion {
display: none;
overflow: hidden; overflow: hidden;
display: none;
position: fixed; position: fixed;
z-index: 10240; z-index: 10240;
left: 0; left: 0;
@ -246,58 +560,21 @@ li {
} }
/* ----- 类型(颜色) ----- */ /* ----- 类型(颜色) ----- */
$colors: 'teal', 'blue', 'green', 'orange', 'red', 'dark', 'grey';
:host(:focus-within) { :host(:focus-within) {
box-shadow: 0 0 0 2px var(--color-plain-a); box-shadow: 0 0 0 2px var(--color-plain-a);
} }
:host([type='primary']:focus-within) { @each $c in $colors {
box-shadow: 0 0 0 2px var(--color-teal-a); :host([#{$c}]:focus-within) {
} box-shadow: 0 0 0 2px var(--color-#{$c}-a);
:host([type='info']:focus-within) { }
box-shadow: 0 0 0 2px var(--color-blue-a);
}
:host([type='success']:focus-within) {
box-shadow: 0 0 0 2px var(--color-green-a);
}
:host([type='danger']:focus-within) {
box-shadow: 0 0 0 2px var(--color-red-a);
}
:host([type='warning']:focus-within) {
box-shadow: 0 0 0 2px var(--color-orange-a);
}
:host([type='primary']) .label { :host([#{$c}]) .label {
border-color: var(--color-teal-2); border-color: var(--color-#{$c}-2);
.prepend, .prepend,
.append { .append {
border-color: var(--color-teal-a); border-color: var(--color-#{$c}-a);
} }
}
:host([type='info']) .label {
border-color: var(--color-blue-2);
.prepend,
.append {
border-color: var(--color-blue-a);
}
}
:host([type='success']) .label {
border-color: var(--color-green-2);
.prepend,
.append {
border-color: var(--color-green-a);
}
}
:host([type='danger']) .label {
border-color: var(--color-red-2);
.prepend,
.append {
border-color: var(--color-red-a);
}
}
:host([type='warning']) .label {
border-color: var(--color-orange-2);
.prepend,
.append {
border-color: var(--color-orange-a);
} }
} }
@ -333,319 +610,3 @@ li {
} }
} }
</style> </style>
<script>
import '../scroll/index'
import '../icon/index'
import $ from '../utils'
export default class Input {
props = {
value: '',
placeholder: '',
maxlength: 0,
minlength: 0,
clearable: false,
autofocus: false,
readonly: false,
disabled: false,
lazy: 0 // 输入建议并发拦截时间, 单位毫秒
}
state = {
list: [], // 补全列表
mvidx: null //下拉列表光标的索引ID
}
__init__() {
/* render */
this.__OUTER__ = this.root.children[1]
this.__PREPEND__ = this.__OUTER__.children[0]
this.__INPUT__ = this.__OUTER__.children[1]
this.__CLOSE__ = this.__OUTER__.children[2]
this.__APPEND__ = this.__OUTER__.children[3]
this.__LIST__ = this.__OUTER__.children[4]
}
get readOnly() {
return this.props.readonly
}
set readOnly(val) {
var type = typeof val
if (val === this.props.readonly) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.readonly = true
this.setAttribute('readonly', '')
this.__INPUT__.setAttribute('readonly', '')
} else {
this.props.readonly = false
this.removeAttribute('readonly')
this.__INPUT__.removeAttribute('readonly')
}
}
get disabled() {
return this.props.disabled
}
set disabled(val) {
var type = typeof val
if (val === this.props.disabled) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.disabled = true
this.setAttribute('disabled', '')
this.__INPUT__.setAttribute('disabled', '')
} else {
this.props.disabled = false
this.removeAttribute('disabled')
this.__INPUT__.removeAttribute('disabled')
}
}
get value() {
return this.__INPUT__.value
}
set value(val) {
this.__INPUT__.value = val
}
// 移动光标选择下拉选项
_moveSelect(ev) {
var { list } = this.state
if (list && list.length) {
ev.preventDefault()
var step = ev.keyCode === 38 ? -1 : 1
var items = Array.from(
this.__LIST__.firstElementChild.firstElementChild.children
)
if (this.state.mvidx === null) {
this.state.mvidx = 0
} else {
this.state.mvidx += step
}
if (this.state.mvidx < 0) {
this.state.mvidx = 0
} else if (this.state.mvidx > items.length - 1) {
this.state.mvidx = items.length - 1
}
items.forEach((it, i) => {
if (i === this.state.mvidx) {
this.__LIST__.firstElementChild.scrollTop = it.offsetTop - 150
it.setAttribute('focus', '')
} else {
it.removeAttribute('focus')
}
})
}
}
// 触发列表选择
_fetchSelect(idx, ev) {
var item = this.state.list[idx]
this.value = item.value
this.dispatchEvent(
new CustomEvent('select', {
detail: item
})
)
this._handleInput(ev)
this.__LIST__.classList.remove('show')
this.state.mvidx = null
}
mounted() {
var prepend = this.__PREPEND__.assignedNodes()
var append = this.__APPEND__.assignedNodes()
this.stamp = 0
// 相同插槽, 只允许1个
while (prepend.length > 1) {
this.removeChild(prepend.pop())
}
while (append.length > 1) {
this.removeChild(append.pop())
}
if (prepend.length) {
this.__OUTER__.setAttribute('prepend', '')
}
if (append.length) {
this.__OUTER__.setAttribute('append', '')
}
// 键盘事件
this._handleSubmit = $.catch(this.__INPUT__, 'keydown', ev => {
let { minlength, lazy } = this.props
let val = this.value
if (this.disabled || this.readOnly) {
return
}
// up: 38, down: 40
if (ev.keyCode === 38 || ev.keyCode === 40) {
return this._moveSelect(ev)
}
// 回车触发submit事件
if (ev.keyCode === 13) {
ev.preventDefault()
let now = Date.now()
// 如果是输入建议存在,则第1次回车的时候, 不触发提交
if (this.state.mvidx !== null) {
return this._fetchSelect(this.state.mvidx, ev)
}
// 并发拦截 intercept
if (lazy && now - this.stamp < lazy) {
// this.dispatchEvent(new CustomEvent('intercept'))
return
}
// 长度不够,拦截submit
if (minlength && minlength > 0) {
if (val.length < minlength) {
return
}
}
this.stamp = now
this.dispatchEvent(new CustomEvent('submit', { detail: this.value }))
}
})
// 输入状态事件
this._handleInput = $.bind(this.__INPUT__, 'input', ev => {
let now = Date.now()
let { lazy } = this.props
// 并发拦截
if (lazy && now - this.stamp < lazy) {
return
}
this.stamp = now
this.dispatchEvent(
new CustomEvent('fetch-suggest', {
detail: {
value: this.value,
send: list => {
this.state.list = list
this._parseSuggestion()
}
}
})
)
})
this._handleChange = $.bind(this.__INPUT__, 'change', ev => {
this.dispatchEvent(ev)
})
// 渲染建议列表
this._parseSuggestion = $.bind(this.__INPUT__, 'click', ev => {
var { list } = this.state
let { x, y, width, height } = this.getBoundingClientRect()
if (list && list.length) {
var html = list
.map((it, i) => `<li data-idx="${i}">${it.value}</li>`)
.join('')
this.__LIST__.firstElementChild.firstElementChild.innerHTML = html
this.__LIST__.classList.toggle('show', true)
this.__LIST__.style.cssText = `left:${x}px;top:${
y + height + 5
}px;width:${width}px;`
} else {
this.__LIST__.classList.toggle('show', false)
}
})
this._inactiveFn = $.outside(this, ev => {
this.__LIST__.classList.remove('show')
})
// 选择建议
this._handleSelect = $.bind(this.__LIST__, 'click', ev => {
if (ev.target.tagName === 'LI') {
this._fetchSelect(ev.target.dataset.idx, ev)
this.dispatchEvent(new CustomEvent('input'))
this.dispatchEvent(new CustomEvent('change'))
}
})
this._clearFn = $.bind(this.__CLOSE__, 'click', ev => {
this.value = ''
this.dispatchEvent(new CustomEvent('input'))
this.dispatchEvent(new CustomEvent('change'))
})
}
unmounted() {
$.unbind(this.__INPUT__, 'keydown', this._handleSubmit)
$.unbind(this.__INPUT__, 'input', this._handleInput)
$.unbind(this.__INPUT__, 'change', this._handleChange)
$.unbind(this.__INPUT__, 'click', this._parseSuggestion)
$.unbind(this.__LIST__, 'click', this._handleSelect)
$.unbind(this.__CLOSE__, 'click', this._clearFn)
$.clearOutside(this._inactiveFn)
}
watch() {
switch (name) {
case 'autofocus':
this.__INPUT__.setAttribute('autofocus', '')
// 辣鸡火狐, 要触发一下focus, 才能聚焦
setTimeout(_ => {
this.__INPUT__.focus()
}, 10)
break
case 'placeholder':
this.__INPUT__.setAttribute('placeholder', val)
break
case 'value':
this.value = val || ''
break
case 'maxlength':
if (val === null) {
this.__INPUT__.removeAttribute(name)
} else {
let n = +val
if (n > 0) {
this.__INPUT__.setAttribute(name, n)
} else {
this.removeAttribute(name)
}
}
break
case 'lazy':
this.props.lazy = val >> 0
break
case 'readonly':
case 'disabled':
var k = name
if (k === 'readonly') {
k = 'readOnly'
}
this[k] = val !== null
break
}
}
}
</script>

View File

@ -4,189 +4,6 @@
</a> </a>
</template> </template>
<style lang="scss">
:host {
position: relative;
display: inline-flex;
border-radius: 2px;
user-select: none;
-moz-user-select: none;
font-size: inherit;
cursor: pointer;
transition: box-shadow 0.15s linear;
.link {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
padding: var(--padding, 0 2px);
line-height: 1;
font-size: inherit;
font-family: inherit;
outline: none;
color: inherit;
cursor: inherit;
text-decoration: none;
transition: color 0.15s linear;
&::-moz-focus-inner {
border: none;
}
}
&::after {
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 1px;
border-bottom: 1px dashed var(--color-grey-1);
content: '';
opacity: 0;
transition: opacity 0.15s linear;
}
}
:host(:not([disabled]):focus-within) {
&::after {
opacity: 1;
}
box-shadow: 0 0 0 2px var(--color-plain-a);
}
:host(:not([disabled]):hover),
:host([underline]) {
&::after {
opacity: 1;
}
}
:host([loading]),
:host([disabled]) {
cursor: not-allowed;
opacity: 0.6;
}
// -------------
:host([type='danger']) {
color: var(--color-red-2);
&::after {
border-color: var(--color-red-1);
}
}
:host([type='danger']:not([disabled]):hover) {
color: var(--color-red-1);
}
:host([type='danger']:not([disabled]):active) {
color: var(--color-red-3);
}
:host([type='danger']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-red-a);
}
// -------------
:host([type='info']) {
color: var(--color-blue-2);
&::after {
border-color: var(--color-blue-1);
}
}
:host([type='info']:not([disabled]):hover) {
color: var(--color-blue-1);
}
:host([type='info']:not([disabled]):active) {
color: var(--color-blue-3);
}
:host([type='info']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-blue-a);
}
// --------
:host([type='success']) {
color: var(--color-green-2);
&::after {
border-color: var(--color-green-1);
}
}
:host([type='success']:not([disabled]):hover) {
color: var(--color-green-1);
}
:host([type='success']:not([disabled]):active) {
color: var(--color-green-3);
}
:host([type='success']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-green-a);
}
// ---------
:host([type='primary']) {
color: var(--color-teal-2);
&::after {
border-color: var(--color-teal-1);
}
}
:host([type='primary']:not([disabled]):hover) {
color: var(--color-teal-1);
}
:host([type='primary']:not([disabled]):active) {
color: var(--color-teal-3);
}
:host([type='primary']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-teal-a);
}
// ----------
:host([type='warning']) {
color: var(--color-orange-2);
&::after {
border-color: var(--color-orange-1);
}
}
:host([type='warning']:not([disabled]):hover) {
color: var(--color-orange-1);
}
:host([type='warning']:not([disabled]):active) {
color: var(--color-orange-3);
}
:host([type='warning']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-orange-a);
}
// -------
:host([type='inverse']) {
color: var(--color-dark-2);
&::after {
border-color: var(--color-dark-1);
}
}
:host([type='inverse']:not([disabled]):hover) {
color: var(--color-dark-1);
}
:host([type='inverse']:not([disabled]):active) {
color: var(--color-dark-3);
}
:host([type='inverse']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-dark-a);
}
// -------
:host([type='help']) {
color: var(--color-grey-2);
&::after {
border-color: var(--color-grey-1);
}
}
:host([type='help']:not([disabled]):hover) {
color: var(--color-grey-1);
}
:host([type='help']:not([disabled]):active) {
color: var(--color-grey-3);
}
:host([type='help']:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-grey-a);
}
</style>
<script> <script>
import '../icon/index' import '../icon/index'
import $ from '../utils' import $ from '../utils'
@ -281,3 +98,88 @@ export default class Link {
} }
} }
</script> </script>
<style lang="scss">
:host {
position: relative;
display: inline-flex;
border-radius: 2px;
user-select: none;
-moz-user-select: none;
font-size: inherit;
cursor: pointer;
transition: box-shadow 0.15s linear;
.link {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
padding: var(--padding, 0 2px);
line-height: 1;
font-size: inherit;
font-family: inherit;
outline: none;
color: inherit;
cursor: inherit;
text-decoration: none;
transition: color 0.15s linear;
&::-moz-focus-inner {
border: none;
}
}
&::after {
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 1px;
border-bottom: 1px dashed var(--color-grey-1);
content: '';
opacity: 0;
transition: opacity 0.15s linear;
}
}
:host(:not([disabled]):focus-within) {
&::after {
opacity: 1;
}
box-shadow: 0 0 0 2px var(--color-plain-a);
}
:host(:not([disabled]):hover),
:host([underline]) {
&::after {
opacity: 1;
}
}
:host([loading]),
:host([disabled]) {
cursor: not-allowed;
opacity: 0.6;
}
$colors: 'teal', 'blue', 'green', 'orange', 'red', 'dark', 'grey';
@each $c in $colors {
:host([#{$c}]) {
color: var(--color-#{$c}-2);
&::after {
border-color: var(--color-#{$c}-1);
}
}
:host([#{$c}]:not([disabled]):hover) {
color: var(--color-#{$c}-1);
}
:host([#{$c}]:not([disabled]):active) {
color: var(--color-#{$c}-3);
}
:host([#{$c}]:not([disabled]):focus-within) {
box-shadow: 0 0 0 2px var(--color-#{$c}-a);
}
}
</style>

View File

@ -7,6 +7,203 @@
</div> </div>
</template> </template>
<script>
import '../icon/index'
import $ from '../utils'
export default class Passwd {
props = {
value: '',
placeholder: '',
maxlength: 0,
minlength: 0,
autofocus: false,
readonly: false,
disabled: false,
lazy: 0 // 输入建议并发拦截时间, 单位毫秒
}
__init__() {
/* render */
this.__OUTER__ = this.root.children[1]
this.__PREPEND__ = this.__OUTER__.children[0]
this.__INPUT__ = this.__OUTER__.children[1]
this.__EYE__ = this.__OUTER__.children[2]
this.__APPEND__ = this.__OUTER__.children[3]
}
get readOnly() {
return this.props.readonly
}
set readOnly(val) {
var type = typeof val
if (val === this.props.readonly) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.readonly = true
this.setAttribute('readonly', '')
this.__INPUT__.setAttribute('readonly', '')
} else {
this.props.readonly = false
this.removeAttribute('readonly')
this.__INPUT__.removeAttribute('readonly')
}
}
get disabled() {
return this.props.disabled
}
set disabled(val) {
var type = typeof val
if (val === this.props.disabled) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.disabled = true
this.setAttribute('disabled', '')
this.__INPUT__.setAttribute('disabled', '')
} else {
this.props.disabled = false
this.removeAttribute('disabled')
this.__INPUT__.removeAttribute('disabled')
}
}
get value() {
return this.__INPUT__.value
}
set value(val) {
this.__INPUT__.value = val
}
mounted() {
var prepend = this.__PREPEND__.assignedNodes()
var append = this.__APPEND__.assignedNodes()
this.stamp = 0
// 相同插槽, 只允许1个
while (prepend.length > 1) {
this.removeChild(prepend.pop())
}
while (append.length > 1) {
this.removeChild(append.pop())
}
if (prepend.length) {
this.__OUTER__.setAttribute('prepend', '')
}
if (append.length) {
this.__OUTER__.setAttribute('append', '')
}
// 键盘事件
this._handleSubmit = $.catch(this.__INPUT__, 'keydown', ev => {
let { minlength, lazy } = this.props
let val = this.value
let now = Date.now()
if (this.disabled || this.readOnly) {
return
}
// 回车触发submit事件
if (ev.keyCode === 13) {
// 并发拦截
if (lazy && now - this.stamp < lazy) {
return
}
// 长度不够,拦截submit
if (minlength && minlength > 0) {
if (val.length < minlength) {
return
}
}
this.stamp = now
$.fire(this, 'submit')
}
})
this._eyeFn = $.bind(this.__EYE__, 'click', ev => {
if (this.__INPUT__.type === 'password') {
this.__INPUT__.type = 'text'
this.__EYE__.is = 'eye-off'
} else {
this.__INPUT__.type = 'password'
this.__EYE__.is = 'eye'
}
})
this._handleChange = $.bind(this.__INPUT__, 'change', ev => {
$.fire(this, 'change')
})
}
unmounted() {
$.unbind(this.__INPUT__, 'keydown', this._handleSubmit)
$.unbind(this.__EYE__, 'click', this._eyeFn)
$.unbind(this.__INPUT__, 'change', this._handleChange)
}
watch() {
switch (name) {
case 'autofocus':
this.__INPUT__.setAttribute('autofocus', '')
// 辣鸡火狐, 要触发一下focus, 才能聚焦
setTimeout(_ => {
this.__INPUT__.focus()
}, 10)
break
case 'placeholder':
this.__INPUT__.setAttribute('placeholder', val)
break
case 'value':
this.value = val
break
case 'maxlength':
if (val === null) {
this.__INPUT__.removeAttribute(name)
} else {
let n = +val
if (n > 0) {
this.__INPUT__.setAttribute(name, n)
} else {
this.removeAttribute(name)
}
}
break
case 'lazy':
this.props.lazy = val >> 0
break
case 'readonly':
case 'disabled':
var k = name
if (k === 'readonly') {
k = 'readOnly'
}
this[k] = val !== null
break
}
}
}
</script>
<style lang="scss"> <style lang="scss">
ul, ul,
li { li {
@ -185,59 +382,22 @@ li {
padding: 0 4px 0 13px; padding: 0 4px 0 13px;
} }
/* ----- 类型(颜色) ----- */ $colors: 'teal', 'blue', 'green', 'orange', 'red', 'dark', 'grey';
:host(:focus-within) { :host(:focus-within) {
box-shadow: 0 0 0 2px var(--color-plain-a); box-shadow: 0 0 0 2px var(--color-plain-a);
} }
:host([type='primary']:focus-within) {
box-shadow: 0 0 0 2px var(--color-teal-a);
}
:host([type='info']:focus-within) {
box-shadow: 0 0 0 2px var(--color-blue-a);
}
:host([type='success']:focus-within) {
box-shadow: 0 0 0 2px var(--color-green-a);
}
:host([type='danger']:focus-within) {
box-shadow: 0 0 0 2px var(--color-red-a);
}
:host([type='warning']:focus-within) {
box-shadow: 0 0 0 2px var(--color-orange-a);
}
:host([type='primary']) .label { @each $c in $colors {
border-color: var(--color-teal-2); :host([#{$c}]:focus-within) {
.prepend, box-shadow: 0 0 0 2px var(--color-#{$c}-a);
.append {
border-color: var(--color-teal-a);
} }
} :host([#{$c}]) .label {
:host([type='info']) .label { border-color: var(--color-#{$c}-2);
border-color: var(--color-blue-2);
.prepend, .prepend,
.append { .append {
border-color: var(--color-blue-a); border-color: var(--color-#{$c}-a);
} }
}
:host([type='success']) .label {
border-color: var(--color-green-2);
.prepend,
.append {
border-color: var(--color-green-a);
}
}
:host([type='danger']) .label {
border-color: var(--color-red-2);
.prepend,
.append {
border-color: var(--color-red-a);
}
}
:host([type='warning']) .label {
border-color: var(--color-orange-2);
.prepend,
.append {
border-color: var(--color-orange-a);
} }
} }
@ -273,195 +433,3 @@ li {
} }
} }
</style> </style>
<script>
import '../icon/index'
import $ from '../utils'
export default class Passwd {
props = {
value: '',
placeholder: '',
maxlength: 0,
minlength: 0,
autofocus: false,
readonly: false,
disabled: false,
lazy: 0 // 输入建议并发拦截时间, 单位毫秒
}
__init__() {
/* render */
this.__OUTER__ = this.root.children[1]
this.__PREPEND__ = this.__OUTER__.children[0]
this.__INPUT__ = this.__OUTER__.children[1]
this.__EYE__ = this.__OUTER__.children[2]
this.__APPEND__ = this.__OUTER__.children[3]
}
get readOnly() {
return this.props.readonly
}
set readOnly(val) {
var type = typeof val
if (val === this.props.readonly) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.readonly = true
this.setAttribute('readonly', '')
this.__INPUT__.setAttribute('readonly', '')
} else {
this.props.readonly = false
this.removeAttribute('readonly')
this.__INPUT__.removeAttribute('readonly')
}
}
get disabled() {
return this.props.disabled
}
set disabled(val) {
var type = typeof val
if (val === this.props.disabled) {
return
}
if ((type === 'boolean' && val) || type !== 'boolean') {
this.props.disabled = true
this.setAttribute('disabled', '')
this.__INPUT__.setAttribute('disabled', '')
} else {
this.props.disabled = false
this.removeAttribute('disabled')
this.__INPUT__.removeAttribute('disabled')
}
}
get value() {
return this.__INPUT__.value
}
set value(val) {
this.__INPUT__.value = val
}
mounted() {
var prepend = this.__PREPEND__.assignedNodes()
var append = this.__APPEND__.assignedNodes()
this.stamp = 0
// 相同插槽, 只允许1个
while (prepend.length > 1) {
this.removeChild(prepend.pop())
}
while (append.length > 1) {
this.removeChild(append.pop())
}
if (prepend.length) {
this.__OUTER__.setAttribute('prepend', '')
}
if (append.length) {
this.__OUTER__.setAttribute('append', '')
}
// 键盘事件
this._handleSubmit = $.catch(this.__INPUT__, 'keydown', ev => {
let { minlength, lazy } = this.props
let val = this.value
let now = Date.now()
if (this.disabled || this.readOnly) {
return
}
// 回车触发submit事件
if (ev.keyCode === 13) {
// 并发拦截
if (lazy && now - this.stamp < lazy) {
return
}
// 长度不够,拦截submit
if (minlength && minlength > 0) {
if (val.length < minlength) {
return
}
}
this.stamp = now
this.dispatchEvent(new CustomEvent('submit', { detail: this.value }))
}
})
this._eyeFn = $.bind(this.__EYE__, 'click', ev => {
if (this.__INPUT__.type === 'password') {
this.__INPUT__.type = 'text'
this.__EYE__.is = 'eye-off'
} else {
this.__INPUT__.type = 'password'
this.__EYE__.is = 'eye'
}
})
}
unmounted() {
$.unbind(this.__INPUT__, 'keydown', this._handleSubmit)
$.unbind(this.__EYE__, 'click', this._eyeFn)
}
watch() {
switch (name) {
case 'autofocus':
this.__INPUT__.setAttribute('autofocus', '')
// 辣鸡火狐, 要触发一下focus, 才能聚焦
setTimeout(_ => {
this.__INPUT__.focus()
}, 10)
break
case 'placeholder':
this.__INPUT__.setAttribute('placeholder', val)
break
case 'value':
this.value = val
break
case 'maxlength':
if (val === null) {
this.__INPUT__.removeAttribute(name)
} else {
let n = +val
if (n > 0) {
this.__INPUT__.setAttribute(name, n)
} else {
this.removeAttribute(name)
}
}
break
case 'lazy':
this.props.lazy = val >> 0
break
case 'readonly':
case 'disabled':
var k = name
if (k === 'readonly') {
k = 'readOnly'
}
this[k] = val !== null
break
}
}
}
</script>

View File

@ -6,11 +6,18 @@
function noop() {} function noop() {}
export default { export default function $(selector, container) {
if (container) {
return container.querySelector(selector)
}
return document.body.querySelector(selector)
}
Object.assign($, {
/** /**
* 异步回调 * 异步回调
*/ */
nextTick: (function() { nextTick: (function () {
let queue = [] let queue = []
let node = document.createTextNode('<!-- -->') let node = document.createTextNode('<!-- -->')
let bool = false let bool = false
@ -25,7 +32,7 @@ export default {
new MutationObserver(callback).observe(node, { characterData: true }) new MutationObserver(callback).observe(node, { characterData: true })
return function(fn) { return function (fn) {
queue.push(fn) queue.push(fn)
bool = !bool bool = !bool
node.data = bool node.data = bool
@ -35,12 +42,12 @@ export default {
//取得距离页面左上角的坐标 //取得距离页面左上角的坐标
offset(node) { offset(node) {
try { try {
var rect = node.getBoundingClientRect() let rect = node.getBoundingClientRect()
if (rect.width || rect.height || node.getClientRects().length) { if (rect.width || rect.height || node.getClientRects().length) {
var doc = node.ownerDocument let doc = node.ownerDocument
var root = doc.documentElement let root = doc.documentElement
var win = doc.defaultView let win = doc.defaultView
return { return {
top: rect.top + win.pageYOffset - root.clientTop, top: rect.top + win.pageYOffset - root.clientTop,
left: rect.left + win.pageXOffset - root.clientLeft left: rect.left + win.pageXOffset - root.clientLeft
@ -79,13 +86,47 @@ export default {
/** /**
* 事件绑定 * 事件绑定
*/ */
bind(dom, type, fn = noop, phase = false) { bind(dom, type, selector, fn, phase = true) {
let events = type.split(',') let events = type.split(',')
this.each(events, function(t) { let callback
t = t.trim()
dom.addEventListener(t, fn, phase) if (typeof selector === 'function') {
phase = fn
fn = selector
selector = null
} else {
if (typeof selector !== 'string') {
selector = null
}
fn = fn || noop
}
if (selector) {
callback = function (ev) {
let agents = $(ev.currentTarget).find(selector)
let elem = ev.target
if (agents) {
while (true) {
if (elem === ev.currentTarget) {
break
}
if (agents.has(elem)) {
fn(ev)
break
} else {
elem = elem.parentNode
}
}
}
}
} else {
callback = fn
}
$.each(events, function (t) {
dom.addEventListener(t.trim(), callback, phase)
}) })
return fn return callback
}, },
/** /**
@ -93,10 +134,10 @@ export default {
*/ */
catch(dom, type, fn, phase) { catch(dom, type, fn, phase) {
function fn2(ev) { function fn2(ev) {
ev.stopPropagation && ev.stopPropagation() ev.stopPropagation()
fn && fn(ev) fn && fn(ev)
} }
return this.bind(dom, type, fn2, phase) return $.bind(dom, type, fn2, phase)
}, },
/** /**
@ -104,35 +145,44 @@ export default {
*/ */
unbind(dom, type, fn = noop, phase = false) { unbind(dom, type, fn = noop, phase = false) {
let events = type.split(',') let events = type.split(',')
this.each(events, function(t) { $.each(events, function (t) {
t = t.trim() dom.removeEventListener(t.trim(), fn, phase)
dom.removeEventListener(t, fn, phase)
}) })
}, },
// 指定节点外点击(最高不能超过body层) // 指定节点外点击(最高不能超过body层)
outside(dom, fn = noop) { outside(dom, fn = noop) {
return this.bind(document, 'mousedown', ev => { return $.bind(document, 'mousedown', ev => {
if (ev) { let path = ev.composedPath ? ev.composedPath() : ev.path
if (ev.path) { if (path) {
var path = ev.path.concat()
while (path.length > 3) { while (path.length > 3) {
if (path.shift() === dom) { if (path.shift() === dom) {
return return
} }
} }
} else { } else {
var target = ev.explicitOriginalTarget || ev.target let target = ev.explicitOriginalTarget || ev.target
if (dom === target || dom.contains(target) || (dom.root && dom.root.contains(target))) { if (
dom === target ||
dom.contains(target) ||
(dom.root && dom.root.contains(target))
) {
return return
} }
} }
}
fn(ev) fn(ev)
}) })
}, },
clearOutside(fn = noop) { clearOutside(fn = noop) {
this.unbind(document, 'mousedown', fn) $.unbind(document, 'mousedown', fn)
},
fire(el, name = 'click', data = {}) {
let ev = document.createEvent('Events')
ev.initEvent(name, true, true)
Object.assign(ev, data)
el.dispatchEvent(ev)
} }
} })