add omi-ex

This commit is contained in:
张磊 2018-12-09 15:43:40 +08:00
parent 0fa2174102
commit 3be809fb42
18 changed files with 506 additions and 0 deletions

140
packages/omi-ex/.gitignore vendored Normal file
View File

@ -0,0 +1,140 @@
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
dist/
omi-ex.iml

21
packages/omi-ex/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

51
packages/omi-ex/README.md Normal file
View File

@ -0,0 +1,51 @@
# omi-ex
[Omi.js ts extension](https://github.com/rainmanhhh/omi-ex) by [rainmanhhh](https://github.com/rainmanhhh)
## Install
```
npm i omi-ex
```
### Usage
* Supports Router/Route(react-router like)
* Supports keepAlive
* Sharing data with subcomponents
* appData.routerData.query
* appData.routerData.params
* appData.routerData.data
```js
import {RouterData} from 'omi-ex'
export class AppData {
abc: string = ''
passToChild: string = 'from parent'
routerData: RouterData = new RouterData()
}
export const appData = new AppData()
```
```js
...
...
render(props: Omi.RenderableProps<AppProps>, data: AppData) {
return (
<div>
<div>
<a href={'#/'}>home</a>
<a href={'#/test'}>test</a>
</div>
<Router data={appData.routerData}>
<Route path={'/'} keepAlive={true}><Main/></Route>
<Route path={'/test'}><Test/></Route>
<Route path={'*'}>Not found</Route>
</Router>
</div>
)
}
...
```

View File

@ -0,0 +1,27 @@
{
"name": "omi-ex",
"version": "1.0.0",
"description": "omi extension",
"main": "dist/index.js",
"files": [
"dist"
],
"types": "dist/index.d.ts",
"author": "rainmanhhh <rainmanhhh@tom.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/rainmanhhh/omi-ex.git"
},
"scripts": {
"build": "tsc"
},
"devDependencies": {
"tslint": "^5.11.0",
"typescript": "^3.2.1"
},
"dependencies": {
"omi": "^5.0.9",
"omi-router": "^2.0.8"
}
}

View File

@ -0,0 +1,2 @@
export * from './route'
export * from './util'

View File

@ -0,0 +1,10 @@
export interface IRouteEvt {
query: {
[k: string]: string
},
params: {
[k: string]: string
},
data: any,
byNative: boolean
}

View File

@ -0,0 +1,29 @@
import {component, h} from '../util'
import * as Omi from 'omi'
import {WeElement} from 'omi'
export interface RouteProps {
path: string
keepAlive?: boolean
}
export interface InnerRouteProps extends RouteProps {
show?: boolean
}
@component('route')
export class Route extends WeElement<RouteProps> {
static noSlot = true
private get show() {
return (this.props as InnerRouteProps).show
}
render(props: Omi.RenderableProps<RouteProps>) {
if (props.keepAlive) {
// language=CSS
const style = this.show ? null : {display: 'none'}
return <div style={style}>{this.props.children}</div>
} else return this.show && this.props.children
}
}

View File

@ -0,0 +1,50 @@
import * as Omi from 'omi'
import {VNode, WeElement} from 'omi'
import {component} from '../util'
import {omiRoute} from './omiRoute'
import {IRouteEvt} from './IRouteEvt'
import {InnerRouteProps} from './Route'
export class RouterData implements IRouteEvt {
path: string = '/'
query: { [k: string]: string } = {}
params: { [k: string]: string } = {}
data: any = null
byNative: boolean = false
nodes: VNode[] = []
}
export interface RouterProps {
data: RouterData
}
@component('router')
export class Router extends WeElement<RouterProps> {
static observe = true
static noSlot = true
render(props: Omi.RenderableProps<RouterProps>) {
props.data.nodes.forEach(n => {
const routeProps = n.attributes as InnerRouteProps
routeProps.show = routeProps.path === props.data.path
})
return props.data.nodes
}
install() {
const children = this.props.children
const routerData = this.props.data
routerData.nodes = ((children instanceof Array) ? children : [children]) as VNode[]
routerData.nodes.forEach(n => {
const path = n.attributes.path
omiRoute(path, (evt: IRouteEvt) => {
routerData.path = path
routerData.params = evt.params
routerData.query = evt.query
routerData.data = evt.data
routerData.byNative = evt.byNative
})
})
if (!location.hash) omiRoute.to('/')
}
}

View File

@ -0,0 +1,4 @@
export * from './omiRoute'
export * from './Route'
export * from './Router'
export * from './IRouteEvt'

View File

@ -0,0 +1,4 @@
declare module 'omi-router' {
const route: any
export = route
}

View File

@ -0,0 +1,23 @@
import oRoute from 'omi-router'
import {IRouteEvt} from './IRouteEvt'
export interface IOmiRoute {
before: ((evt: IRouteEvt) => void) | (() => void)
after: ((evt: IRouteEvt) => void) | (() => void)
/**
*
* @param path
* @param data
*/
to(path: string, data?: any): void
/**
*
* @param path
* @param callback
*/
(path: string, callback: ((evt: IRouteEvt) => void) | (() => void)): void
}
export const omiRoute: IOmiRoute = oRoute

View File

@ -0,0 +1,3 @@
export interface IOmiComponent {
__omiComponentName: string
}

View File

@ -0,0 +1,15 @@
import {define, WeElementConstructor} from 'omi'
import {IOmiComponent} from './IOmiComponent'
export const COMPONENT_PREFIX = 'oc-'
export function component(name: string, pure?: boolean) {
return function (target: WeElementConstructor) {
const t = target as any as IOmiComponent & {
pure?: boolean
}
t.__omiComponentName = COMPONENT_PREFIX + name
t.pure = pure
define(t.__omiComponentName, target)
}
}

View File

@ -0,0 +1,15 @@
const classes = {
hide: 'oc-hide'
}
// language=CSS
const style = `
.${classes.hide} {
display: none;
}
`
export const css = {
classes,
style
}

View File

@ -0,0 +1,10 @@
import {IOmiComponent} from './IOmiComponent'
import {ComponentChildren, h as omiH, VNode} from 'omi'
export function h(node: string | IOmiComponent,
params: JSX.HTMLAttributes & JSX.SVGAttributes & Record<string, any> | null,
...children: ComponentChildren[]): VNode<any> {
const name = typeof node === 'string' ?
node : (node as IOmiComponent).__omiComponentName
return omiH(name, params, children)
}

View File

@ -0,0 +1,4 @@
export * from './component'
export * from './h'
export * from './IOmiComponent'
export * from './css'

View File

@ -0,0 +1,69 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es5",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"jsxFactory": "h",
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist",
/* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true,
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
"inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */
},
"include": [
"src/**/*"
]
}

View File

@ -0,0 +1,29 @@
{
"extends": ["tslint:recommended", "tslint-config-prettier"],
"linterOptions": {
"exclude": [
"config/**/*.js",
"node_modules/**/*.ts",
"coverage/lcov-report/*.js"
]
},
"rules": {
"interface-name": false,
"member-access": false,
"semicolon": false,
"curly": false,
"no-console": false,
"ordered-imports": false,
"no-var-requires": false,
"max-classes-per-file": false,
"member-ordering": false,
"object-literal-sort-keys": false,
"variable-name": false,
"radix": false,
"only-arrow-functions": false
},
"jsRules": {
"object-literal-sort-keys": false,
"no-console": false
}
}