refactor(core): add router

This commit is contained in:
qingwei.li 2017-02-18 11:41:33 +08:00 committed by cinwell.li
commit 30da0d5d46
17 changed files with 316 additions and 88 deletions

View file

@ -1,7 +1,7 @@
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
export function cached (fn) {
const cache = Object.create(null)
return function cachedFn (str) {
const hit = cache[str]
@ -10,11 +10,10 @@ function cached (fn) {
}
/**
* Camelize a hyphen-delimited string.
* Hyphenate a camelCase string.
*/
const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
export const hyphenate = cached(str => {
return str.replace(/([A-Z])/g, m => '-' + m.toLowerCase())
})
/**

View file

@ -10,22 +10,34 @@ const cacheNode = {}
*/
export function getNode (el, noCache = false) {
if (typeof el === 'string') {
el = noCache ? dom.find(el) : (cacheNode[el] || dom.find(el))
el = noCache ? find(el) : (cacheNode[el] || find(el))
}
return el
}
export const dom = {
body: document.body,
head: document.head,
find: node => document.querySelector(node),
findAll: node => document.querySelectorAll(node),
create: (node, tpl) => {
node = document.createElement(node)
if (tpl) node.innerHTML = tpl
},
appendTo: (target, el) => target.appendChild(el)
export const $ = document
export const body = $.body
export const head = $.head
export function find (node) {
return $.querySelector(node)
}
export function findAll (node) {
return [].clice.call($.querySelectorAll(node))
}
export function create (node, tpl) {
node = $.createElement(node)
if (tpl) node.innerHTML = tpl
return node
}
export function appendTo (target, el) {
return target.appendChild(el)
}
export function on (el, type, handler) {

View file

@ -1,3 +1,2 @@
export * from './core'
export * from './env'
export * from './dom'

View file

@ -1,22 +1,22 @@
import { dom } from '../dom'
import * as dom from '../dom'
import { get } from '../../fetch/ajax'
function replaceVar (block, themeColor) {
function replaceVar (block, color) {
block.innerHTML = block.innerHTML
.replace(/var\(\s*--theme-color.*?\)/g, themeColor)
.replace(/var\(\s*--theme-color.*?\)/g, color)
}
export default function (themeColor) {
export default function (color) {
// Variable support
if (window.CSS
&& window.CSS.supports
&& window.CSS.supports('(--foo: red)')) return
if (window.CSS &&
window.CSS.supports &&
window.CSS.supports('(--v:red)')) return
const styleBlocks = dom.findAll('style:not(.inserted),link')
;[].forEach.call(styleBlocks, block => {
if (block.nodeName === 'STYLE') {
replaceVar(block, themeColor)
replaceVar(block, color)
} else if (block.nodeName === 'LINK') {
const href = block.getAttribute('href')
@ -26,7 +26,7 @@ export default function (themeColor) {
const style = dom.create('style', res)
dom.head.appendChild(style)
replaceVar(style, themeColor)
replaceVar(style, color)
})
}
})