Compare commits
No commits in common. "master" and "1.10.1" 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/
|
|
@ -1,11 +1,11 @@
|
|||
## Wkit
|
||||
> 一个简单易用、功能完善的用于开发`web components`的轻量级开发库。模板解析基于`lit-html`二次开发
|
||||
> A library for building fast, lightweight web components.
|
||||
|
||||
![downloads](https://img.shields.io/npm/dt/wkit.svg)
|
||||
![version](https://img.shields.io/npm/v/wkit.svg)
|
||||
|
||||
### 开发文档
|
||||
[开发文档](https://git.wkit.fun/bytedo/wkit/wiki)
|
||||
[开发文档](https://github.com/bytedo/wkit/wiki)
|
||||
|
||||
|
||||
### 我们的特色
|
||||
|
@ -15,7 +15,6 @@
|
|||
- `:xxx=yyy`, 属性绑定, 类似`vue`,在属性前加上`:`, 该属性不再使用`setAttribute()`, 而是直接赋值, 可满足你需要传递复杂数据结构的需求。
|
||||
- `#animation={type}`, 开箱即用的动画配置, 内置6种动画`fade(默认), scale, bounce, micro-bounce, rotate, slide`
|
||||
- `ref=xxx`, 类似`vue`的节点标识, 可方便的在`mounted()`之后通过 `this.$refs.xxx` 来访问该节点
|
||||
- 内置特色的双向绑定方法`live()`
|
||||
- 用内置的`bind()`方法来给当前组件绑定事件时, 组件移除时事件也会自动销毁,无需手动销毁。
|
||||
- 灵活的`props`定义
|
||||
|
||||
|
@ -85,7 +84,3 @@ Hello.reg('hello')
|
|||
|
||||
|
||||
|
||||
### 开源协议
|
||||
|
||||
- BSD 3-Clause License (Lit框架的html模板解析的源码)
|
||||
- MIT (除Lit代码之外的所有代码)
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "wkit",
|
||||
"version": "1.12.0",
|
||||
"version": "1.10.1",
|
||||
"type": "module",
|
||||
"description": "A library for building fast, lightweight web components.",
|
||||
"main": "dist/index.js",
|
||||
|
@ -14,7 +14,7 @@
|
|||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.wkit.fun/bytedo/wkit.git"
|
||||
"url": "git+https://github.com/bytedo/wkit.git"
|
||||
},
|
||||
"keywords": [
|
||||
"wkit",
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
*/
|
||||
|
||||
export function animate(duration = 200, fromto = [], out = false) {
|
||||
if (out === false && this.style.display === 'none') {
|
||||
if (out === false) {
|
||||
this.style.display = ''
|
||||
}
|
||||
let res = this.animate(fromto, {
|
||||
|
|
|
@ -35,8 +35,6 @@ const boolMap = Object.create(null)
|
|||
|
||||
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 NOTHING = Symbol('wc-nothing')
|
||||
export const __finalized__ = Symbol('finalized')
|
||||
|
@ -44,8 +42,9 @@ export const __props__ = Symbol('props')
|
|||
export const __changed_props__ = Symbol('changed_props')
|
||||
export const __mounted__ = Symbol('mounted')
|
||||
export const __pending__ = Symbol('pending')
|
||||
export const __children__ = Symbol('children')
|
||||
|
||||
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) {
|
||||
|
@ -83,14 +82,16 @@ function getType(v) {
|
|||
let type = String
|
||||
let attribute = true
|
||||
if (v.includes('!')) {
|
||||
if (v.startsWith('str!')) {
|
||||
v = v.slice(4)
|
||||
} else if (v.startsWith('num!')) {
|
||||
v = v.split('!')
|
||||
let _t = v.shift()
|
||||
if (_t === 'str') {
|
||||
v = v.join('!')
|
||||
} else if (_t === 'num') {
|
||||
type = Number
|
||||
v = +v.slice(4) || 0
|
||||
} else if (v.startsWith('bool!')) {
|
||||
v = +v.shift() || 0
|
||||
} else if (_t === 'bool') {
|
||||
type = Boolean
|
||||
v = v.slice(5)
|
||||
v = v.shift()
|
||||
v = v !== 'false' && v !== ''
|
||||
}
|
||||
attribute = false
|
||||
|
@ -98,7 +99,7 @@ function getType(v) {
|
|||
return { type, default: v, attribute }
|
||||
|
||||
default:
|
||||
return { type: null, default: '' }
|
||||
return { type: String, default: v + '' }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -128,10 +129,6 @@ export function parsePropsDeclaration(options) {
|
|||
options = { type: Array }
|
||||
break
|
||||
|
||||
case String:
|
||||
options = { type: String }
|
||||
break
|
||||
|
||||
default:
|
||||
options = getType(options)
|
||||
break
|
||||
|
@ -175,9 +172,6 @@ export function fixedValue(value, options) {
|
|||
}
|
||||
}
|
||||
|
||||
case null:
|
||||
return value
|
||||
|
||||
default:
|
||||
return value === null || value === void 0 ? null : value + ''
|
||||
}
|
||||
|
|
429
src/html.js
429
src/html.js
|
@ -6,30 +6,30 @@
|
|||
|
||||
import { boolMap, WC_PART, NOTHING } from './constants.js'
|
||||
import { animate, MODES } from './anim.js'
|
||||
import { nextTick, noop } from './utils.js'
|
||||
|
||||
const BIND_ATTR_SUFFIX = '{{$wkit$}}'
|
||||
const MARKER = `{{^wkit${String(Math.random()).slice(-8)}^}}`
|
||||
const MARKER_MATCH = '?' + MARKER
|
||||
const NODE_MARKER = `<${MARKER_MATCH}>`
|
||||
|
||||
// 是否原始值
|
||||
const boundAttributeSuffix = '$wc$'
|
||||
const marker = `wc$${String(Math.random()).slice(9)}$`
|
||||
const markerMatch = '?' + marker
|
||||
const nodeMarker = `<${markerMatch}>`
|
||||
const createMarker = (v = '') => document.createComment(v)
|
||||
const isPrimitive = value =>
|
||||
value === null || (typeof value !== 'object' && typeof value !== 'function')
|
||||
value === null || (typeof value != 'object' && typeof value != 'function')
|
||||
const isArray = Array.isArray
|
||||
const isIterable = value =>
|
||||
value ? isArray(value) || typeof value[Symbol.iterator] === 'function' : false
|
||||
|
||||
isArray(value) ||
|
||||
typeof (value === null || value === void 0
|
||||
? false
|
||||
: value[Symbol.iterator]) === 'function'
|
||||
const SPACE_CHAR = `[ \n\f\r]`
|
||||
const ATTR_VALUE_CHAR = `[^ \n\f\r"'\`<>=]`
|
||||
const NAME_CHAR = `[^\\s"'>=/]`
|
||||
const TEXT_END_REGEX = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g
|
||||
const textEndRegex = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g
|
||||
const COMMENT_START = 1
|
||||
const TAG_NAME = 2
|
||||
const DYNAMIC_TAG_NAME = 3
|
||||
const COMMENT_END_REGEXP = /-->/g
|
||||
const COMMENT_END_REGEXP_2 = />/g
|
||||
const TAG_END_REGEXP = new RegExp(
|
||||
const commentEndRegex = /-->/g
|
||||
const comment2EndRegex = />/g
|
||||
const tagEndRegex = new RegExp(
|
||||
`>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|("|')|))|$)`,
|
||||
'g'
|
||||
)
|
||||
|
@ -37,9 +37,9 @@ const ENTIRE_MATCH = 0
|
|||
const ATTRIBUTE_NAME = 1
|
||||
const SPACES_AND_EQUALS = 2
|
||||
const QUOTE_CHAR = 3
|
||||
const SINGLE_QUOTE_REGEXP = /'/g
|
||||
const DOUBLE_QUOTE_REGEXP = /"/g
|
||||
const RAW_TEXT_ELEM_REGEXP = /^(?:script|style|textarea|title)$/i
|
||||
const singleQuoteAttrEndRegex = /'/g
|
||||
const doubleQuoteAttrEndRegex = /"/g
|
||||
const rawTextElement = /^(?:script|style|textarea|title)$/i
|
||||
const HTML_RESULT = 1
|
||||
const SVG_RESULT = 2
|
||||
const ATTRIBUTE_PART = 1
|
||||
|
@ -51,12 +51,14 @@ const COMMENT_PART = 7
|
|||
const TEMPLATE_CACHE = new Map()
|
||||
const walker = document.createTreeWalker(document, 129, null, false)
|
||||
|
||||
function noop() {}
|
||||
|
||||
function getTemplateHtml(strings, type) {
|
||||
let len = strings.length - 1
|
||||
let attrNames = []
|
||||
let html2 = type === SVG_RESULT ? '<svg>' : ''
|
||||
let rawTextEndRegex
|
||||
let regex = TEXT_END_REGEX
|
||||
let regex = textEndRegex
|
||||
for (let i = 0; i < len; i++) {
|
||||
let s = strings[i]
|
||||
let attrNameEndIndex = -1
|
||||
|
@ -70,26 +72,25 @@ function getTemplateHtml(strings, type) {
|
|||
break
|
||||
}
|
||||
lastIndex = regex.lastIndex
|
||||
|
||||
if (regex === TEXT_END_REGEX) {
|
||||
if (regex === textEndRegex) {
|
||||
if (match[COMMENT_START] === '!--') {
|
||||
regex = COMMENT_END_REGEXP
|
||||
regex = commentEndRegex
|
||||
} else if (match[COMMENT_START] !== void 0) {
|
||||
regex = COMMENT_END_REGEXP_2
|
||||
regex = comment2EndRegex
|
||||
} else if (match[TAG_NAME] !== void 0) {
|
||||
if (RAW_TEXT_ELEM_REGEXP.test(match[TAG_NAME])) {
|
||||
if (rawTextElement.test(match[TAG_NAME])) {
|
||||
rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g')
|
||||
}
|
||||
regex = TAG_END_REGEXP
|
||||
regex = tagEndRegex
|
||||
} else if (match[DYNAMIC_TAG_NAME] !== void 0) {
|
||||
regex = TAG_END_REGEXP
|
||||
regex = tagEndRegex
|
||||
}
|
||||
} else if (regex === TAG_END_REGEXP) {
|
||||
} else if (regex === tagEndRegex) {
|
||||
if (match[ENTIRE_MATCH] === '>') {
|
||||
regex =
|
||||
rawTextEndRegex !== null && rawTextEndRegex !== void 0
|
||||
? rawTextEndRegex
|
||||
: TEXT_END_REGEX
|
||||
: textEndRegex
|
||||
attrNameEndIndex = -1
|
||||
} else if (match[ATTRIBUTE_NAME] === void 0) {
|
||||
attrNameEndIndex = -2
|
||||
|
@ -98,76 +99,58 @@ function getTemplateHtml(strings, type) {
|
|||
attrName = match[ATTRIBUTE_NAME]
|
||||
regex =
|
||||
match[QUOTE_CHAR] === void 0
|
||||
? TAG_END_REGEXP
|
||||
? tagEndRegex
|
||||
: match[QUOTE_CHAR] === '"'
|
||||
? DOUBLE_QUOTE_REGEXP
|
||||
: SINGLE_QUOTE_REGEXP
|
||||
? doubleQuoteAttrEndRegex
|
||||
: singleQuoteAttrEndRegex
|
||||
}
|
||||
} else if (
|
||||
regex === DOUBLE_QUOTE_REGEXP ||
|
||||
regex === SINGLE_QUOTE_REGEXP
|
||||
regex === doubleQuoteAttrEndRegex ||
|
||||
regex === singleQuoteAttrEndRegex
|
||||
) {
|
||||
regex = TAG_END_REGEXP
|
||||
} else if (
|
||||
regex === COMMENT_END_REGEXP ||
|
||||
regex === COMMENT_END_REGEXP_2
|
||||
) {
|
||||
regex = TEXT_END_REGEX
|
||||
regex = tagEndRegex
|
||||
} else if (regex === commentEndRegex || regex === comment2EndRegex) {
|
||||
regex = textEndRegex
|
||||
} else {
|
||||
regex = TAG_END_REGEXP
|
||||
regex = tagEndRegex
|
||||
rawTextEndRegex = void 0
|
||||
}
|
||||
}
|
||||
|
||||
let end =
|
||||
regex === TAG_END_REGEXP && strings[i + 1].startsWith('/>') ? ' ' : ''
|
||||
regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : ''
|
||||
html2 +=
|
||||
regex === TEXT_END_REGEX
|
||||
? s + NODE_MARKER
|
||||
regex === textEndRegex
|
||||
? s + nodeMarker
|
||||
: attrNameEndIndex >= 0
|
||||
? (attrNames.push(attrName),
|
||||
s.slice(0, attrNameEndIndex) +
|
||||
BIND_ATTR_SUFFIX +
|
||||
boundAttributeSuffix +
|
||||
s.slice(attrNameEndIndex)) +
|
||||
MARKER +
|
||||
marker +
|
||||
end
|
||||
: s +
|
||||
MARKER +
|
||||
marker +
|
||||
(attrNameEndIndex === -2 ? (attrNames.push(void 0), i) : end)
|
||||
}
|
||||
let htmlResult =
|
||||
html2 + (strings[len] || '<?>') + (type === SVG_RESULT ? '</svg>' : '')
|
||||
if (!isArray(strings) || !strings.hasOwnProperty('raw')) {
|
||||
if (!Array.isArray(strings) || !strings.hasOwnProperty('raw')) {
|
||||
throw new Error('invalid html ast')
|
||||
}
|
||||
return [htmlResult, attrNames]
|
||||
}
|
||||
|
||||
function createElement(v = '') {
|
||||
let el = document.createElement('template')
|
||||
el.innerHTML = v
|
||||
return el
|
||||
}
|
||||
|
||||
function createMarker(v = '') {
|
||||
return document.createComment(v)
|
||||
}
|
||||
|
||||
class Template {
|
||||
parts = []
|
||||
|
||||
constructor({ strings, values, __dom_type__: type }, options) {
|
||||
constructor({ strings, ['__dom_type__']: type }, options) {
|
||||
this.parts = []
|
||||
let node
|
||||
let nodeIndex = 0
|
||||
let attrNameIndex = 0
|
||||
let partCount = strings.length - 1
|
||||
let parts = this.parts
|
||||
let [html2, attrNames] = getTemplateHtml(strings, type)
|
||||
|
||||
this.el = createElement(html2)
|
||||
|
||||
this.el = Template.createElement(html2)
|
||||
walker.currentNode = this.el.content
|
||||
|
||||
if (type === SVG_RESULT) {
|
||||
let content = this.el.content
|
||||
let svgElement = content.firstChild
|
||||
|
@ -181,14 +164,17 @@ class Template {
|
|||
let attrsToRemove = []
|
||||
|
||||
for (let name of node.getAttributeNames()) {
|
||||
if (name.endsWith(BIND_ATTR_SUFFIX) || name.startsWith(MARKER)) {
|
||||
if (
|
||||
name.endsWith(boundAttributeSuffix) ||
|
||||
name.startsWith(marker)
|
||||
) {
|
||||
let realName = attrNames[attrNameIndex++]
|
||||
attrsToRemove.push(name)
|
||||
if (realName !== void 0) {
|
||||
let value = node.getAttribute(
|
||||
realName.toLowerCase() + BIND_ATTR_SUFFIX
|
||||
realName.toLowerCase() + boundAttributeSuffix
|
||||
)
|
||||
let statics = value.split(MARKER)
|
||||
let statics = value.split(marker)
|
||||
let m = /([#:@])?(.*)/.exec(realName)
|
||||
let decorates = []
|
||||
|
||||
|
@ -224,8 +210,8 @@ class Template {
|
|||
node.removeAttribute(name)
|
||||
}
|
||||
}
|
||||
if (RAW_TEXT_ELEM_REGEXP.test(node.tagName)) {
|
||||
let strings2 = node.textContent.split(MARKER)
|
||||
if (rawTextElement.test(node.tagName)) {
|
||||
let strings2 = node.textContent.split(marker)
|
||||
let lastIndex = strings2.length - 1
|
||||
if (lastIndex > 0) {
|
||||
node.textContent = ''
|
||||
|
@ -239,29 +225,38 @@ class Template {
|
|||
}
|
||||
} else if (node.nodeType === 8) {
|
||||
let data = node.data
|
||||
if (data === MARKER_MATCH) {
|
||||
if (data === markerMatch) {
|
||||
parts.push({ type: CHILD_PART, index: nodeIndex })
|
||||
} else {
|
||||
let i = -1
|
||||
while ((i = node.data.indexOf(MARKER, i + 1)) !== -1) {
|
||||
while ((i = node.data.indexOf(marker, i + 1)) !== -1) {
|
||||
parts.push({ type: COMMENT_PART, index: nodeIndex })
|
||||
i += MARKER.length - 1
|
||||
i += marker.length - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
nodeIndex++
|
||||
}
|
||||
}
|
||||
static createElement(html2) {
|
||||
let el = document.createElement('template')
|
||||
el.innerHTML = html2
|
||||
return el
|
||||
}
|
||||
}
|
||||
|
||||
class TemplateInstance {
|
||||
constructor(template, parent) {
|
||||
this.$parts = []
|
||||
this.$template = template
|
||||
this.$parent = parent
|
||||
this._parts = []
|
||||
this._$disconnectableChildren = void 0
|
||||
this._$template = template
|
||||
this._$parent = parent
|
||||
}
|
||||
get parentNode() {
|
||||
return this.$parent.parentNode
|
||||
return this._$parent.parentNode
|
||||
}
|
||||
get _$isConnected() {
|
||||
return this._$parent._$isConnected
|
||||
}
|
||||
|
||||
#checkRef(node, walker, options) {
|
||||
|
@ -273,11 +268,11 @@ class TemplateInstance {
|
|||
} while ((node = walker.nextNode()) !== null)
|
||||
}
|
||||
|
||||
clone(options) {
|
||||
_clone(options) {
|
||||
let {
|
||||
el: { content },
|
||||
parts
|
||||
} = this.$template
|
||||
} = this._$template
|
||||
|
||||
let fragment = document.importNode(content, true)
|
||||
let nodeIndex = 0
|
||||
|
@ -315,7 +310,7 @@ class TemplateInstance {
|
|||
} else if (templatePart.type === ELEMENT_PART) {
|
||||
part = new ElementPart(node, this, options)
|
||||
}
|
||||
this.$parts.push(part)
|
||||
this._parts.push(part)
|
||||
templatePart = parts[++partIndex]
|
||||
}
|
||||
if (
|
||||
|
@ -334,16 +329,15 @@ class TemplateInstance {
|
|||
|
||||
return fragment
|
||||
}
|
||||
|
||||
update(values) {
|
||||
_update(values) {
|
||||
let i = 0
|
||||
for (let part of this.$parts) {
|
||||
for (let part of this._parts) {
|
||||
if (part !== void 0) {
|
||||
if (part.strings !== void 0) {
|
||||
part.$setValue(values, i)
|
||||
part._$setValue(values, i)
|
||||
i += part.strings.length - 2
|
||||
} else {
|
||||
part.$setValue(values[i])
|
||||
part._$setValue(values[i])
|
||||
}
|
||||
}
|
||||
i++
|
||||
|
@ -352,116 +346,118 @@ class TemplateInstance {
|
|||
}
|
||||
|
||||
class ChildPart {
|
||||
type = CHILD_PART
|
||||
#value = NOTHING
|
||||
|
||||
constructor(startNode, endNode, parent, options) {
|
||||
this.startNode = startNode
|
||||
this.endNode = endNode
|
||||
this.$parent = parent
|
||||
this.type = CHILD_PART
|
||||
this._$committedValue = NOTHING
|
||||
this._$disconnectableChildren = void 0
|
||||
this._$startNode = startNode
|
||||
this._$endNode = endNode
|
||||
this._$parent = parent
|
||||
this.options = options
|
||||
this.__isConnected = options.isConnected || true
|
||||
}
|
||||
get _$isConnected() {
|
||||
return this._$parent?._$isConnected || this.__isConnected
|
||||
}
|
||||
|
||||
get parentNode() {
|
||||
let parentNode = this.startNode.parentNode
|
||||
let parent = this.$parent
|
||||
let parentNode = this._$startNode.parentNode
|
||||
let parent = this._$parent
|
||||
if (parent !== void 0 && parentNode.nodeType === 11) {
|
||||
parentNode = parent.parentNode
|
||||
}
|
||||
return parentNode
|
||||
}
|
||||
|
||||
$setValue(value, clear) {
|
||||
get startNode() {
|
||||
return this._$startNode
|
||||
}
|
||||
get endNode() {
|
||||
return this._$endNode
|
||||
}
|
||||
_$setValue(value) {
|
||||
if (isPrimitive(value)) {
|
||||
if (value === NOTHING || value == null || value === '') {
|
||||
if (this.#value !== NOTHING) {
|
||||
if (this._$committedValue !== NOTHING) {
|
||||
this.#clear()
|
||||
}
|
||||
this.#value = NOTHING
|
||||
} else if (value !== this.#value) {
|
||||
this.#commitText(value)
|
||||
this._$committedValue = NOTHING
|
||||
} else if (value !== this._$committedValue) {
|
||||
this._commitText(value)
|
||||
}
|
||||
} else if (value.__dom_type__ !== void 0) {
|
||||
this.#commitTemplateResult(value)
|
||||
} else if (value['__dom_type__'] !== void 0) {
|
||||
this._commitTemplateResult(value)
|
||||
} else if (value.nodeType !== void 0) {
|
||||
this.#commitNode(value)
|
||||
this._commitNode(value)
|
||||
} else if (isIterable(value)) {
|
||||
this.#commitIterable(value)
|
||||
this._commitIterable(value)
|
||||
} else {
|
||||
this.#commitText(value)
|
||||
}
|
||||
if (clear) {
|
||||
nextTick(_ => this.#clearBindings())
|
||||
this._commitText(value)
|
||||
}
|
||||
}
|
||||
|
||||
#insert(node, target = this.endNode) {
|
||||
return this.startNode.parentNode.insertBefore(node, target)
|
||||
_insert(node, target = this._$endNode) {
|
||||
return this._$startNode.parentNode.insertBefore(node, target)
|
||||
}
|
||||
|
||||
#commitNode(value) {
|
||||
if (this.#value !== value) {
|
||||
_commitNode(value) {
|
||||
if (this._$committedValue !== value) {
|
||||
this.#clear()
|
||||
this.#value = this.#insert(value)
|
||||
this._$committedValue = this._insert(value)
|
||||
}
|
||||
}
|
||||
|
||||
#commitText(value) {
|
||||
if (this.#value !== NOTHING && isPrimitive(this.#value)) {
|
||||
let node = this.startNode.nextSibling
|
||||
_commitText(value) {
|
||||
if (
|
||||
this._$committedValue !== NOTHING &&
|
||||
isPrimitive(this._$committedValue)
|
||||
) {
|
||||
let node = this._$startNode.nextSibling
|
||||
|
||||
node.data = value
|
||||
} else {
|
||||
this.#commitNode(document.createTextNode(value))
|
||||
this._commitNode(document.createTextNode(value))
|
||||
}
|
||||
this.#value = value
|
||||
this._$committedValue = value
|
||||
}
|
||||
|
||||
#commitTemplateResult(result) {
|
||||
let { values, __dom_type__: type } = result
|
||||
_commitTemplateResult(result) {
|
||||
let { values, ['__dom_type__']: type } = result
|
||||
let template =
|
||||
typeof type === 'number'
|
||||
? this.#getTemplate(result)
|
||||
: (type.el === void 0 && (type.el = createElement(type.h)), type)
|
||||
: (type.el === void 0 && (type.el = Template.createElement(type.h)),
|
||||
type)
|
||||
|
||||
if (this.#value?.$template === template) {
|
||||
this.#value.update(values)
|
||||
if (this._$committedValue?._$template === template) {
|
||||
this._$committedValue._update(values)
|
||||
} else {
|
||||
let instance = new TemplateInstance(template, this)
|
||||
let fragment = instance.clone(this.options)
|
||||
let fragment = instance._clone(this.options)
|
||||
|
||||
instance.update(values)
|
||||
instance._update(values)
|
||||
|
||||
this.#commitNode(fragment)
|
||||
this.#value = instance
|
||||
this._commitNode(fragment)
|
||||
this._$committedValue = instance
|
||||
}
|
||||
}
|
||||
|
||||
#getTemplate(result) {
|
||||
let key = result.strings.join()
|
||||
let template = TEMPLATE_CACHE.get(key)
|
||||
let template = TEMPLATE_CACHE.get(result.strings.join())
|
||||
|
||||
if (template === void 0) {
|
||||
template = new Template(result, this.options)
|
||||
TEMPLATE_CACHE.set(key, template)
|
||||
TEMPLATE_CACHE.set(result.strings.join(), template)
|
||||
}
|
||||
return template
|
||||
}
|
||||
|
||||
#commitIterable(value) {
|
||||
if (!isArray(this.#value)) {
|
||||
this.#value = []
|
||||
_commitIterable(value) {
|
||||
if (!isArray(this._$committedValue)) {
|
||||
this._$committedValue = []
|
||||
this.#clear()
|
||||
}
|
||||
let itemParts = this.#value
|
||||
let itemParts = this._$committedValue
|
||||
let partIndex = 0
|
||||
let itemPart
|
||||
for (let item of value) {
|
||||
if (partIndex === itemParts.length) {
|
||||
itemParts.push(
|
||||
(itemPart = new ChildPart(
|
||||
this.#insert(createMarker()),
|
||||
this.#insert(createMarker()),
|
||||
this._insert(createMarker()),
|
||||
this._insert(createMarker()),
|
||||
this,
|
||||
this.options
|
||||
))
|
||||
|
@ -469,74 +465,63 @@ class ChildPart {
|
|||
} else {
|
||||
itemPart = itemParts[partIndex]
|
||||
}
|
||||
itemPart.$setValue(item)
|
||||
itemPart._$setValue(item)
|
||||
partIndex++
|
||||
}
|
||||
if (partIndex < itemParts.length) {
|
||||
this.#clear(itemPart && itemPart.endNode.nextSibling, partIndex)
|
||||
this.#clear(itemPart && itemPart._$endNode.nextSibling, partIndex)
|
||||
itemParts.length = partIndex
|
||||
}
|
||||
}
|
||||
|
||||
#clear(start = this.startNode.nextSibling, from) {
|
||||
while (start && start !== this.endNode) {
|
||||
#clear(start = this._$startNode.nextSibling, from) {
|
||||
this._$notifyConnectionChanged?.call(this, false, true, from)
|
||||
|
||||
while (start && start !== this._$endNode) {
|
||||
let node = start.nextSibling
|
||||
start.remove()
|
||||
start = node
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除已被移除的节点事件
|
||||
*/
|
||||
#clearBindings() {
|
||||
let host = this.options.host
|
||||
let events = host.$events
|
||||
|
||||
for (let ev in events) {
|
||||
for (let i = -1, it; (it = events[ev][++i]); ) {
|
||||
if (!host.root.contains(it.el)) {
|
||||
it.el.removeEventListener(this.name, it.listener, it.options)
|
||||
events[ev][i] = null
|
||||
}
|
||||
}
|
||||
events[ev] = events[ev].filter(e => e !== null)
|
||||
setConnected(isConnected) {
|
||||
if (this._$parent === void 0) {
|
||||
this.__isConnected = isConnected
|
||||
this._$notifyConnectionChanged?.call(this, isConnected)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 常规属性
|
||||
class AttributePart {
|
||||
type = ATTRIBUTE_PART
|
||||
|
||||
#value = NOTHING
|
||||
|
||||
constructor(element, name, strings, decorates, parent, options = {}) {
|
||||
this.type = ATTRIBUTE_PART
|
||||
this._$committedValue = NOTHING
|
||||
this._$disconnectableChildren = void 0
|
||||
this.element = element
|
||||
this.name = name
|
||||
this.decorates = decorates
|
||||
this.$parent = parent
|
||||
this._$parent = parent
|
||||
this.options = options
|
||||
if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {
|
||||
this.#value = Array(strings.length - 1).fill(null)
|
||||
this._$committedValue = new Array(strings.length - 1).fill(new String())
|
||||
this.strings = strings
|
||||
} else {
|
||||
this._$committedValue = NOTHING
|
||||
}
|
||||
}
|
||||
get tagName() {
|
||||
return this.element.tagName
|
||||
}
|
||||
get _$isConnected() {
|
||||
return this._$parent._$isConnected
|
||||
}
|
||||
|
||||
$setValue(value, valueIndex) {
|
||||
_$setValue(value, valueIndex) {
|
||||
let strings = this.strings
|
||||
let changed = false
|
||||
|
||||
if (typeof value === 'function') {
|
||||
value = value(this.element)
|
||||
}
|
||||
|
||||
if (strings === void 0) {
|
||||
changed = !isPrimitive(value) || value !== this.#value
|
||||
changed = !isPrimitive(value) || value !== this._$committedValue
|
||||
if (changed) {
|
||||
this.#value = value
|
||||
this._$committedValue = value
|
||||
}
|
||||
} else {
|
||||
let values = value
|
||||
|
@ -545,49 +530,41 @@ class AttributePart {
|
|||
for (let i = 0; i < strings.length - 1; i++) {
|
||||
let v = values[valueIndex + i]
|
||||
|
||||
changed || (changed = !isPrimitive(v) || v !== this.#value[i])
|
||||
changed || (changed = !isPrimitive(v) || v !== this._$committedValue[i])
|
||||
if (v === NOTHING) {
|
||||
value = NOTHING
|
||||
} else if (value !== NOTHING) {
|
||||
value += (v !== null && v !== void 0 ? v : '') + strings[i + 1]
|
||||
}
|
||||
this.#value[i] = v
|
||||
this._$committedValue[i] = v
|
||||
}
|
||||
}
|
||||
// value属性做特殊处理, 解决输入框无法清空的问题
|
||||
if (changed || this.name === 'value') {
|
||||
if (changed) {
|
||||
this.commitValue(value)
|
||||
}
|
||||
}
|
||||
|
||||
commitValue(value) {
|
||||
let elem = this.element
|
||||
let attr = this.name
|
||||
let isBoolAttr = boolMap[attr]
|
||||
let isBoolAttr = boolMap[this.name]
|
||||
// ref属性不渲染到节点上
|
||||
if (attr === 'ref') {
|
||||
this.options.host.$refs[value] = elem
|
||||
if (this.name === 'ref') {
|
||||
this.options.host.$refs[value] = this.element
|
||||
return
|
||||
}
|
||||
|
||||
if (isBoolAttr) {
|
||||
elem[isBoolAttr] = !(value === false || value === null)
|
||||
this.element[isBoolAttr] = !(value === false || value === null)
|
||||
|
||||
if (elem[isBoolAttr]) {
|
||||
elem.setAttribute(attr, '')
|
||||
if (this.element[isBoolAttr]) {
|
||||
this.element.setAttribute(this.name, '')
|
||||
} else {
|
||||
elem.removeAttribute(attr)
|
||||
this.element.removeAttribute(this.name)
|
||||
}
|
||||
} else {
|
||||
// value 绑定, 特殊处理
|
||||
if (attr === 'value') {
|
||||
elem.value = value
|
||||
if (value === null || value === void 0) {
|
||||
this.element.removeAttribute(this.name)
|
||||
} else {
|
||||
if (value === null || value === void 0) {
|
||||
elem.removeAttribute(attr)
|
||||
} else {
|
||||
elem.setAttribute(attr, value)
|
||||
}
|
||||
this.element.setAttribute(this.name, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -609,23 +586,20 @@ class AnimPart extends AttributePart {
|
|||
}
|
||||
|
||||
commitValue({ type = 'fade', duration, custom, immediate = false } = {}) {
|
||||
let elem = this.element
|
||||
let fromto = MODES[type] || MODES.fade
|
||||
|
||||
if (custom) {
|
||||
fromto = custom
|
||||
}
|
||||
elem.$animate = function (out = false) {
|
||||
this.element.$animate = function (out = false) {
|
||||
return animate.call(this, duration, fromto, out)
|
||||
}
|
||||
elem.$animate.immediate = immediate
|
||||
this.element.$animate.immediate = immediate
|
||||
}
|
||||
}
|
||||
|
||||
// 事件属性
|
||||
class EventPart extends AttributePart {
|
||||
type = EVENT_PART
|
||||
|
||||
#listener = null
|
||||
|
||||
#prevent = noop
|
||||
|
@ -634,14 +608,12 @@ class EventPart extends AttributePart {
|
|||
|
||||
constructor(...args) {
|
||||
super(...args)
|
||||
this.type = EVENT_PART
|
||||
}
|
||||
|
||||
$setValue(listener) {
|
||||
_$setValue(listener) {
|
||||
let host = this.options.host
|
||||
let elem = this.element
|
||||
let name = this.name
|
||||
let options = {}
|
||||
let events = host.$events[name] || []
|
||||
|
||||
if (this.decorates.length) {
|
||||
for (let it of this.decorates) {
|
||||
|
@ -653,7 +625,7 @@ class EventPart extends AttributePart {
|
|||
this.#prevent = ev => ev.preventDefault()
|
||||
break
|
||||
case 'self':
|
||||
this.#checkSelf = ev => ev.target === elem
|
||||
this.#checkSelf = ev => ev.target === this.element
|
||||
break
|
||||
case 'capture':
|
||||
case 'once':
|
||||
|
@ -666,34 +638,42 @@ class EventPart extends AttributePart {
|
|||
|
||||
let shouldRemove = listener !== this.#listener
|
||||
|
||||
if (this.#listener) {
|
||||
for (let i = -1, it; (it = events[++i]); ) {
|
||||
if (it.el === elem) {
|
||||
if (this.#listener && host.$events[this.name]) {
|
||||
for (let it of host.$events[this.name]) {
|
||||
if (it.el === this.element) {
|
||||
shouldRemove =
|
||||
shouldRemove ||
|
||||
options.capture !== it.capture ||
|
||||
options.once !== it.once ||
|
||||
options.passive !== it.passive
|
||||
if (shouldRemove) {
|
||||
it.el.removeEventListener(name, it.listener, it.options)
|
||||
events[i] = null
|
||||
this.element.removeEventListener(this.name, it.listener, it.options)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
events = events.filter(it => it !== null)
|
||||
host.$events[name] = events
|
||||
|
||||
if (listener && shouldRemove) {
|
||||
elem.addEventListener(name, this, options)
|
||||
this.element.addEventListener(this.name, this, options)
|
||||
this.#listener = listener
|
||||
|
||||
events.push({ el: elem, listener: this, options })
|
||||
if (host.$events[this.name]) {
|
||||
host.$events[this.name].push({
|
||||
el: this.element,
|
||||
listener: this,
|
||||
options
|
||||
})
|
||||
} else {
|
||||
host.$events[this.name] = [
|
||||
{
|
||||
el: this.element,
|
||||
listener: this,
|
||||
options
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleEvent(ev) {
|
||||
this.#stop(ev)
|
||||
this.#prevent(ev)
|
||||
|
@ -705,14 +685,17 @@ class EventPart extends AttributePart {
|
|||
}
|
||||
|
||||
class ElementPart {
|
||||
type = ELEMENT_PART
|
||||
constructor(element, parent, options) {
|
||||
this.element = element
|
||||
this.$parent = parent
|
||||
this.type = ELEMENT_PART
|
||||
this._$disconnectableChildren = void 0
|
||||
this._$parent = parent
|
||||
this.options = options
|
||||
}
|
||||
|
||||
$setValue() {}
|
||||
get _$isConnected() {
|
||||
return this._$parent._$isConnected
|
||||
}
|
||||
_$setValue(value) {}
|
||||
}
|
||||
|
||||
export function render(value, container, options = {}) {
|
||||
|
@ -727,7 +710,7 @@ export function render(value, container, options = {}) {
|
|||
)
|
||||
container[WC_PART] = part
|
||||
}
|
||||
part.$setValue(value, true)
|
||||
part._$setValue(value)
|
||||
|
||||
return part
|
||||
}
|
||||
|
|
215
src/index.js
215
src/index.js
|
@ -7,37 +7,21 @@ import {
|
|||
fixedValue,
|
||||
parsePropsDeclaration,
|
||||
boolMap,
|
||||
KEEP_ALIVE,
|
||||
KEEP_ALIVE_C,
|
||||
__finalized__,
|
||||
__props__,
|
||||
__changed_props__,
|
||||
__mounted__,
|
||||
__pending__
|
||||
__pending__,
|
||||
__children__
|
||||
} 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 { $, $$, 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 = ''
|
||||
|
@ -59,42 +43,6 @@ export function styleMap(data = {}) {
|
|||
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)
|
||||
}
|
||||
|
||||
export class Component extends HTMLElement {
|
||||
/**
|
||||
* 声明可监听变化的属性列表
|
||||
|
@ -109,7 +57,7 @@ export class Component extends HTMLElement {
|
|||
this[__props__].forEach((options, prop) => {
|
||||
list.push(options.attrName)
|
||||
})
|
||||
return list.concat(this.watches || [], KEEP_ALIVE)
|
||||
return list
|
||||
}
|
||||
|
||||
static parseAnim() {
|
||||
|
@ -129,7 +77,8 @@ export class Component extends HTMLElement {
|
|||
if (this[__mounted__]) {
|
||||
return animate.call(this, duration, fromto, out)
|
||||
}
|
||||
}
|
||||
},
|
||||
enumerable: false
|
||||
})
|
||||
this.prototype.$animate.immediate = immediate
|
||||
delete this.animation
|
||||
|
@ -147,10 +96,6 @@ 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()
|
||||
|
||||
|
@ -176,10 +121,6 @@ export class Component extends HTMLElement {
|
|||
}
|
||||
}
|
||||
|
||||
keepAlive = false
|
||||
|
||||
removed = false
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this[__pending__] = false
|
||||
|
@ -191,40 +132,37 @@ export class Component extends HTMLElement {
|
|||
this.root.ownHost = this
|
||||
|
||||
Object.defineProperty(this, '$refs', {
|
||||
value: Object.create(null)
|
||||
value: Object.create(null),
|
||||
enumerable: false
|
||||
})
|
||||
Object.defineProperty(this, '$events', {
|
||||
value: Object.create(null)
|
||||
value: Object.create(null),
|
||||
enumerable: false
|
||||
})
|
||||
|
||||
for (let [prop, options] of this.constructor[__props__]) {
|
||||
this.#createProperty(prop, options)
|
||||
// 按W3C规范, 在构造函数内不可设置节点的属性
|
||||
// 所以这里只记录需要初始化的属性, 在#init()回调中才去修改
|
||||
this[__changed_props__].set(prop, this[prop])
|
||||
this.createProperty(prop, options)
|
||||
this.$requestUpdate(prop)
|
||||
}
|
||||
|
||||
nextTick(_ => this.created())
|
||||
this.created()
|
||||
}
|
||||
|
||||
#createProperty(name, options) {
|
||||
createProperty(name, options) {
|
||||
let key = Symbol(name)
|
||||
let descriptor
|
||||
|
||||
if (options.type === Array || options.type === Object) {
|
||||
let proxyValue = this.#createProxy(null, options, name)
|
||||
let proxyValue = this.#createProxy(name, options)
|
||||
descriptor = {
|
||||
get() {
|
||||
return proxyValue
|
||||
},
|
||||
set(value) {
|
||||
proxyValue = this.#createProxy(
|
||||
fixedValue(value, options),
|
||||
options,
|
||||
name
|
||||
)
|
||||
proxyValue = this.#createProxy(name, options, value)
|
||||
this.$requestUpdate(name)
|
||||
}
|
||||
},
|
||||
enumerable: false
|
||||
}
|
||||
} else {
|
||||
descriptor = {
|
||||
|
@ -239,8 +177,11 @@ export class Component extends HTMLElement {
|
|||
}
|
||||
this[key] = value
|
||||
this.$requestUpdate(name)
|
||||
safely.call(this, options.observer, value, oldValue)
|
||||
}
|
||||
if (options.observer) {
|
||||
options.observer.call(this, value, oldValue)
|
||||
}
|
||||
},
|
||||
enumerable: false
|
||||
}
|
||||
this[key] = options.default
|
||||
}
|
||||
|
@ -248,33 +189,27 @@ export class Component extends HTMLElement {
|
|||
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)
|
||||
#createProxy(name, options, newValue) {
|
||||
return new Proxy(newValue || options.default, {
|
||||
set: (target, prop, value) => {
|
||||
if (prop === 'length' && options.type === Array) {
|
||||
return true
|
||||
}
|
||||
return value
|
||||
},
|
||||
set: (target, prop, value, receiver) => {
|
||||
let oldValue = target[prop]
|
||||
Reflect.set(target, prop, value, receiver)
|
||||
target[prop] = value
|
||||
|
||||
this.$requestUpdate(key)
|
||||
safely.call(this, options.observer, value, oldValue)
|
||||
this.$requestUpdate(name)
|
||||
if (options.observer) {
|
||||
options.observer.call(this, value, oldValue)
|
||||
}
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#init() {
|
||||
for (let [prop, value] of this[__changed_props__]) {
|
||||
this.#prop2attr(prop, value)
|
||||
}
|
||||
// 这里要清除初始化产生的记录
|
||||
this[__changed_props__].clear()
|
||||
// 这里重新赋值一次, 用于清除掉因为 observer 修正产生的变化
|
||||
this[__changed_props__] = new Map()
|
||||
this.$requestUpdate()
|
||||
}
|
||||
|
||||
|
@ -286,38 +221,32 @@ export class Component extends HTMLElement {
|
|||
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[__children__]?.setConnected(false)
|
||||
|
||||
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.unmounted()
|
||||
}
|
||||
// 监听属性变化
|
||||
attributeChangedCallback(name, old, val) {
|
||||
if (old === val) {
|
||||
return
|
||||
}
|
||||
if (name === KEEP_ALIVE) {
|
||||
this.keepAlive = val !== null
|
||||
return
|
||||
}
|
||||
this.#attr2prop(name, val, old)
|
||||
}
|
||||
|
||||
|
@ -328,10 +257,10 @@ export class Component extends HTMLElement {
|
|||
* @param value<String|Boolean|Number>
|
||||
*/
|
||||
#prop2attr(name, value) {
|
||||
let options = this.#getPropOptions(name) || {}
|
||||
let options = this.#getPropOptions(name)
|
||||
let attrName = options.attrName
|
||||
|
||||
if (options.attribute === false || options.type === null) {
|
||||
if (options.attribute === false) {
|
||||
this.removeAttribute(attrName)
|
||||
return
|
||||
}
|
||||
|
@ -371,18 +300,15 @@ export class Component extends HTMLElement {
|
|||
propName = camelize(name)
|
||||
|
||||
options = this.#getPropOptions(propName)
|
||||
value = fixedValue(value, options)
|
||||
|
||||
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
|
||||
}
|
||||
if (options.attribute === false) {
|
||||
if (value === null) {
|
||||
return
|
||||
}
|
||||
if (value === this[propName]) {
|
||||
this.removeAttribute(name)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -418,35 +344,28 @@ export class Component extends HTMLElement {
|
|||
if (this.$animate?.immediate) {
|
||||
this.$animate()
|
||||
}
|
||||
nextTick(_ => {
|
||||
if (this.keepAlive) {
|
||||
this.activated()
|
||||
}
|
||||
this.mounted()
|
||||
this.$requestUpdate()
|
||||
})
|
||||
if (this.__keep_alive__) {
|
||||
this.activated()
|
||||
}
|
||||
this.mounted()
|
||||
} else {
|
||||
nextTick(_ => this.updated(props))
|
||||
this.updated(props)
|
||||
}
|
||||
}
|
||||
|
||||
#clearUpdate() {
|
||||
this[__changed_props__].clear()
|
||||
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)
|
||||
}
|
||||
let ast = this.render()
|
||||
this[__children__] = render(ast, this.root, {
|
||||
host: this,
|
||||
isConnected: !this[__mounted__] && this.isConnected
|
||||
})
|
||||
}
|
||||
|
||||
// 几个生命周期回调
|
||||
created() {}
|
||||
mounted() {}
|
||||
|
|
71
src/utils.js
71
src/utils.js
|
@ -4,7 +4,7 @@
|
|||
* @date 2023/03/07 22:11:30
|
||||
*/
|
||||
|
||||
export function noop() {}
|
||||
function noop() {}
|
||||
|
||||
export function $(selector, container, multi) {
|
||||
let fn = multi ? 'querySelectorAll' : 'querySelector'
|
||||
|
@ -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,32 +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()
|
||||
|
@ -108,20 +79,14 @@ 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 isWc = 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 {
|
||||
|
@ -168,21 +133,11 @@ 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)
|
||||
}
|
||||
if (host.$events[t]) {
|
||||
host.$events[t].push({ el: dom, listener: callback, options: phase })
|
||||
} else {
|
||||
host.$events[t] = [{ el: dom, listener: callback, options: phase }]
|
||||
}
|
||||
_list.push({ el: dom, listener: callback, options: phase })
|
||||
}
|
||||
dom.addEventListener(t, callback, phase)
|
||||
})
|
||||
|
@ -192,7 +147,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)
|
||||
|
|
|
@ -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