Compare commits
No commits in common. "master" and "1.0.2" have entirely different histories.
|
@ -1,9 +1,12 @@
|
|||
*.min.js
|
||||
.httpserver
|
||||
index.html
|
||||
test.js
|
||||
.vscode
|
||||
node_modules/
|
||||
dist/
|
||||
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
package-lock.json
|
||||
|
||||
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
test/
|
92
Readme.md
92
Readme.md
|
@ -1,56 +1,27 @@
|
|||
## Wkit
|
||||
> 一个简单易用、功能完善的用于开发`web components`的轻量级开发库。模板解析基于`lit-html`二次开发
|
||||
|
||||
![downloads](https://img.shields.io/npm/dt/wkit.svg)
|
||||
![version](https://img.shields.io/npm/v/wkit.svg)
|
||||
## 9号UI组件库的核心
|
||||
|
||||
### 开发文档
|
||||
[开发文档](https://git.wkit.fun/bytedo/wkit/wiki)
|
||||
|
||||
|
||||
### 我们的特色
|
||||
|
||||
- `@xxx=yyy` 事件绑定, 可以任意节点上直接使用类似`vue事件绑定`的这种写法, 就可实现事件绑定。组件被移出文档时, 事件会**自动销毁**, 无须手动销毁。
|
||||
- `@click.stop=xxx` 事件绑定支持修饰符
|
||||
- `:xxx=yyy`, 属性绑定, 类似`vue`,在属性前加上`:`, 该属性不再使用`setAttribute()`, 而是直接赋值, 可满足你需要传递复杂数据结构的需求。
|
||||
- `#animation={type}`, 开箱即用的动画配置, 内置6种动画`fade(默认), scale, bounce, micro-bounce, rotate, slide`
|
||||
- `ref=xxx`, 类似`vue`的节点标识, 可方便的在`mounted()`之后通过 `this.$refs.xxx` 来访问该节点
|
||||
- 内置特色的双向绑定方法`live()`
|
||||
- 用内置的`bind()`方法来给当前组件绑定事件时, 组件移除时事件也会自动销毁,无需手动销毁。
|
||||
- 灵活的`props`定义
|
||||
|
||||
[开发文档](https://github.com/9th-js/core/wiki)
|
||||
|
||||
### 示例
|
||||
|
||||
```js
|
||||
// alias wkit='//jscdn.ink/wkit/latest/index.js'
|
||||
import { css, html, Component } from 'wkit'
|
||||
import { css, html, Component } from '//jscdn.ink/@ninejs/core/latest/index.js'
|
||||
|
||||
class Hello extends Component {
|
||||
|
||||
static props = {
|
||||
count: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
attribute: true // 是否显式表现为html属性
|
||||
},
|
||||
foo: 0, // 简写
|
||||
bar: String // 简写
|
||||
default: 0
|
||||
}
|
||||
}
|
||||
|
||||
// 若需要支持 scss语法, 则需要使用构建工具编译。
|
||||
// 可支持数组
|
||||
static styles = css`
|
||||
button { color: #09f; }
|
||||
span { color: #f30; }
|
||||
`
|
||||
|
||||
// 支持多个
|
||||
static styles = [
|
||||
css`...`,
|
||||
css`...`
|
||||
]
|
||||
|
||||
render(){
|
||||
return html`
|
||||
<div>
|
||||
|
@ -66,12 +37,7 @@ class Hello extends Component {
|
|||
|
||||
}
|
||||
|
||||
if (!customElements.get('wc-hello')) {
|
||||
customElements.define('wc-hello', Hello)
|
||||
}
|
||||
// 和上面的写法等价
|
||||
// 如果不希望修改前缀`wc-`的话, 可以直接调用内置的reg方法注册组件即可。
|
||||
Hello.reg('hello')
|
||||
customElements.define('wc-hello', Hello)
|
||||
|
||||
|
||||
/*
|
||||
|
@ -83,9 +49,49 @@ Hello.reg('hello')
|
|||
|
||||
```
|
||||
|
||||
若需要支持 scss, 则需要使用构建工具,预处理。
|
||||
|
||||
```js
|
||||
import { css, html, Component } from '@ninejs/core'
|
||||
|
||||
@customElement('wc-hello')
|
||||
class Hello extends Component {
|
||||
|
||||
static props = {
|
||||
count: {
|
||||
type: Number,
|
||||
default: 0
|
||||
}
|
||||
}
|
||||
|
||||
// 这个scss会被解析进来
|
||||
@extendStyle('hello.scss')
|
||||
static styles
|
||||
|
||||
render(){
|
||||
return html`
|
||||
<div>
|
||||
<button @click="${this.increase}">点击我</button>
|
||||
</div>
|
||||
<div>所有点击数为: <span>${this.count}</span></div>
|
||||
`
|
||||
}
|
||||
|
||||
increase(){
|
||||
this.count++
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 这个可以省略
|
||||
// customElements.define('wc-hello', Hello)
|
||||
|
||||
|
||||
### 开源协议
|
||||
/*
|
||||
|
||||
- BSD 3-Clause License (Lit框架的html模板解析的源码)
|
||||
- MIT (除Lit代码之外的所有代码)
|
||||
<!-- 在html中,便可以直接使用 -->
|
||||
<wc-hello></wc-hello>
|
||||
|
||||
*/
|
||||
|
||||
```
|
||||
|
|
22
package.json
22
package.json
|
@ -1,29 +1,25 @@
|
|||
{
|
||||
"name": "wkit",
|
||||
"version": "1.12.0",
|
||||
"name": "@bd/core",
|
||||
"version": "1.0.2",
|
||||
"type": "module",
|
||||
"description": "A library for building fast, lightweight web components.",
|
||||
"description": "百搭UI组件库的核心",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/*"
|
||||
],
|
||||
"scripts": {
|
||||
"build:next": "esbuild src/index.js --minify --bundle --format=esm --target=esnext --outfile=dist/index.js",
|
||||
"build:es6": "esbuild src/index.js --minify --bundle --format=esm --target=es6 --outfile=dist/index.es6.js",
|
||||
"build": "npm run build:next && npm run build:es6"
|
||||
"build": "esbuild src/index.js --minify --bundle --format=esm --target=es2017 --outfile=dist/index.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.wkit.fun/bytedo/wkit.git"
|
||||
"url": "git+https://github.com/bd-js/core.git"
|
||||
},
|
||||
"keywords": [
|
||||
"wkit",
|
||||
"bd.js",
|
||||
"bdjs",
|
||||
"bd-ui",
|
||||
"wcui",
|
||||
"web-components",
|
||||
"native",
|
||||
"cross-framework",
|
||||
"html",
|
||||
"css"
|
||||
"bd-core"
|
||||
],
|
||||
"devDependencies": {
|
||||
"esbuild": "^0.17.11"
|
||||
|
|
48
src/anim.js
48
src/anim.js
|
@ -1,48 +0,0 @@
|
|||
/**
|
||||
* {}
|
||||
* @author yutent<yutent.io@gmail.com>
|
||||
* @date 2023/03/29 10:28:16
|
||||
*/
|
||||
|
||||
export function animate(duration = 200, fromto = [], out = false) {
|
||||
if (out === false && this.style.display === 'none') {
|
||||
this.style.display = ''
|
||||
}
|
||||
let res = this.animate(fromto, {
|
||||
duration,
|
||||
direction: out ? 'reverse' : 'normal',
|
||||
fill: 'forwards'
|
||||
})
|
||||
return new Promise(resolve => {
|
||||
res.addEventListener(
|
||||
'finish',
|
||||
_ => {
|
||||
if (out) {
|
||||
this.style.display = 'none'
|
||||
}
|
||||
res.cancel()
|
||||
resolve()
|
||||
},
|
||||
{ once: true }
|
||||
)
|
||||
})
|
||||
}
|
||||
export const MODES = {
|
||||
fade: [{ opacity: 0 }, { opacity: 1 }],
|
||||
scale: [{ transform: 'scale(0)' }, { transform: 'scale(1)' }],
|
||||
'micro-bounce': [
|
||||
{ opacity: 0, transform: 'scale(0.8)' },
|
||||
{ transform: 'scale(1.05)', opacity: 1 },
|
||||
{ transform: 'scale(1)' }
|
||||
],
|
||||
slide: [
|
||||
{ opacity: 0, transform: 'translateY(-50px)' },
|
||||
{ opacity: 1, transform: 'translateY(0)' }
|
||||
],
|
||||
bounce: [
|
||||
{ transform: 'scale(0)' },
|
||||
{ transform: 'scale(1.2)' },
|
||||
{ transform: 'scale(1)' }
|
||||
],
|
||||
rotate: [{ transform: 'rotate(0)' }, { transform: 'rotate(360deg)' }]
|
||||
}
|
|
@ -27,25 +27,31 @@ const boolMap = Object.create(null)
|
|||
'noShade',
|
||||
'open',
|
||||
'readOnly',
|
||||
'selected',
|
||||
'loading'
|
||||
'selected'
|
||||
].forEach(function (name) {
|
||||
boolMap[name.toLowerCase()] = name
|
||||
})
|
||||
|
||||
export { boolMap }
|
||||
|
||||
export const KEEP_ALIVE = 'keep-alive' // hyphen
|
||||
export const KEEP_ALIVE_C = 'keepAlive' // camelize
|
||||
export const WC_PART = Symbol('wc_path')
|
||||
export const NO_CHANGE = Symbol('wc-noChange')
|
||||
export const NOTHING = Symbol('wc-nothing')
|
||||
export const __finalized__ = Symbol('finalized')
|
||||
export const __render__ = Symbol('render')
|
||||
export const __init__ = Symbol('init')
|
||||
export const __props__ = Symbol('props')
|
||||
export const __changed_props__ = Symbol('changed_props')
|
||||
export const __mounted__ = Symbol('mounted')
|
||||
export const __feedback__ = Symbol('feedback')
|
||||
export const __pending__ = Symbol('pending')
|
||||
export const __prop2attr__ = Symbol('prop2attr')
|
||||
export const __attr2prop__ = Symbol('attr2prop')
|
||||
export const __clear_update__ = Symbol('clearupdate')
|
||||
export const __children__ = Symbol('children')
|
||||
export const __updated__ = Symbol('updated')
|
||||
|
||||
export const RESET_CSS_STYLE = `* {box-sizing: border-box;margin: 0;padding: 0;}::before,::after {box-sizing: border-box;}::selection {background: var(--selection-background, var(--color-plain-a));color: var(--selection-color, inherit);}`
|
||||
export const RESET_CSS_STYLE = `* {box-sizing: border-box;margin: 0;padding: 0;}::before,::after {box-sizing: border-box;}`
|
||||
|
||||
function getDefaultValue(type) {
|
||||
switch (type) {
|
||||
|
@ -79,26 +85,8 @@ function getType(v) {
|
|||
? { type: Array, default: v }
|
||||
: { type: Object, default: v }
|
||||
|
||||
case 'string':
|
||||
let type = String
|
||||
let attribute = true
|
||||
if (v.includes('!')) {
|
||||
if (v.startsWith('str!')) {
|
||||
v = v.slice(4)
|
||||
} else if (v.startsWith('num!')) {
|
||||
type = Number
|
||||
v = +v.slice(4) || 0
|
||||
} else if (v.startsWith('bool!')) {
|
||||
type = Boolean
|
||||
v = v.slice(5)
|
||||
v = v !== 'false' && v !== ''
|
||||
}
|
||||
attribute = false
|
||||
}
|
||||
return { type, default: v, attribute }
|
||||
|
||||
default:
|
||||
return { type: null, default: '' }
|
||||
return { type: String, default: v + '' }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -128,30 +116,24 @@ export function parsePropsDeclaration(options) {
|
|||
options = { type: Array }
|
||||
break
|
||||
|
||||
case String:
|
||||
options = { type: String }
|
||||
break
|
||||
|
||||
default:
|
||||
options = getType(options)
|
||||
break
|
||||
}
|
||||
options.default = options.hasOwnProperty('default')
|
||||
? options.default
|
||||
: getDefaultValue(options.type)
|
||||
options.attribute = options.hasOwnProperty('attribute')
|
||||
? options.attribute
|
||||
: true
|
||||
options.default = options.default || getDefaultValue(options.type)
|
||||
options.attribute = true
|
||||
return options
|
||||
}
|
||||
|
||||
export function fixedValue(value, options) {
|
||||
switch (options.type) {
|
||||
case Number:
|
||||
return value === null ? null : +value || 0
|
||||
return +value || 0
|
||||
break
|
||||
|
||||
case Boolean:
|
||||
return value === false ? false : value !== null
|
||||
break
|
||||
|
||||
case Object:
|
||||
if (typeof value === 'object') {
|
||||
|
@ -163,6 +145,7 @@ export function fixedValue(value, options) {
|
|||
return {}
|
||||
}
|
||||
}
|
||||
break
|
||||
|
||||
case Array:
|
||||
if (typeof value === 'object') {
|
||||
|
@ -174,11 +157,10 @@ export function fixedValue(value, options) {
|
|||
return []
|
||||
}
|
||||
}
|
||||
|
||||
case null:
|
||||
return value
|
||||
break
|
||||
|
||||
default:
|
||||
return value === null || value === void 0 ? null : value + ''
|
||||
return value + ''
|
||||
break
|
||||
}
|
||||
}
|
||||
|
|
20
src/css.js
20
src/css.js
|
@ -6,18 +6,6 @@
|
|||
|
||||
import { RESET_CSS_STYLE } from './constants.js'
|
||||
|
||||
let MyCSSStyleSheet = CSSStyleSheet
|
||||
|
||||
if (!document.adoptedStyleSheets) {
|
||||
MyCSSStyleSheet = class {
|
||||
elem = document.createElement('style')
|
||||
|
||||
replaceSync(css) {
|
||||
this.elem.textContent = css.replace(/\s+/g, ' ')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function css(strs, ...args) {
|
||||
let output = ''
|
||||
let tmp = Array.from(strs)
|
||||
|
@ -28,7 +16,7 @@ export function css(strs, ...args) {
|
|||
}
|
||||
|
||||
export function adoptStyles(root, styles = '') {
|
||||
let sheet = new MyCSSStyleSheet()
|
||||
let sheet = new CSSStyleSheet()
|
||||
if (typeof styles === 'string') {
|
||||
styles = [styles]
|
||||
} else {
|
||||
|
@ -36,9 +24,5 @@ export function adoptStyles(root, styles = '') {
|
|||
}
|
||||
styles = (RESET_CSS_STYLE + styles.join(' ')).trim()
|
||||
sheet.replaceSync(styles)
|
||||
if (root.adoptedStyleSheets) {
|
||||
root.adoptedStyleSheets = [sheet]
|
||||
} else {
|
||||
root.appendChild(sheet.elem)
|
||||
}
|
||||
root.adoptedStyleSheets.push(sheet)
|
||||
}
|
||||
|
|
924
src/html.js
924
src/html.js
File diff suppressed because it is too large
Load Diff
438
src/index.js
438
src/index.js
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* { wkit library }
|
||||
* {wcui的核心库, 基于lit-core二次开发}
|
||||
* @author yutent<yutent.io@gmail.com>
|
||||
* @date 2023/03/07 18:10:43
|
||||
*/
|
||||
|
@ -7,93 +7,25 @@ import {
|
|||
fixedValue,
|
||||
parsePropsDeclaration,
|
||||
boolMap,
|
||||
KEEP_ALIVE,
|
||||
KEEP_ALIVE_C,
|
||||
__finalized__,
|
||||
__render__,
|
||||
__init__,
|
||||
__props__,
|
||||
__changed_props__,
|
||||
__mounted__,
|
||||
__pending__
|
||||
__feedback__,
|
||||
__pending__,
|
||||
__prop2attr__,
|
||||
__attr2prop__,
|
||||
__clear_update__,
|
||||
__children__,
|
||||
__updated__
|
||||
} from './constants.js'
|
||||
import { css, adoptStyles } from './css.js'
|
||||
import { render, html, svg, raw } from './html.js'
|
||||
import { animate, MODES } from './anim.js'
|
||||
import { nextTick, fire, bind, unbind, hyphen, camelize } from './utils.js'
|
||||
|
||||
export {
|
||||
$,
|
||||
$$,
|
||||
range,
|
||||
offset,
|
||||
outsideClick,
|
||||
clearOutsideClick
|
||||
} from './utils.js'
|
||||
export { html, raw, css, svg, bind, unbind, nextTick, fire, hyphen, camelize }
|
||||
|
||||
function safely(callback, ...args) {
|
||||
try {
|
||||
callback && callback.apply(this, args)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
// 简单的类名解析
|
||||
export function classMap(data = {}) {
|
||||
let output = ''
|
||||
for (let k in data) {
|
||||
if (data[k]) {
|
||||
output += ' ' + k
|
||||
}
|
||||
}
|
||||
return output.slice(1)
|
||||
}
|
||||
// 简单的样式解析
|
||||
export function styleMap(data = {}) {
|
||||
let output = ''
|
||||
for (let k in data) {
|
||||
if (data[k] || data[k] === 0) {
|
||||
output += hyphen(k) + ':' + data[k] + ';'
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
// 三元运算符的函数封装(只为了省个参数)
|
||||
export function when(condition, trueCase = '', falseCase = '') {
|
||||
return condition ? trueCase : falseCase
|
||||
}
|
||||
|
||||
// swicth语句的封装
|
||||
export function which(target, list = [], defaultCase = '') {
|
||||
for (let [name, content] of list) {
|
||||
if (target === name) {
|
||||
return content
|
||||
}
|
||||
}
|
||||
return defaultCase
|
||||
}
|
||||
|
||||
/**
|
||||
* 双向绑定
|
||||
* @param key<String> 绑定的字段
|
||||
* @param el 当前对象, 无需传递, 由框架内部处理
|
||||
*
|
||||
*/
|
||||
export function live(key, el) {
|
||||
let callback = ev => {
|
||||
Function('o', 'v', `o.${key} = v`)(this, ev.target.value)
|
||||
this.$requestUpdate()
|
||||
}
|
||||
|
||||
if (el && !el.__live__) {
|
||||
bind(el, 'input', callback)
|
||||
this.$events.input ??= []
|
||||
this.$events.input.push({ el, listener: callback, options: false })
|
||||
el.__live__ = true
|
||||
}
|
||||
return Function('o', `return o.${key}`)(this)
|
||||
}
|
||||
import { render, html, svg } from './html.js'
|
||||
import { nextTick, fire, bind, unbind } from './utils.js'
|
||||
export { $, $$, offset, outsideClick, clearOutsideClick } from './utils.js'
|
||||
export { html, css, svg, bind, unbind, nextTick }
|
||||
|
||||
export class Component extends HTMLElement {
|
||||
/**
|
||||
|
@ -104,36 +36,33 @@ export class Component extends HTMLElement {
|
|||
let list = []
|
||||
|
||||
this.finalize()
|
||||
this.parseAnim()
|
||||
|
||||
this[__props__].forEach((options, prop) => {
|
||||
list.push(options.attrName)
|
||||
options.attribute && list.push(prop.toLowerCase())
|
||||
})
|
||||
return list.concat(this.watches || [], KEEP_ALIVE)
|
||||
return list
|
||||
}
|
||||
|
||||
static parseAnim() {
|
||||
if (this.hasOwnProperty('animation')) {
|
||||
let {
|
||||
type = 'fade',
|
||||
duration,
|
||||
custom,
|
||||
immediate = false
|
||||
} = this.animation
|
||||
let fromto = MODES[type] || MODES.fade
|
||||
if (custom) {
|
||||
fromto = custom
|
||||
}
|
||||
Object.defineProperty(this.prototype, '$animate', {
|
||||
value(out) {
|
||||
if (this[__mounted__]) {
|
||||
return animate.call(this, duration, fromto, out)
|
||||
}
|
||||
static createProperty(name, options) {
|
||||
let key = Symbol(name)
|
||||
let descriptor = {
|
||||
get() {
|
||||
return this[key]
|
||||
},
|
||||
set(value) {
|
||||
let oldValue = this[key]
|
||||
value = fixedValue(value, options)
|
||||
if (oldValue === value) {
|
||||
return
|
||||
}
|
||||
})
|
||||
this.prototype.$animate.immediate = immediate
|
||||
delete this.animation
|
||||
this[key] = value
|
||||
this.#requestUpdate(name, oldValue)
|
||||
},
|
||||
enumerable: false
|
||||
}
|
||||
|
||||
this[__props__].set(name, options)
|
||||
Object.defineProperty(this.prototype, name, descriptor)
|
||||
}
|
||||
|
||||
// 处理静态声明
|
||||
|
@ -147,135 +76,38 @@ export class Component extends HTMLElement {
|
|||
|
||||
if (this.hasOwnProperty('props')) {
|
||||
for (let k in this.props) {
|
||||
// 保留关键字, 直接跳过
|
||||
if (k === KEEP_ALIVE || k === KEEP_ALIVE_C) {
|
||||
continue
|
||||
}
|
||||
let options = parsePropsDeclaration(this.props[k])
|
||||
let attrName = k.toLowerCase()
|
||||
|
||||
options.attrName = attrName
|
||||
|
||||
if (boolMap[attrName]) {
|
||||
k = boolMap[attrName]
|
||||
} else {
|
||||
options.attrName = hyphen(k)
|
||||
k = camelize(k)
|
||||
if (boolMap[k] && k !== boolMap[k]) {
|
||||
k = boolMap[k]
|
||||
}
|
||||
this[__props__].set(k, options)
|
||||
this.createProperty(k, options)
|
||||
}
|
||||
}
|
||||
|
||||
delete this.props
|
||||
}
|
||||
|
||||
static reg(name = '') {
|
||||
name = 'wc-' + name
|
||||
if (!customElements.get(name)) {
|
||||
customElements.define(name, this)
|
||||
}
|
||||
}
|
||||
|
||||
keepAlive = false
|
||||
|
||||
removed = false
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this[__pending__] = false
|
||||
this[__mounted__] = false
|
||||
// 这里提前定义一次, 是为了在connectedCallback之前, 就已有赋值时报错的bug
|
||||
this[__changed_props__] = new Map() // 记录一次渲染周期内变化的属性
|
||||
this.host = this
|
||||
this[__init__]()
|
||||
this.created()
|
||||
}
|
||||
|
||||
[__init__]() {
|
||||
this.root = this.shadowRoot || this.attachShadow({ mode: 'open' })
|
||||
this.root.ownHost = this
|
||||
|
||||
Object.defineProperty(this, '$refs', {
|
||||
value: Object.create(null)
|
||||
this[__changed_props__] = new Map() // 记录本次变化的属性
|
||||
// 初始化 props
|
||||
this.constructor[__props__].forEach((options, prop) => {
|
||||
this[prop] = options.default
|
||||
})
|
||||
Object.defineProperty(this, '$events', {
|
||||
value: Object.create(null)
|
||||
})
|
||||
|
||||
for (let [prop, options] of this.constructor[__props__]) {
|
||||
this.#createProperty(prop, options)
|
||||
// 按W3C规范, 在构造函数内不可设置节点的属性
|
||||
// 所以这里只记录需要初始化的属性, 在#init()回调中才去修改
|
||||
this[__changed_props__].set(prop, this[prop])
|
||||
// 若无定义props时, 手动执行一次渲染
|
||||
if (this[__pending__] === false) {
|
||||
this[__pending__] = true
|
||||
this.performUpdate()
|
||||
}
|
||||
|
||||
nextTick(_ => this.created())
|
||||
}
|
||||
|
||||
#createProperty(name, options) {
|
||||
let key = Symbol(name)
|
||||
let descriptor
|
||||
|
||||
if (options.type === Array || options.type === Object) {
|
||||
let proxyValue = this.#createProxy(null, options, name)
|
||||
descriptor = {
|
||||
get() {
|
||||
return proxyValue
|
||||
},
|
||||
set(value) {
|
||||
proxyValue = this.#createProxy(
|
||||
fixedValue(value, options),
|
||||
options,
|
||||
name
|
||||
)
|
||||
this.$requestUpdate(name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
descriptor = {
|
||||
get() {
|
||||
return this[key]
|
||||
},
|
||||
set(value) {
|
||||
let oldValue = this[key]
|
||||
value = fixedValue(value, options)
|
||||
if (oldValue === value) {
|
||||
return
|
||||
}
|
||||
this[key] = value
|
||||
this.$requestUpdate(name)
|
||||
safely.call(this, options.observer, value, oldValue)
|
||||
}
|
||||
}
|
||||
this[key] = options.default
|
||||
}
|
||||
|
||||
Object.defineProperty(this, name, descriptor)
|
||||
}
|
||||
|
||||
#createProxy(obj, options = {}, key) {
|
||||
return new Proxy(obj || options.default, {
|
||||
get: (target, prop, receiver) => {
|
||||
let value = Reflect.get(target, prop, receiver)
|
||||
// 当访问的值是对象时,需要对这个对象也进行代理
|
||||
if (typeof value === 'object') {
|
||||
return this.#createProxy(value, {}, key)
|
||||
}
|
||||
return value
|
||||
},
|
||||
set: (target, prop, value, receiver) => {
|
||||
let oldValue = target[prop]
|
||||
Reflect.set(target, prop, value, receiver)
|
||||
|
||||
this.$requestUpdate(key)
|
||||
safely.call(this, options.observer, value, oldValue)
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#init() {
|
||||
for (let [prop, value] of this[__changed_props__]) {
|
||||
this.#prop2attr(prop, value)
|
||||
}
|
||||
// 这里要清除初始化产生的记录
|
||||
this[__changed_props__].clear()
|
||||
this.$requestUpdate()
|
||||
}
|
||||
|
||||
#getPropOptions(name) {
|
||||
|
@ -283,42 +115,21 @@ export class Component extends HTMLElement {
|
|||
}
|
||||
|
||||
connectedCallback() {
|
||||
if (this.$animate) {
|
||||
this.style.display = 'none'
|
||||
}
|
||||
this.removed = false
|
||||
this.#init()
|
||||
adoptStyles(this.root, this.constructor.styles)
|
||||
|
||||
this[__children__]?.setConnected(true)
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
if (this.keepAlive) {
|
||||
nextTick(_ => this.deactivated())
|
||||
} else {
|
||||
if (!document.body?.contains(this)) {
|
||||
let $events = this.$events
|
||||
if ($events) {
|
||||
for (let name in $events) {
|
||||
for (let it of $events[name]) {
|
||||
unbind(it.el, name, it.listener, it.options)
|
||||
}
|
||||
}
|
||||
}
|
||||
this.removed = true
|
||||
}
|
||||
nextTick(_ => this.unmounted())
|
||||
}
|
||||
this[__children__]?.setConnected(false)
|
||||
this.unmounted()
|
||||
}
|
||||
// 监听属性变化
|
||||
attributeChangedCallback(name, old, val) {
|
||||
if (old === val) {
|
||||
return
|
||||
}
|
||||
if (name === KEEP_ALIVE) {
|
||||
this.keepAlive = val !== null
|
||||
return
|
||||
}
|
||||
this.#attr2prop(name, val, old)
|
||||
this[__attr2prop__](name, val)
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -327,12 +138,10 @@ export class Component extends HTMLElement {
|
|||
* @param name<String>
|
||||
* @param value<String|Boolean|Number>
|
||||
*/
|
||||
#prop2attr(name, value) {
|
||||
let options = this.#getPropOptions(name) || {}
|
||||
let attrName = options.attrName
|
||||
[__prop2attr__](name, value) {
|
||||
let options = this.#getPropOptions(name)
|
||||
|
||||
if (options.attribute === false || options.type === null) {
|
||||
this.removeAttribute(attrName)
|
||||
if (options.attribute === false) {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -340,17 +149,17 @@ export class Component extends HTMLElement {
|
|||
case Number:
|
||||
case String:
|
||||
if (value === null) {
|
||||
this.removeAttribute(attrName)
|
||||
this.removeAttribute(name)
|
||||
} else {
|
||||
this.setAttribute(attrName, value)
|
||||
this.setAttribute(name, value)
|
||||
}
|
||||
break
|
||||
|
||||
case Boolean:
|
||||
if (value === null || value === false) {
|
||||
this.removeAttribute(attrName)
|
||||
this.removeAttribute(name)
|
||||
} else {
|
||||
this.setAttribute(attrName, '')
|
||||
this.setAttribute(name, '')
|
||||
}
|
||||
break
|
||||
}
|
||||
|
@ -361,112 +170,79 @@ export class Component extends HTMLElement {
|
|||
* @param name<String>
|
||||
* @param value<String|Boolean|Number>
|
||||
*/
|
||||
#attr2prop(name, value, old) {
|
||||
let _name = boolMap[name]
|
||||
let options, propName
|
||||
[__attr2prop__](name, value) {
|
||||
let options = this.#getPropOptions(name)
|
||||
|
||||
if (_name) {
|
||||
name = _name
|
||||
}
|
||||
propName = camelize(name)
|
||||
|
||||
options = this.#getPropOptions(propName)
|
||||
|
||||
if (options) {
|
||||
value = fixedValue(value, options)
|
||||
|
||||
if (options.attribute === false || options.type === null) {
|
||||
if (value === null) {
|
||||
return
|
||||
}
|
||||
if (value === this[propName]) {
|
||||
this.removeAttribute(name)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this[propName] = value
|
||||
this[name] = fixedValue(value, options)
|
||||
}
|
||||
|
||||
// 请求更新
|
||||
$requestUpdate(name) {
|
||||
if (name !== void 0) {
|
||||
this[__changed_props__].set(name, this[name])
|
||||
this.#prop2attr(name, this[name])
|
||||
}
|
||||
#requestUpdate(name, oldValue) {
|
||||
let shouldUpdate = true
|
||||
|
||||
this[__changed_props__].set(name, this[name])
|
||||
this[__prop2attr__](name, this[name])
|
||||
|
||||
if (this[__pending__] === false) {
|
||||
this[__pending__] = true
|
||||
nextTick(_ => this.#confirmUpdate())
|
||||
nextTick(_ => this[__updated__]())
|
||||
}
|
||||
}
|
||||
|
||||
// 确认更新到视图
|
||||
#confirmUpdate() {
|
||||
let props = this[__changed_props__]
|
||||
this.#render()
|
||||
this.#feedback(props)
|
||||
this.#clearUpdate()
|
||||
}
|
||||
|
||||
// 更新回调反馈
|
||||
#feedback(props) {
|
||||
// 初始化时不触发updated回调
|
||||
if (this[__mounted__] === false) {
|
||||
this[__mounted__] = true
|
||||
if (this.$animate?.immediate) {
|
||||
this.$animate()
|
||||
[__updated__]() {
|
||||
if (this[__pending__]) {
|
||||
try {
|
||||
let props = this[__changed_props__]
|
||||
this[__render__]()
|
||||
this[__feedback__](props)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
nextTick(_ => {
|
||||
if (this.keepAlive) {
|
||||
this.activated()
|
||||
}
|
||||
this.mounted()
|
||||
this.$requestUpdate()
|
||||
})
|
||||
} else {
|
||||
nextTick(_ => this.updated(props))
|
||||
this[__clear_update__]()
|
||||
}
|
||||
}
|
||||
|
||||
#clearUpdate() {
|
||||
this[__changed_props__].clear()
|
||||
// 更新回调反馈
|
||||
[__feedback__](props) {
|
||||
// 初始化时不触发updated回调
|
||||
if (!this[__mounted__]) {
|
||||
this[__mounted__] = true
|
||||
this.mounted()
|
||||
} else {
|
||||
this.updated(props)
|
||||
}
|
||||
}
|
||||
|
||||
[__clear_update__]() {
|
||||
this[__changed_props__] = new Map()
|
||||
this[__pending__] = false
|
||||
}
|
||||
|
||||
// 渲染视图
|
||||
#render() {
|
||||
try {
|
||||
let ast = this.render()
|
||||
render(ast, this.root, {
|
||||
host: this
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
[__render__]() {
|
||||
let htmlText = this.render()
|
||||
|
||||
this[__children__] = render(htmlText, this.root, {
|
||||
host: this,
|
||||
isConnected: !this[__mounted__] && this.isConnected
|
||||
})
|
||||
}
|
||||
// 几个生命周期回调
|
||||
created() {}
|
||||
mounted() {}
|
||||
activated() {}
|
||||
deactivated() {}
|
||||
unmounted() {}
|
||||
updated() {}
|
||||
render() {
|
||||
return html`<slot></slot>`
|
||||
|
||||
$on(type, callback) {
|
||||
return bind(this, type, callback)
|
||||
}
|
||||
|
||||
$on(type, callback, options) {
|
||||
return bind(this, type, callback, options)
|
||||
$off(type, callback) {
|
||||
unbind(this, type, callback)
|
||||
}
|
||||
|
||||
$off(type, callback, options) {
|
||||
unbind(this, type, callback, options)
|
||||
}
|
||||
|
||||
$emit(type, data = {}, stop = false) {
|
||||
return fire(this, type, data, stop)
|
||||
$emit(type, data = {}) {
|
||||
return fire(this, type, data)
|
||||
}
|
||||
}
|
||||
|
|
126
src/utils.js
126
src/utils.js
|
@ -4,18 +4,18 @@
|
|||
* @date 2023/03/07 22:11:30
|
||||
*/
|
||||
|
||||
export function noop() {}
|
||||
|
||||
export function $(selector, container, multi) {
|
||||
let fn = multi ? 'querySelectorAll' : 'querySelector'
|
||||
export function $(selector, container) {
|
||||
if (container) {
|
||||
return container[fn](selector)
|
||||
return container.querySelector(selector)
|
||||
}
|
||||
return document.body[fn](selector)
|
||||
return document.body.querySelector(selector)
|
||||
}
|
||||
|
||||
export function $$(selector, container) {
|
||||
return $(selector, container, true)
|
||||
if (container) {
|
||||
return container.querySelectorsAll(selector)
|
||||
}
|
||||
return document.body.querySelectorsAll(selector)
|
||||
}
|
||||
|
||||
export const nextTick = (function () {
|
||||
|
@ -24,14 +24,11 @@ export const nextTick = (function () {
|
|||
let bool = false
|
||||
|
||||
function callback() {
|
||||
while (queue.length > 0) {
|
||||
let fn = queue.shift()
|
||||
try {
|
||||
fn()
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
let n = queue.length
|
||||
for (let i = 0; i < n; i++) {
|
||||
queue[i]()
|
||||
}
|
||||
queue = queue.slice(n)
|
||||
}
|
||||
|
||||
new MutationObserver(callback).observe(node, { characterData: true })
|
||||
|
@ -43,46 +40,6 @@ export const nextTick = (function () {
|
|||
}
|
||||
})()
|
||||
|
||||
export function range(...args) {
|
||||
let start = 0,
|
||||
end = 0,
|
||||
step = 1,
|
||||
out = []
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
end = args[0]
|
||||
break
|
||||
case 2:
|
||||
case 3:
|
||||
;[start, end, step = 1] = args
|
||||
step = Math.abs(step) || 1
|
||||
break
|
||||
}
|
||||
|
||||
if (start > end) {
|
||||
;[start, end] = [end, start]
|
||||
}
|
||||
|
||||
for (let i = start; i < end; i += step) {
|
||||
out.push(i)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
//驼峰转换为连字符线风格
|
||||
export function hyphen(target) {
|
||||
return target.replace(/([a-z\d])([A-Z]+)/g, '$1-$2').toLowerCase()
|
||||
}
|
||||
|
||||
//连字符转换为驼峰风格
|
||||
export function camelize(target) {
|
||||
//提前判断,提高效率
|
||||
if (target.indexOf('-') < 0) {
|
||||
return target
|
||||
}
|
||||
return target.replace(/\-([a-z])/g, (m, s) => s.toUpperCase())
|
||||
}
|
||||
|
||||
//取得距离页面左上角的坐标
|
||||
export function offset(node) {
|
||||
try {
|
||||
|
@ -108,20 +65,12 @@ export function offset(node) {
|
|||
/**
|
||||
* 事件绑定
|
||||
*/
|
||||
export function bind(dom, type = '', selector, fn, phase = false) {
|
||||
export function bind(dom, type, selector, fn, phase = true) {
|
||||
let events = type.split(',')
|
||||
let callback
|
||||
let isWc = dom && dom.host === dom
|
||||
let host = isWc ? dom : null
|
||||
|
||||
if (!dom || !type) {
|
||||
return console.error(
|
||||
"Argument Error: function bind's arg 1 must be a document obejct"
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof selector === 'function') {
|
||||
phase = fn || false
|
||||
phase = fn
|
||||
fn = selector
|
||||
selector = null
|
||||
} else {
|
||||
|
@ -131,25 +80,13 @@ export function bind(dom, type = '', selector, fn, phase = false) {
|
|||
fn = fn || noop
|
||||
}
|
||||
|
||||
if (isWc === false) {
|
||||
let node = dom
|
||||
while (node && node !== document.body && node !== document) {
|
||||
if (node.ownHost) {
|
||||
isWc = true
|
||||
host = node.ownHost
|
||||
break
|
||||
}
|
||||
node = node.parentNode
|
||||
}
|
||||
}
|
||||
|
||||
if (selector) {
|
||||
callback = function (ev) {
|
||||
let agents = $(selector, dom)
|
||||
let agents = $(selector, ev.currentTarget)
|
||||
let elem = ev.target
|
||||
if (agents) {
|
||||
while (true) {
|
||||
if (elem === dom) {
|
||||
if (elem === ev.currentTarget) {
|
||||
break
|
||||
}
|
||||
if (agents.contains(elem)) {
|
||||
|
@ -166,25 +103,7 @@ export function bind(dom, type = '', selector, fn, phase = false) {
|
|||
}
|
||||
|
||||
events.forEach(function (t) {
|
||||
t = t.trim()
|
||||
if (isWc) {
|
||||
host.$events[t] ??= []
|
||||
|
||||
let _list = host.$events[t]
|
||||
if (_list.length) {
|
||||
let idx = _list.findIndex(
|
||||
it =>
|
||||
it.el === dom && it.listener === callback && it.options === phase
|
||||
)
|
||||
if (idx > -1) {
|
||||
let item = _list[idx]
|
||||
_list.splice(idx, 1)
|
||||
dom.removeEventListener(t, item.listener, item.options)
|
||||
}
|
||||
}
|
||||
_list.push({ el: dom, listener: callback, options: phase })
|
||||
}
|
||||
dom.addEventListener(t, callback, phase)
|
||||
dom.addEventListener(t.trim(), callback, phase)
|
||||
})
|
||||
return callback
|
||||
}
|
||||
|
@ -192,7 +111,7 @@ export function bind(dom, type = '', selector, fn, phase = false) {
|
|||
/**
|
||||
* 解除事件绑定
|
||||
*/
|
||||
export function unbind(dom, type = '', fn = noop, phase = false) {
|
||||
export function unbind(dom, type, fn = noop, phase = false) {
|
||||
let events = type.split(',')
|
||||
events.forEach(function (t) {
|
||||
dom.removeEventListener(t.trim(), fn, phase)
|
||||
|
@ -228,14 +147,9 @@ export function clearOutsideClick(fn = noop) {
|
|||
unbind(document, 'mousedown', fn)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param el <DOM> 节点
|
||||
* @param name <String> 自定义的事件名
|
||||
* @param data <Object> 要合并进event对象的参数
|
||||
* @param stop <Boolean> 是否禁止事件冒泡
|
||||
*/
|
||||
export function fire(el, name = 'click', data = {}, stop) {
|
||||
let ev = new Event(name, { bubbles: !stop, cancelable: true })
|
||||
export function fire(el, name = 'click', data = {}) {
|
||||
let ev = document.createEvent('Events')
|
||||
ev.initEvent(name, true, true)
|
||||
Object.assign(ev, data)
|
||||
el.dispatchEvent(ev)
|
||||
}
|
||||
|
|
|
@ -1,47 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
|
||||
<title>wkit test page</title>
|
||||
<style>
|
||||
body {line-height: 1.5;font-size:14px;background:var(--page-color);color:var(--text-color);}
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
border-radius: 10px;
|
||||
background: var(--summary-bg-color);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
border-radius: 3px;
|
||||
background: var(--border-color-dark);
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--summary-color);
|
||||
}
|
||||
@media screen and (max-width: 480px) {
|
||||
::-webkit-scrollbar {
|
||||
display: none;
|
||||
width: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports":{
|
||||
"es.shim":"//jscdn.ink/es.shim/latest/index.js",
|
||||
"wkit":"//127.0.0.1:9999/src/index.js",
|
||||
"wkitd":"//jscdn.ink/wkitd/1.3.10/index.js",
|
||||
"fetch":"//jscdn.ink/@bytedo/fetch/latest/next.js",
|
||||
"@bd/ui/":"//jscdn.ink/@bd/ui/0.1.16/"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script type="module" src="./test.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<wc-app></wc-app>
|
||||
</body>
|
||||
</html>
|
31
test/test.js
31
test/test.js
|
@ -1,31 +0,0 @@
|
|||
import { html, Component, live } from 'wkit'
|
||||
|
||||
class App extends Component {
|
||||
foo = ''
|
||||
|
||||
bar = { a: 333 }
|
||||
|
||||
created() {
|
||||
// live = live.bind(this)
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.foo = ''
|
||||
this.bar.a = '666'
|
||||
this.$requestUpdate()
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<p>${this.foo}</p>
|
||||
<p>${this.bar.a}</p>
|
||||
<input value=${live.bind(this, 'bar.a')} />
|
||||
<input value=${this.foo} />
|
||||
<input value=${live.bind(this, 'foo')} />
|
||||
|
||||
<button @click=${this.reset}>666</button>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
App.reg('app')
|
Loading…
Reference in New Issue