Commit 4501995c by 夏新然

app

0 parents
Showing 1000 changed files with 4826 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

<script>
export default {
onLaunch: function () {
uni.setStorage({
key:'statusBarH',
data:Number(window.location.href.split('=')[1])
})
},
onShow: function () {
console.log('App Show')
},
onHide: function () {
console.log('App Hide')
},
methods: {
}
}
</script>
<style>
.picker-title{
background: #0069FF!important;
}
body{
font-size: 25.36upx;
}
.littleTit{
overflow:hidden;
text-overflow:ellipsis;
-o-text-overflow:ellipsis;
-webkit-text-overflow:ellipsis;
-moz-text-overflow:ellipsis;
white-space:nowrap;
}
/*每个页面公共css */
</style>
<template>
<view>
<div :style="{ height: navheight + 'px',background:'#0069FF'}" ></div>
<view class="indexNav">
<text class="left" @tap="lClick">{{leftText}}</text>
<image :src="leftImgSrc" class="lImg"></image>
{{title}}
<span class="right" @tap="rClick">{{rightText}}</span>
</view>
</view>
</template>
<script>
export default{
data(){
return{
navheight:0
}
},
created(){
uni.getStorage({
key:'statusBarH',
success:(res)=>{
if(res.data){
this.navheight=res.data;
}
}
})
},
props:{
leftText:{
type:String,
default:''
},
rightText:{
type:String,
default:''
},
leftImgSrc:{
type:String,
default:''
},
rightText:{
type:String,
default:''
},
title:{
type:String,
default:''
}
},
methods: {
rClick() {
this.$emit('rightClick')
},
lClick(){
this.$emit('leftClick')
}
}
}
</script>
<style>
.indexNav{
height: 77.89upx;
line-height: 77.89upx;
text-align: center;
background: #0069FF;
position: relative;
font-size:33upx;
color:rgba(255,255,255,1);
}
.left{
float: left;
font-size:25.36upx;
display: inline-block;
height: 77.89upx;
line-height: 77.89upx;
padding-left: 23.55upx;
}
.right{
float: right;
font-size:25.36upx;
display: inline-block;
height: 77.89upx;
line-height: 77.89upx;
padding-right: 23.55upx;
}
.lImg{
width: 12.68upx;
height: 23.55upx;
float: left;
position: relative;
top: 27.17upx;
}
</style>
<template>
<view class="linechart">
<div :id='bindId' class="chart"></div>
</view>
</template>
<script>
export default {
data () {
return {
}
},
mounted() {
console.log('chartData',this.chartData)
},
watch:{
bindId:function(newValue,oldValue){
},
chartData:{
handler(newValue,oldValue){
this.drawLine();
},
deep:true
},
},
props:{
bindId:{
type:String,
default:''
},
chartData: {
type: Object,
default: function(){
return {}
}
}
},
methods: {
drawLine() {
let myChart = {};
let chartDom = document.getElementById(this.bindId);
myChart = this.echarts.init(chartDom);
myChart.showLoading('default', {
text: '',
color: '#409eff'
});
var option = {
title:{
show:true,
text:this.chartData.title,
left: '13px',
top: '13px',
textStyle: {
fontWeight: "normal",
fontSize: 14,
color: '#444'
}
},
backgroundColor: '#fff',
color: ["#0069FF", "#3BB8FF", "#6784e3", "#ff9631", "#ffc62e","#7460ee","#eb6100"],
tooltip: {
triggerOn: 'none',
position: function (pt) {
return [pt[0], 130];
}
},
grid: {
left: '50px',
right: '26px',
top: '50px',
bottom: '60px'
},
yAxis: {
scale: true,
axisLabel: {
textStyle: {
color: '#888'
}
},
axisLine : {
show: true,
lineStyle: {
color: '#888'
}
},
axisTick:{
show:false
},
splitLine:{
lineStyle: {
color: '#f5f5f5'
}
}
},
xAxis: {
axisTick:{
show:false
},
axisLine : {
show: true,
lineStyle: {
color: '#888'
}
},
axisLabel : {
textStyle: {
color: '#888'
}
},
splitLine : {
show: false
}
},
legend : {
orient: "horizontal",
x: "center",
textStyle: {
fontSize: 12,
},
itemWidth: 12,
itemHeight: 6,
itemGap: 10,
bottom: 2,
data: []
},
series:this.chartData.series
}
if(this.chartData.series.length>1){
this.chartData.series.forEach((item,index)=>{
var legendObj = {};
legendObj.name = item.name;
option.legend.data.push(legendObj);
item.areaStyle={
normal: {
color: new this.echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: option.color[index]
}, {
offset: 1,
color: option.color[index]
}])
}
}
})
}
option.xAxis.data = this.chartData.xaxis.data;
myChart.clear();
setTimeout(() => {
myChart.hideLoading();
}, 500);
myChart.setOption(option);
console.log(option)
}
}
}
</script>
<style>
.chart{
width:706.52upx;
height:438.4upx;
margin: 0 auto;
box-shadow:0px 0px 7px 0px rgba(0,0,0,0.14);
border-radius:4px;
background: #FFFFFF;
margin-bottom: 18.11upx;;
}
</style>
### Badge 数字角标
数字角标一般和其它控件(列表、9宫格等)配合使用,用于进行数量提示,默认为实心灰色背景,组件名:``uni-badge``,代码块: uBadge。
**使用方式:**
``script`` 中引用组件
```javascript
import uniBadge from "@/components/uni-badge/uni-badge.vue"
export default {
components: {uniBadge}
}
```
``template`` 中使用组件
```html
<uni-badge text="1"></uni-badge>
<uni-badge text="2" type="success" @click="bindClick"></uni-badge>
<uni-badge text="3" type="primary" :inverted="true"></uni-badge>
```
实际效果参考:[https://github.com/dcloudio/uni-ui](https://github.com/dcloudio/uni-ui)
**Badge 属性说明:**
|属性名 |类型 |默认值 |说明 |
|--- |---- |--- |--- |
|text |String |- |角标内容 |
|type |String |default|颜色类型,可选值:default(灰色)、primary(蓝色)、success(绿色)、warning(黄色)、error(红色) |
|size |String |normal|Badge 大小,可取值:normal、small|
|inverted |Boolean |false |是否无需背景颜色,为 true 时,背景颜色将变为文字的字体颜色 |
|@click |EventHandle| - |点击 Badge 触发事件 |
<template>
<text class="uni-badge" v-if="text" :class="setClass" @click="onClick()">{{text}}</text>
</template>
<script>
export default {
name: 'uni-badge',
props: {
type: {
type: String,
default: 'default'
},
inverted: {
type: Boolean,
default: false
},
text: {
type: String,
default: ''
},
size: { //small.normal
type: String,
default: 'normal'
}
},
computed: {
setClass() {
let classList = ['uni-badge-' + this.type, 'uni-badge--' + this.size];
if (this.inverted === true) {
classList.push('uni-badge-inverted')
}
return classList.join(" ")
}
},
methods: {
onClick() {
this.$emit('click')
}
}
}
</script>
<style lang="scss">
$bage-size:12px;
$bage-small:scale(0.8);
.uni-badge {
font-family: 'Helvetica Neue', Helvetica, sans-serif;
box-sizing: border-box;
font-size: $bage-size;
line-height: 1;
display: inline-block;
padding: 3px 6px;
color: $uni-text-color;
border-radius: 100px;
background-color: $uni-bg-color-hover;
&.uni-badge-inverted {
padding: 0 5px 0 0;
color: $uni-text-color-grey;
background-color: transparent;
}
&-primary {
color: $uni-text-color-inverse;
background-color: $uni-color-primary;
&.uni-badge-inverted {
color: $uni-color-primary;
background-color: transparent
}
}
&-success {
color: $uni-text-color-inverse;
background-color: $uni-color-success;
&.uni-badge-inverted {
color: $uni-color-success;
background-color: transparent
}
}
&-warning {
color: $uni-text-color-inverse;
background-color: $uni-color-warning;
&.uni-badge-inverted {
color: $uni-color-warning;
background-color: transparent
}
}
&-error {
color: $uni-text-color-inverse;
background-color: $uni-color-error;
&.uni-badge-inverted {
color: $uni-color-error;
background-color: transparent
}
}
&--small {
transform: $bage-small;
transform-origin: center center;
}
}
</style>
### Icon 图标
用于展示 icon,组件名:``uni-icon``,代码块: uIcon。
**使用方式:**
``script`` 中引用组件
```javascript
import uniIcon from "@/components/uni-icon/uni-icon.vue"
export default {
components: {uniIcon}
}
```
``template`` 中使用组件
```html
<uni-icon type="contact" size="30"></uni-icon>
```
实际效果参考:[https://github.com/dcloudio/uni-ui](https://github.com/dcloudio/uni-ui)
**Icon 属性说明:**
|属性名 |类型|默认值 |说明|
|---|----|---|---|
|type |String |-|图标图案,参考下表|
|color |String |-|图标颜色 |
|size |Number |24|图标大小|
|@click |EventHandle|-|点击 Icon 触发事件|
**type 类型:**
![icon](https://img-cdn-qiniu.dcloud.net.cn/img/icon.png)
\ No newline at end of file \ No newline at end of file
<template>
<view class="uni-list-cell" :class="[disabled === true || disabled === 'true' ? 'uni-list-cell--disabled' : '']"
:hover-class="disabled === true || disabled === 'true' || showSwitch === true || showSwitch === 'true' ? '' : 'uni-list-cell--hover'" @click="onClick">
<view class="uni-list-cell__container">
<view class="uni-list-cell__icon" v-if="thumb">
<image class="uni-list-cell__icon-img" :src="thumb"></image>
</view>
<view class="uni-list-cell__icon" v-else-if="showExtraIcon === true || showExtraIcon === 'true'">
<uni-icon :color="extraIcon.color" :size="extraIcon.size" :type="extraIcon.type"></uni-icon>
</view>
<view class="uni-list-cell__content">
<view class="uni-list-cell__content-title">{{title}}</view>
<view class="uni-list-cell__content-note" v-if="note">{{note}}</view>
</view>
<view class="uni-list-cell__extra" v-if="showBadge === true || showBadge === 'true' || showArrow === true || showArrow === 'true'||showSwitch === true || showSwitch === 'true'">
<uni-badge v-if="showBadge === true || showBadge === 'true'" :type="badgeType" :text="badgeText"></uni-badge>
<switch v-if="showSwitch === true || showSwitch === 'true'" :disabled='disabled' :checked="switchChecked" @change="onSwitchChange" />
<uni-icon v-if="showArrow === true || showArrow === 'true'" color="#bbb" size="20" type="arrowright"></uni-icon>
</view>
</view>
</view>
</template>
<script>
import uniIcon from '../uni-icon/uni-icon.vue'
import uniBadge from '../uni-badge/uni-badge.vue'
export default {
name: 'uni-list-item',
components: {
uniIcon,
uniBadge
},
data() {
return {
};
},
props: {
title: String, //列表标题
note: String, //列表描述
disabled: { //是否禁用
type: [Boolean, String],
default: false
},
showArrow: { //是否显示箭头
type: [Boolean, String],
default: true
},
showBadge: { //是否显示数字角标
type: [Boolean, String],
default: false
},
showSwitch: { //是否显示Switch
type: [Boolean, String],
default: false
},
switchChecked: { //Switch是否被选中
type: [Boolean, String],
default: false
},
badgeText: String, //badge内容
badgeType: { //badge类型
type: String,
default: 'success'
},
thumb: String, //缩略图
showExtraIcon: { //是否显示扩展图标
type: [Boolean, String],
default: false
},
extraIcon: {
type: Object,
default () {
return {
type: "contact",
color: "#000000",
size: "20"
};
}
}
},
methods: {
onClick() {
this.$emit('click')
},
onSwitchChange(e) {
this.$emit('switchChange', e.detail)
}
}
}
</script>
<style lang="scss">
@mixin list-hover {
background-color: $uni-bg-color-hover;
}
@mixin list-disabled {
opacity: 0.3;
}
$list-cell-pd:$uni-spacing-col-lg $uni-spacing-row-lg;
.uni-list-cell {
font-size: $uni-font-size-lg;
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
&--disabled {
@include list-disabled;
}
&--hover {
@include list-hover;
}
&__container {
padding: $list-cell-pd;
width: 100%;
box-sizing: border-box;
flex: 1;
position: relative;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
&:after {
position: absolute;
z-index: 3;
right: 0;
bottom: 0;
left: 30upx;
height: 1px;
content: '';
-webkit-transform: scaleY(.5);
transform: scaleY(.5);
background-color: $uni-border-color;
}
}
&__content {
flex: 1;
overflow: hidden;
display: flex;
flex-direction: column;
&-title {
font-size: $uni-font-size-lg;
text-overflow: ellipsis;
white-space: nowrap;
color: inherit;
line-height: 1.5;
overflow: hidden;
}
&-note {
color: $uni-text-color-grey;
font-size: $uni-font-size-base;
white-space: normal;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
}
&__extra {
width: 25%;
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: center;
}
&__icon {
margin-right: 18upx;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
&-img {
height: $uni-img-size-base;
width: $uni-img-size-base;
}
}
}
.uni-list>.uni-list-cell:last-child .uni-list-cell-container:after {
height: 0px;
}
</style>
\ No newline at end of file \ No newline at end of file
### List 列表
列表组件,组件名:``uni-list````uni-list-item``,代码块: uList。
**使用方式:**
``script`` 中引用组件
```javascript
import uniList from '@/components/uni-list/uni-list.vue'
import uniListItem from '@/components/uni-list-item/uni-list-item.vue'
export default {
components: {uniList,uniListItem}
}
```
List 一般用法
```html
<uni-list>
<uni-list-item title="标题文字" show-arrow="false"></uni-list-item>
<uni-list-item title="标题文字"></uni-list-item>
<uni-list-item title="标题文字" show-badge="true" badge-text="12"></uni-list-item>
<uni-list-item title="禁用状态" disabled="true" show-badge="true" badge-text="12"></uni-list-item>
</uni-list>
```
带描述信息
```html
<uni-list>
<uni-list-item title="标题文字" note="描述信息"></uni-list-item>
<uni-list-item title="标题文字" note="描述信息" show-badge="true" badge-text="12"></uni-list-item>
</uni-list>
```
包含图片
```html
<uni-list>
<uni-list-item title="标题文字" thumb="http://img-cdn-qiniu.dcloud.net.cn/new-page/hx.png"></uni-list-item>
</uni-list>
```
包含图标
```html
<uni-list>
<uni-list-item title="标题文字"
show-extra-icon="true"
:extra-icon="{color: '#4cd964',size: '22',type: 'spinner'}">
</uni-list-item>
</uni-list>
```
显示Switch
```html
<uni-list>
<uni-list-item title="标题文字" show-switch="true" show-arrow="false"></uni-list-item>
</uni-list>
```
实际效果参考:[https://github.com/dcloudio/uni-ui](https://github.com/dcloudio/uni-ui)
**uniListItem 属性说明:**
|属性名|类型|默认值 |说明|
|---|----|---|---|
|title|String|-|标题|
|note|String|-|描述|
|disabled|Boolean|false|是否禁用|
|show-arrow|Boolean|true|是否显示箭头图标|
|show-badge|Boolean|false|是否显示数字角标|
|badge-text|String|-|数字角标内容|
|badge-type|String|-|数字角标类型,参考[Badge 数字角标](https://ext.dcloud.net.cn/plugin?id=21)|
|show-switch|Boolean|false|是否显示Switch|
|switch-checked|Boolean|false|Switch是否被选中|
|show-extra-icon|Boolean|false|左侧是否显示扩展图标|
|extra-icon|Object|-|扩展图标参数,格式为 ``{color: '#4cd964',size: '22',type: 'spinner'}``,参考 [Iocn 图标](https://ext.dcloud.net.cn/plugin?id=28)|
|thumb|String|-|左侧缩略图,若thumb有值,则不会显示扩展图标|
**uniListItem 事件说明:**
|事件称名|说明|返回参数|
|---|----|---|
|click|点击 uniListItem 触发事件|-|
|switchChange|点击切换 Switch 时触发|{value:checked}|
<template>
<view class="uni-list">
<slot></slot>
</view>
</template>
<script>
export default {
name: 'uni-list'
}
</script>
<style lang="scss">
.uni-list {
background-color: $uni-bg-color;
position: relative;
width: 100%;
display: flex;
flex-direction: column;
&:after {
position: absolute;
z-index: 10;
right: 0;
bottom: 0;
left: 0;
height: 1px;
content: '';
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
background-color: $uni-border-color;
}
&:before {
position: absolute;
z-index: 10;
right: 0;
top: 0;
left: 0;
height: 1px;
content: '';
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
background-color: $uni-border-color;
}
}
</style>
<template>
<view class="piechart">
<div :id='bindId' class="chart"></div>
</view>
</template>
<script>
export default {
data () {
return {
}
},
mounted() {
},
watch:{
bindId:function(newValue,oldValue){
},
chartData:{
handler(newValue,oldValue){
this.drawPie();
},
deep:true
},
},
props:{
bindId:{
type:String,
default:''
},
chartData: {
type: Object,
default: function(){
return {}
}
}
},
methods: {
drawPie() {
let myChart = {};
let chartDom = document.getElementById(this.bindId);
myChart = this.echarts.init(chartDom);
myChart.showLoading('default', {
text: '',
color: '#409eff'
});
var itemDatas = [];
var option=this.chartData;
if(!option.series) return;
for(let i = 0, len = option.series.length;i < len; i++) {
itemDatas = option.series[i].data;
}
let legendData = [];
for(let i = 0, len = itemDatas.length;i < len; i++) {
legendData.push({
name: itemDatas[i].name,
icon: 'rect'
});
}
var opt = {
title:{
show:true,
text:this.chartData.title,
left: '13px',
top: '13px',
textStyle: {
fontWeight: "normal",
fontSize: 14,
color: '#444'
}
},
legend: {
orient: 'horizontal',
right: 'center',
itemWidth: 11,
itemHeight: 11,
bottom: '10',
left: 'center',
data: legendData
},
series: [{
type: 'pie',
color: ['#6e6fc1', '#33bafe', '#fec62b', '#ff9c01', '#38d4be', '#79ce4c'],
center: ['50%', '50%'],
radius: ['20%', '60%'],
label: {
normal: {
show: true,
position: 'outside',
formatter: '{b} {d}%'
},
emphasis: {
show: true
}
},
labelLine: {
normal: {
show: true
}
},
data: itemDatas
}]
};
myChart.clear();
setTimeout(() => {
myChart.hideLoading();
}, 500);
myChart.setOption(opt);
}
}
}
</script>
<style>
.chart{
width:706.52upx;
height:438.4upx;
margin: 0 auto;
box-shadow:0px 0px 7px 0px rgba(0,0,0,0.14);
border-radius:4px;
background: #FFFFFF;
margin-bottom: 18.11upx;;
}
</style>
<template>
<view class="piechart">
<div :id='bindId' class="chart"></div>
</view>
</template>
<script>
export default {
data () {
return {
}
},
mounted() {
console.log('chartData',this.chartData)
},
watch:{
bindId:function(newValue,oldValue){
},
chartData:{
handler(newValue,oldValue){
this.drawStackBar();
},
deep:true
},
},
props:{
bindId:{
type:String,
default:''
},
chartData: {
type: Object,
default: function(){
return {}
}
}
},
methods: {
drawStackBar() {
let myChart = {};
let chartDom = document.getElementById(this.bindId);
myChart = this.echarts.init(chartDom);
myChart.showLoading('default', {
text: '',
color: '#409eff'
});
let option = {
title :{
show:true,
text:this.chartData.title,
left: '13px',
top: '13px',
textStyle: {
fontWeight: "normal",
fontSize: 14,
color: '#444'
}
},
color: ["#0069FF", "#3BB8FF", "#87D14B", "#FFC62E", "#FF9631"],
grid: {
left: '50px',
right: '26px',
top: '55px',
bottom: '60px'
},
legend: {
data: [],
bottom: 12,
textStyle: {
color: '#555',
fontSize: 12
},
itemGap: 10,
itemWidth: 10,
itemHeight: 10
},
tooltip: {
trigger: 'axis',
backgroundColor: '#fff',
padding: [0, 0, 0, 0],
textStyle: {
color: '#333'
},
axisPointer: {
type: 'line',
animation: true,
lineStyle: {
color: 'transparent'
}
},
extraCssText: 'box-shadow: 0px 0px 10px -4px rgba(3, 3, 3, .4)'
},
yAxis: {
name: '人次',
type: 'value',
nameRotate: 1,
splitLine: {
lineStyle: {
color: '#EBEBEB'
}
},
axisLine: {
lineStyle: {
color: '#888'
}
},
axisTick: {
show: false
},
axisLabel: {
fontSize: 13,
color: '#666'
}
},
xAxis: {
splitLine: {
show: false
},
axisLine: {
lineStyle: {
color: '#888'
}
},
axisTick: {
show: false
},
axisLabel: {
fontSize: 13,
color: '#666'
},
data:[]
},
series:this.chartData.series
};
if(!option.series) return;
// 按照 echarts 数据规范重构数据
let seriesObj = {}, seriesData = [], totalData = [], totalNum = 0, ageArr = [];
try {
seriesData = this.chartData.xaxis.data.map(item => {
return {
name: item,
data: []
}
});
if(option.series.length > 0) {
let ageNum;
for(let i = 0; i < option.series.length; i++) {
ageNum = 0;
option.xAxis.data.push(option.series[i].name);
for(let j = 0; j < option.series[i].data.length; j++) {
seriesObj[this.chartData.xaxis.data[j]] = option.series[i].data[j];
totalNum += option.series[i].data[j];
ageNum += option.series[i].data[j];
for(let k in seriesObj) {
if(seriesData[j].name == k) {
seriesData[j].data.push(seriesObj[k])
}
}
seriesObj = {};
}
ageArr.push(ageNum);
}
}
for(let i = 0; i < seriesData.length; i++) {
seriesData[i].itemStyle = {
show: false
};
seriesData[i].type = 'bar';
seriesData[i].stack = 'gender';
// seriesData[i].barWidth = 20;
// seriesData[i].barCategoryGap = '50px';
option.legend.data.push(seriesData[i].name);
}
seriesData.forEach(item => {
item.data.forEach((k, i) => {
if(totalData[i]) {
totalData[i] += k;
} else {
totalData[i] = k;
}
})
})
option.series = seriesData;
if(!option.series.length) {
option.graphic = {
type: 'text',
left: 'center',
top: 'middle',
z: 100,
style: {
fill: '#333',
text: '无数据',
font: '14px'
}
}
// option.xAxis.data = [];
myChart.clear();
setTimeout(() => {
myChart.hideLoading();
myChart.setOption(option);
}, 500);
}
} catch (error) {}
option.tooltip.formatter = (params, ticket, callback) => {
let htmls = '', xaxisName = '', ratio = '', numRatio = '', ageNum = '', ageRatioNum = '', ageRatio = '', ageUnit = '', genderUnit = '', genderNum = '';
if(params.length > 0) {
xaxisName = params[0].axisValue;
ageNum = (ageArr[params[0].dataIndex] || ageArr[params[0].dataIndex] == 0) ? (ageArr[params[0].dataIndex] >= 100000 ? (ageArr[params[0].dataIndex] / 10000).toFixed(2) : ageArr[params[0].dataIndex]) : '--';
ageUnit = ageArr[params[0].dataIndex] ? ((ageArr[params[0].dataIndex] >= 100000) ? '万人' : '人') : '人';
ageRatioNum = ageArr[params[0].dataIndex] / totalNum;
ageRatio = ageRatioNum == 0 ? '0%' : (ageRatioNum * 100).toFixed(2) + '%';
htmls += '<div style="font-size:16px;height:32px;color:#0069FF;border-radius:4px;line-height:36px;padding-left:15px;padding-right:15px;text-align: left; overflow: hidden;"><span style="float: left; text-align: left;">' + xaxisName + '</span>';
htmls += '<span style="float: left; width: 60px; text-align: center; padding: 0 10px;">' + ageNum + ageUnit + '</span>';
htmls += '<span style="float: right; width: 60px; text-align: center;">' + ageRatio + '</span></div><div>';
for(let j = 0; j < params.length; j++) {
// totalNum
genderNum = (params[0].data || params[0].data == 0) ? (params[j].data >= 100000 ? (params[j].data / 10000).toFixed(2) : params[j].data) : '--';
numRatio = (params[j].data == 0 || totalData[params[j].dataIndex] == 0) ? 0 : params[j].data / totalData[params[j].dataIndex];
genderUnit = params[j].data ? (params[j].data >= 100000 ? '万人' : '人') : '人';
ratio = numRatio == 0 ? '0%' : (numRatio * 100).toFixed(2) + '%';
htmls += '<p style="font-size:14px;padding:4px 23px 6px 15px;color:#333;text-align: center; overflow: hidden;"><span style="float: left; text-align: center;">'+ params[j].seriesName + ':' + '</span>';
htmls += '<span style="float: right; text-align: center; width: 60px;">'+ ratio + '</span>';
htmls += '<span style="float: right; text-align: center; width: 60px;">'+ genderNum + genderUnit + '</span></p>';
}
htmls += '</div>';
return htmls;
}
}
console.log(option)
myChart.clear();
setTimeout(() => {
myChart.hideLoading();
}, 500);
myChart.setOption(option);
}
}
}
</script>
<style>
.chart{
width:706.52upx;
height:438.4upx;
margin: 0 auto;
box-shadow:0px 0px 7px 0px rgba(0,0,0,0.14);
border-radius:4px;
background: #FFFFFF;
margin-bottom: 18.11upx;;
}
</style>
<template>
<view>
<div style="position: relative;">
<slot></slot>
<div class="toast" v-show="toastShow">
<div class="toastContent">
<div class="arrow"></div>
<span class="typeBox" v-for="item in typeArr" @tap="itemClick(item.key)">{{item.name}}</span>
</div>
</div>
</div>
<div class="dialog" v-if="toastShow" @tap="$emit('update:toastShow', false)"></div>
</view>
</template>
<script>
export default{
data() {
return {
}
},
props: {
toastShow:{
type:Boolean,
default:false
},
typeArr: {
type: Array,
default:function(){
return [{
name:"**",
key:""
}]
}
},
},
watch: {
toastShow(newValue, oldValue) {
}
},
methods: {
itemClick(key) {
this.$emit('update:toastShow',false)
this.$emit('handleChange',key);
}
},
}
</script>
<style>
.toast{
position: absolute;
top: 36px;
left: 12px;
z-index: 1001;
box-shadow:0px 3.62upx 7.24upx 0px rgba(0,0,0,0.5);
}
.toastContent{
position: relative;
padding: 0 10.86upx;
background: #FFFFFF;
border-radius:7.24upx ;
}
.dialog{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000;
background: rgba(0,0,0,0.3);
}
.arrow{
border: 9.06upx solid;
width: 0;
height: 0;
border-color: transparent transparent #FFFFFF transparent;
position: absolute;
top: -18.11upx;
left: 25.36upx;
}
.typeBox{
padding: 19.92upx;
border-bottom: 1px solid #DBDBDB;
color: #000000;
font-size:25.37upx;
display: block;
line-height: normal;
}
.typeBox:last-child{
border-bottom: none;
}
.typeBox:active{
color: #C8C7CC;
}
</style>
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[**.js]
indent_style = space
indent_size = 4
[**.css]
indent_style = space
indent_size = 4
[**.less]
indent_style = space
indent_size = 4
[**.styl]
indent_style = space
indent_size = 4
[**.html]
indent_style = space
indent_size = 4
[**.tpl]
indent_style = space
indent_size = 4
[**.json]
indent_style = space
indent_size = 4
[*.md]
trim_trailing_whitespace = false
如果你想帮助 **ECharts** 的话,请首先阅读指导原则:
- 如果你希望提 bug:
- 清楚地描述问题,注意:**别人是否能通过你的描述理解这是什么问题**
- 说明版本(ECharts 版本,浏览器版本,设备、操作系统版本等)
- 最好提供完整的ECharts option,截图或线上实例(可以使用JSFiddle/JSBin/Codepen)。
- 如果你想问问题:
- 首先是否在这些文档中寻找过问题的答案:[option文档](http://echarts.baidu.com/option.html)[API文档](http://echarts.baidu.com/api.html)[教程](http://echarts.baidu.com/tutorial.html)
- 简单的问题,可以在QQ群中求助(群号:465958031)
- 如何取得能运行的 `ECharts option`
一个参考方式:
在你的程序的
```javascript
chart.setOption(option);
```
前加入这句话
```javascript
console.log(JSON.stringify(option, null, 4));
```
然后打开浏览器的调试工具(如 `Chrome Deverloper Tool`)的 `控制台(console)`,可以得到option输出。
<!--
为了方便我们能够复现和修复 bug,请遵从下面的规范描述您的问题。
-->
### One-line summary [问题简述]
### Version & Environment [版本及环境]
+ ECharts version [ECharts 版本]:
+ Browser version [浏览器类型和版本]:
+ OS Version [操作系统类型和版本]:
### Expected behaviour [期望结果]
### ECharts option [ECharts配置项]
<!-- Copy and paste your 'echarts option' here. -->
<!-- [下方贴你的option,注意不要删掉下方 ```javascript 和 尾部的 ``` 字样。最好是我们能够直接运行的 option。如何得到能运行的 option 参见上方的 guidelines for contributing] -->
```javascript
option = {
}
```
### Other comments [其他信息]
<!-- For example: Screenshot or Online demo -->
<!-- [例如,截图或线上实例 (JSFiddle/JSBin/Codepen)] -->
{
"bitwise": false,
"camelcase": true,
"curly": true,
"eqeqeq": false,
"forin": false,
"immed": true,
"latedef": false,
"newcap": true,
"noarg": false,
"noempty": true,
"nonew": true,
"plusplus": false,
"quotmark": "single",
"regexp": false,
"undef": true,
"unused": "vars",
"strict": false,
"trailing": false,
"maxparams": 20,
"maxdepth": 6,
"maxlen": 200,
"asi": false,
"boss": false,
"debug": false,
"eqnull": true,
"esversion": 6,
"module": true,
"evil": true,
"expr": true,
"funcscope": false,
"globalstrict": false,
"iterator": false,
"lastsemic": false,
"laxbreak": true,
"laxcomma": false,
"loopfunc": false,
"multistr": false,
"onecase": false,
"proto": false,
"regexdash": false,
"scripturl": false,
"smarttabs": false,
"shadow": true,
"sub": true,
"supernew": false,
"validthis": true,
"browser": true,
"couch": false,
"devel": true,
"dojo": false,
"jquery": true,
"mootools": false,
"node": false,
"nonstandard": false,
"prototypejs": false,
"rhino": false,
"wsh": false,
"nomen": false,
"onevar": false,
"passfail": false,
"white": false,
"predef": [
"global"
]
}
\ No newline at end of file \ No newline at end of file
{
"bitwise": false,
"camelcase": false,
"curly": true,
"eqeqeq": false,
"forin": false,
"immed": true,
"latedef": false,
"newcap": true,
"noarg": false,
"noempty": true,
"nonew": true,
"plusplus": false,
"quotmark": "single",
"regexp": false,
"undef": true,
"unused": "vars",
"strict": false,
"trailing": false,
"maxparams": 20,
"maxdepth": 6,
"maxlen": 200,
"asi": false,
"boss": false,
"debug": false,
"eqnull": true,
"esversion": 3,
"module": false,
"evil": true,
"expr": true,
"funcscope": false,
"globalstrict": false,
"iterator": false,
"lastsemic": false,
"laxbreak": true,
"laxcomma": false,
"loopfunc": false,
"multistr": false,
"onecase": false,
"proto": false,
"regexdash": false,
"scripturl": false,
"smarttabs": false,
"shadow": true,
"sub": true,
"supernew": false,
"validthis": true,
"browser": true,
"couch": false,
"devel": true,
"dojo": false,
"jquery": true,
"mootools": false,
"node": false,
"nonstandard": false,
"prototypejs": false,
"rhino": false,
"wsh": false,
"nomen": false,
"onevar": false,
"passfail": false,
"white": false,
"predef": [
"global"
]
}
\ No newline at end of file \ No newline at end of file
Wed Mar 06 2019 09:38:08 GMT+0800 (中国标准时间)
\ No newline at end of file \ No newline at end of file
This file contains the PGP keys of various developers.
Please don't use them for email unless you have to. Their main
purpose is code signing.
Examples of importing this file in your keystore:
gpg --import KEYS.txt
(need pgp and other examples here)
Examples of adding your key to this file:
pgp -kxa <your name> and append it to this file.
(pgpk -ll <your name> && pgpk -xa <your name>) >> this file.
(gpg --list-sigs <your name>
&& gpg --armor --export <your name>) >> this file.
---------------------------------------
pub rsa4096 2018-04-23 [SC]
9B06D9B4FA37C4DD52725742747985D7E3CEB635
uid [ultimate] Su Shuang (CODE SIGNING KEY) <sushuang@apache.org>
sig 3 747985D7E3CEB635 2018-04-23 Su Shuang (CODE SIGNING KEY) <sushuang@apache.org>
sub rsa4096 2018-04-23 [E]
sig 747985D7E3CEB635 2018-04-23 Su Shuang (CODE SIGNING KEY) <sushuang@apache.org>
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBFrd5SYBEADoCBw12lsK1sxn3r879jI50GhRAg5vF0aBql0h2BIJ3d+oYYSm
nIsK/XGpIk3t6ZhJRXK+le89t8a7vBsU+y0+3+OehxOV63du1wscQU9GPu7IfXhw
V4YcsGK330+V/GiwBs3EX808fdQrdkfCsaGEJhKJbK2fldUcnNp3M1Y2+DVZqGmb
I7fRJuEj/S9bcVGWnv40jBbMKjx/8LyP2dxZLyy1+whEUimU9em6Tj+SnyISe1I2
sLa3lwhWer0rkrz0siGFTgDHaDvLlpL9TV34acj/FOon3XKMtx4neNVmkC3QVi0z
PSlnX6EV8Fas9ylA4x9bdaUo6zUZKO533ASfC6uEibvE2XSRXYJ0xB2bThcQbkdl
332JqD1TkyF/UQRel3pUm/bCsv2daKD98ZO+eCbvNNonrip2qXDwJJ5HzlXlThyR
eN1Og90gXvYix4sbsZgNEIyYSaLri7/GjyMD34GCLQiV/kvc/foaC/hkvz6kVOiq
/tMHY3KsGYAIF4Z9kuTCwJOwFqgfb+Y15bPRDK84uyCiRhtIubNWY7Euy4bBd3ul
uazQ9LabBhZaa7HCOMssW+TaB+GondZJTiwnI6MCTJKrKtvb8kzcKR4mNf/dvF0O
x7zwVBeklMKXjkpOtje/+/XOYKuD3g1BZ/+vrfMFPTZ7y7ASC2ylcKI0/QARAQAB
tDJTdSBTaHVhbmcgKENPREUgU0lHTklORyBLRVkpIDxzdXNodWFuZ0BhcGFjaGUu
b3JnPokCTgQTAQoAOBYhBJsG2bT6N8TdUnJXQnR5hdfjzrY1BQJa3eUmAhsDBQsJ
CAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEHR5hdfjzrY13yIP+wS+Mh86IuIK+zG5
qr/cncV541RxvIGbv5uCQEbFRIwtR8SJEyx2tu4pIgsaTu93hdwxHFCcOZT2IsXP
meRWPfhaguDFQArdu4VdOfq2AbMqqByFWRsbwvF8CX8fGMPBCsMp0pzqp0px1uUr
WlK5hBSVwDHWACElyJE7jmk5K+O7RmDUD2E/pgXid+SiU8W+k9vWj49nHAhStYTm
SwVQA4Gl7jGCJY5jFwZIRD5/b8kVYjbJFl9CBDD2nOIytrGfMVlhp2OcT1f6yZvZ
oY2nvWLBUF0SmQzlli3EW9zzsNAXDu3f81kqwa+kC2WqQ3s4bKZKQurN5sCWvoyX
db+AWedArK+m3fH9y3JFIr5Lu1MwfbgfMfm9EZS4A+3DqLFIsLrmnzbGZ9FCkqsj
TuvKWOP2H365xH44gHImYKZ92PDdLKE7XArVU5b9qtAimgCDsCjEiXTB4S3NVJGX
R0RZCttKgnrLHwAad3TeLhktWcjH4TdxNCrNZsHLO9mklGyeM1IxKqba4OdHTmYX
tYYlixSlAu5vSPa+vDkILRfyU87n9YD9RiVGmvy27IP7wdxSClJun6+9fviU2NpG
FCkLZovYz8/Qht1c8yQZGscw3sa316m1nJz42Lo+p2s6AQZhZupu8bi/W85VHoxa
roRO16i+mFr4bnbo2/jftB6UVVo7uQINBFrd5SYBEACVsgwBHz5cpBqZQVNS6o0W
RUnWWNDiBYidNQNTWCF9NDF0HCh6oHecjjXQEPduvMPdzOPpawAkKMRG+7MlHiu/
ugAq0RluoM3QzDZwvCPw+p/NTESZMqLvbHXEs2u6YCdIsFcTLXr2d+JBWDeGri0S
YB4gjjQIVvDGqG0tDoW4JmqHHMZiJ6c+h2Rq+saHte0rctHcVAq4p5I8O1iJ1Mkg
gKJ/TBsjPM5aK6ahPpIPPh48nbhpsLjKHwqB/UWdUcB/HUDa0YfV4JbJilEeeQFZ
PzlP5SJaGyuEnTnhEwnoXpFetfMYi+Mxnc4VoSrQ3UOsVpD2Ii3haUjdKWTjukyn
o3sCxvsBTQ8jyBtjjhLw1jfWJdHJ2WCDGVtQVuJ6Gx1GCV0XRbKDTWdIBnCkdKtU
FY+VMt77oQ/ydeRsZDXhkdgBqqkvdiRHRyEFy72rx61cGTIKuKcWu0rJx8/LnVyi
nOEk8K8mgNR8omnpFmkkStOtSDLjDb8WeIdigxwJ4wtQnLlLGWiAAVNnDDsqgGIB
3rrR+/HKUa05CwKI1oIC7i4f7qkgfFUjjr1e496FDSq2tBTLukq/v5FpU6C0JSVq
MeD5+UuGtSezBxQUdxV7caftIptopwWnx4bBjWSuk2FVCzWcYMnXNIbtfEbqMKuS
mrpk4mOBNAV6XYzNcOHQqwARAQABiQI2BBgBCgAgFiEEmwbZtPo3xN1ScldCdHmF
1+POtjUFAlrd5SYCGwwACgkQdHmF1+POtjXK4g//c7vJXmN0FtACspBJVrgsKrYj
ha4c2PCEynfKSwhVXW3yHnQMwh8/bpQUs5bwCTWx27IEeBrfb03/X9tlx12koGvl
LujaR7IP6xaqWpbh6rrfttOKGx3xKopJ4nHgNPIYN/ApflAacwyOd+/leWOjHrii
JXbB60oc7FNvfQRREICLZyeAnzlAcEOVcWvBTngB0EDUZucKwkQtt0x3YvKetgQf
EMFBAH4RUXG0ms85acX2rpi/kbdarFv6Hc2pzakoWDKNjHMMae1J8wQbPRaXx1NB
+xF362eLXZaxtvKdzs9Q03R46DY9cyQRofG5WNnZapgemEzPgixur8FYK5EPCQkh
Y2FA0WUbZFIkO7pE7UNS5ZN5fHkkEhAFo4wV0uqWRVBpFrjKeBxtRkIaw7jLCHr5
3EpkTusjT/529rEYIq9cGOTwf75AbKR1IZFxffEZYOU76y6SH0bINoYp0VxFJ/IR
zy5CHqvyUQVUed5O/7UzkYx0IVBGk2wSwOtC7+iRptqj+kI9RCjGizhNe4hG3SUq
1qkUGkQu6+skyXeFCR1PIAbQgleRNUQotsh/rfsfZpQOomBdvDRPT8ZcN5bjUIJ1
5c4abryWPkun+BgZk+YFtYLbGZVJAUy2OtXRG5uYzeLc5ID+X5XwwtZOO4gSWMTh
oQH7TsthVKvdZyjtZQg=
=Uv8d
-----END PGP PUBLIC KEY BLOCK-----
Apache ECharts (incubating)
Copyright 2017-2018 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
# ECharts
<a href="http://echarts.baidu.com">
<img style="vertical-align: top;" src="./asset/logo.png?raw=true" alt="logo" height="50px">
</a>
ECharts is a free, powerful charting and visualization library offering an easy way of adding intuitive, interactive, and highly customizable charts to your commercial products. It is written in pure JavaScript and based on <a href="https://github.com/ecomfe/zrender">zrender</a>, which is a whole new lightweight canvas library.
Now ECharts is an incubator project of Apache Software Foundation.
Please check its incubator status [here](http://incubator.apache.org/projects/echarts.html)
**[中文官网](http://echarts.baidu.com)** | **[ENGLISH HOMEPAGE](http://ecomfe.github.io/echarts-doc/public/en/index.html)**
## Get ECharts
+ Download [中文](http://echarts.baidu.com/download.html)
+ Download [English](https://ecomfe.github.io/echarts-doc/public/en/download.html)
+ `npm install echarts --save`
## Get ECharts GL
ECharts-GL is an extension pack of ECharts, which provides 3D plots, globe visualization and WebGL acceleration.
+ Get from [https://github.com/ecomfe/echarts-gl](https://github.com/ecomfe/echarts-gl)
+ `npm install echarts-gl --save`
## Docs
+ [Tutorial](http://echarts.baidu.com/tutorial.html)
+ [中文](http://echarts.baidu.com/tutorial.html)
+ [English](http://ecomfe.github.io/echarts-doc/public/en/tutorial.html)
+ [API](http://echarts.baidu.com/api.html)
+ [中文](http://echarts.baidu.com/api.html)
+ [English](http://ecomfe.github.io/echarts-doc/public/en/api.html)
+ [Option Manual](http://echarts.baidu.com/option.html)
+ [中文](http://echarts.baidu.com/option.html)
+ [English](http://ecomfe.github.io/echarts-doc/public/en/option.html)
## Resources
### Awesome ECharts
[https://github.com/ecomfe/awesome-echarts](https://github.com/ecomfe/awesome-echarts)
### Official Extensions
+ [水球图 Liquidfill](https://github.com/ecomfe/echarts-liquidfill)
+ [字符云 Wordcloud](https://github.com/ecomfe/echarts-wordcloud)
+ [Graph Modularity](https://github.com/ecomfe/echarts-graph-modularity) Graph modularity extension for community detection
+ [百度地图扩展](https://github.com/ecomfe/echarts/tree/master/extension/bmap)
+ [vue-echarts](https://github.com/ecomfe/vue-echarts) ECharts component for Vue.js
+ [echarts-stat](https://github.com/ecomfe/echarts-stat) Statistics tool for ECharts
### Developers Contributions
#### GIS
+ [leaflet-echarts](https://github.com/wandergis/leaflet-echarts3) by wandergis
+ [arcgis-echarts](https://github.com/wandergis/arcgis-echarts3) by wandergis
+ [echarts-leaflet](https://github.com/gnijuohz/echarts-leaflet) by gnijuohz
+ [ol3Echarts](https://github.com/sakitam-fdd/ol3Echarts) by sakitam-fdd
#### AngularJS Binding
+ [angular-echarts](https://github.com/wangshijun/angular-echarts) by wangshijun
+ [echarts-ng](https://github.com/bornkiller/echarts-ng) by bornkiller
+ [ng-echarts](https://github.com/liekkas/ng-echarts) by liekkas
+ [ngx-echarts](https://github.com/xieziyu/ngx-echarts) by xieziyu
#### Ember Binding
+ [echarts-ember](https://github.com/bruckwubete/echarts-ember) by [bruck wubete](https://github.com/bruckwubete)
+ [ember-cli-echarts](https://github.com/funnelcloudinc/ember-cli-echarts) by FunnelCloud
#### Vue Component
+ [vue-echarts](https://github.com/panteng/vue-echarts) by panteng
+ [vue-echarts-v3](https://github.com/xlsdg/vue-echarts-v3) by xlsdg
#### React Component
+ [echarts-for-react](https://github.com/hustcc/echarts-for-react) by hustcc
+ [react-echarts](https://github.com/somonus/react-echarts) by somonus
+ [re-echarts](https://github.com/liekkas/re-echarts) by liekkas
+ [react-echarts-v3](https://github.com/xlsdg/react-echarts-v3) by xlsdg
+ [d2recharts](https://github.com/leungwensen/d2recharts) by leungwensen
#### React Native Component
+ [react-native-echarts](https://github.com/somonus/react-native-echarts) by somonus
### Other Languages
#### Python
+ [echarts-python](https://github.com/yufeiminds/echarts-python) by yufeiminds
+ [krisk](https://github.com/napjon/krisk) by napjon
+ [pyecharts](https://github.com/chenjiandongx/pyecharts) by chenjiandong
#### R
+ [recharts](https://github.com/taiyun/recharts) by taiyun
+ [recharts](https://github.com/yihui/recharts) by yihui
+ [ECharts2Shiny](https://github.com/XD-DENG/ECharts2Shiny) by XD-DENG
#### Julia
+ [ECharts.jl](https://github.com/randyzwitch/ECharts.jl) by randyzwitch
#### PureScript
+ [purescript-echarts](https://github.com/slamdata/purescript-echarts/)
#### iOS
+ [iOS-Echarts](https://github.com/Pluto-Y/iOS-Echarts) by Pluto-Y
#### Java
+ [ECharts-Java](http://www.oschina.net/p/echarts-java) by Liuzh_533
#### .NET
+ [EChartsSDK](https://github.com/idoku/EChartsSDK) by idoku
#### PHP
+ [Echarts-PHP](https://github.com/hisune/Echarts-PHP) by hisune
#### Node
+ [Node-Echarts](https://github.com/suxiaoxin/node-echarts) by suxiaoxin
## Build
Check this tutorial [Create Custom Build of ECharts](https://ecomfe.github.io/echarts-doc/public/en/tutorial.html#Create%20Custom%20Build%20of%20ECharts)
please.
## License
ECharts is available under the Apache License V2.
{
"bitwise": false,
"camelcase": true,
"curly": true,
"eqeqeq": false,
"forin": false,
"immed": true,
"latedef": false,
"newcap": true,
"noarg": false,
"noempty": true,
"nonew": true,
"plusplus": false,
"quotmark": "single",
"regexp": false,
"undef": true,
"unused": "vars",
"strict": false,
"trailing": false,
"maxparams": 20,
"maxdepth": 6,
"maxlen": 200,
"asi": false,
"boss": false,
"debug": false,
"eqnull": true,
"esversion": 6,
"evil": true,
"expr": true,
"funcscope": false,
"globalstrict": false,
"iterator": false,
"lastsemic": false,
"laxbreak": true,
"laxcomma": false,
"loopfunc": false,
"multistr": false,
"onecase": false,
"proto": false,
"regexdash": false,
"scripturl": false,
"smarttabs": false,
"shadow": true,
"sub": true,
"supernew": false,
"validthis": true,
"browser": true,
"couch": false,
"devel": true,
"dojo": false,
"jquery": true,
"mootools": false,
"node": false,
"nonstandard": false,
"prototypejs": false,
"rhino": false,
"wsh": false,
"nomen": false,
"onevar": false,
"passfail": false,
"white": false,
"varstmt": true,
"predef": [
"__DEV__",
"global",
"require",
"exports",
"Buffer",
"module",
"__dirname"
]
}
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const glob = require('glob');
const fs = require('fs');
const headerStr = `/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
`;
const lists = [
'../src/**/*.js',
'../build/*.js',
'../benchmark/src/*.js',
'../benchmark/src/gulpfile.js',
'../extension-src/**/*.js',
'../extension/**/*.js',
'../map/js/**/*.js',
'../test/build/**/*.js',
'../test/node/**/*.js',
'../test/ut/core/*.js',
'../test/ut/spe/*.js',
'../test/ut/ut.js',
'../test/*.js',
'../theme/*.js',
'../theme/tool/**/*.js',
'../echarts.all.js',
'../echarts.blank.js',
'../echarts.common.js',
'../echarts.simple.js',
'../index.js',
'../index.common.js',
'../index.simple.js'
];
function extractLicense(str) {
str = str.trim();
const regex = new RegExp('/\\*[\\S\\s]*?\\*/', 'm');
const res = regex.exec(str);
const commentText = res && res[0];
if (commentText) {
if(commentText.toLowerCase().includes('apache license') || commentText.toLowerCase().includes('apache commons')) {
return 'Apache';
}
else if(commentText.toUpperCase().includes('BSD')) {
return 'BSD';
}
else if(commentText.toUpperCase().includes('LGPL')) {
return 'LGPL';
}
else if(commentText.toUpperCase().includes('GPL')) {
return 'GPL';
}
else if(commentText.toLowerCase().includes('mozilla public')) {
return 'Mozilla';
}
else if(commentText.toLowerCase().includes('mit license')) {
return 'MIT';
}
}
}
lists.forEach(function (pattern) {
glob(pattern, function (err, fileList) {
if (err) {
throw new Error();
}
fileList.forEach(function (fileUrl) {
const str = fs.readFileSync(fileUrl, 'utf-8');
const existLicense = extractLicense(str);
if (existLicense) {
console.log('File ' + fileUrl + ' already have license ' + existLicense);
return;
}
fs.writeFileSync(fileUrl, headerStr + str, 'utf-8');
});
});
});
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var glob = require('glob');
var fsExtra = require('fs-extra');
var esprima = require('esprima');
function run(cb) {
glob('**/*.js', {
cwd: __dirname + '/../src/'
}, function (err, files) {
files.forEach(function (filePath) {
var code = parse(fsExtra.readFileSync(
__dirname + '/../src/' + filePath, 'utf-8'));
code = code.replace(/require\(([\'"])zrender\//g, 'require($1zrender/lib/');
fsExtra.outputFileSync(
__dirname + '/../lib/' + filePath,
code, 'utf-8');
});
cb && cb();
});
}
if (require.main === module) {
run();
}
else {
module.exports = run;
}
var MAGIC_DEPS = {
'exports' : true,
'module' : true,
'require' : true
};
var SIMPLIFIED_CJS = ['require', 'exports', 'module'];
// Convert AMD-style JavaScript string into node.js compatible module
function parse (raw){
var output = '';
var ast = esprima.parse(raw, {
range: true,
raw: true
});
var defines = ast.body.filter(isDefine);
if ( defines.length > 1 ){
throw new Error('Each file can have only a single define call. Found "'+ defines.length +'"');
} else if (!defines.length){
return raw;
}
var def = defines[0];
var args = def.expression['arguments'];
var factory = getFactory( args );
var useStrict = getUseStrict( factory );
// do replacements in-place to avoid modifying the code more than needed
if (useStrict) {
output += useStrict.expression.raw +';\n';
}
output += raw.substring( 0, def.range[0] ); // anything before define
output += getRequires(args, factory); // add requires
output += getBody(raw, factory.body, useStrict); // module body
output += raw.substring( def.range[1], raw.length ); // anything after define
return output;
}
function getRequires(args, factory){
var requires = [];
var deps = getDependenciesNames( args );
var params = factory.params.map(function(param, i){
return {
name : param.name,
// simplified cjs doesn't have deps
dep : (deps.length)? deps[i] : SIMPLIFIED_CJS[i]
};
});
params.forEach(function(param){
if ( MAGIC_DEPS[param.dep] && !MAGIC_DEPS[param.name] ) {
// if user remaped magic dependency we declare a var
requires.push( 'var '+ param.name +' = '+ param.dep +';' );
} else if ( param.dep && !MAGIC_DEPS[param.dep] ) {
// only do require for params that have a matching dependency also
// skip "magic" dependencies
requires.push( 'var '+ param.name +' = require(\''+ param.dep +'\');' );
}
});
return requires.join('\n');
}
function getDependenciesNames(args){
var deps = [];
var arr = args.filter(function(arg){
return arg.type === 'ArrayExpression';
})[0];
if (arr) {
deps = arr.elements.map(function(el){
return el.value;
});
}
return deps;
}
function isDefine(node){
return node.type === 'ExpressionStatement' &&
node.expression.type === 'CallExpression' &&
node.expression.callee.type === 'Identifier' &&
node.expression.callee.name === 'define';
}
function getFactory(args){
return args.filter(function(arg){
return arg.type === 'FunctionExpression';
})[0];
}
function getBody(raw, factoryBody, useStrict){
var returnStatement = factoryBody.body.filter(function(node){
return node.type === 'ReturnStatement';
})[0];
var body = '';
var bodyStart = useStrict ? useStrict.expression.range[1] + 1 : factoryBody.range[0] + 1;
if (returnStatement) {
body += raw.substring( bodyStart, returnStatement.range[0] );
// "return ".length === 7 so we add "6" to returnStatement start
body += 'module.exports ='+ raw.substring( returnStatement.range[0] + 6, factoryBody.range[1] - 1 );
} else {
// if using exports or module.exports or just a private module we
// simply return the factoryBody content
body = raw.substring( bodyStart, factoryBody.range[1] - 1 );
}
return body;
}
function getUseStrict(factory){
return factory.body.body.filter(isUseStrict)[0];
}
function isUseStrict(node){
return node.type === 'ExpressionStatement' &&
node.expression.type === 'Literal' &&
node.expression.value === 'use strict';
}
#!/usr/bin/env node
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const fsExtra = require('fs-extra');
const fs = require('fs');
const {resolve} = require('path');
const config = require('./config.js');
const commander = require('commander');
const {build, watch, color} = require('zrender/build/helper');
const ecLangPlugin = require('./rollup-plugin-ec-lang');
const prePublish = require('./pre-publish');
const recheckDEV = require('zrender/build/babel-plugin-transform-remove-dev').recheckDEV;
function run() {
/**
* Tips for `commander`:
* (1) If arg xxx not specified, `commander.xxx` is undefined.
* Otherwise:
* If '-x, --xxx', `commander.xxx` can only be true/false, even if '--xxx yyy' input.
* If '-x, --xxx <some>', the 'some' string is required, or otherwise error will be thrown.
* If '-x, --xxx [some]', the 'some' string is optional, that is, `commander.xxx` can be boolean or string.
* (2) `node ./build/build.js --help` will print helper info and exit.
*/
let descIndent = ' ';
let egIndent = ' ';
commander
.usage('[options]')
.description([
'Build echarts and generate result files in directory `echarts/dist`.',
'',
' For example:',
'',
egIndent + 'node build/build.js --release'
+ '\n' + descIndent + '# Build all to `dist` folder.',
egIndent + 'node build/build.js --prepublish'
+ '\n' + descIndent + '# Only prepublish.',
egIndent + 'node build/build.js --removedev'
+ '\n' + descIndent + '# Remove __DEV__ code. If --min, __DEV__ always be removed.',
egIndent + 'node build/build.js --type ""'
+ '\n' + descIndent + '# Only generate `dist/echarts.js`.',
egIndent + 'node build/build.js --type common --min'
+ '\n' + descIndent + '# Only generate `dist/echarts.common.min.js`.',
egIndent + 'node build/build.js --type simple --min --lang en'
+ '\n' + descIndent + '# Only generate `dist/echarts-en.simple.min.js`.',
egIndent + 'node build/build.js --lang "my/lang.js" -i "my/index.js" -o "my/bundle.js"'
+ '\n' + descIndent + '# Take `<cwd>/my/index.js` as input and generate `<cwd>/my/bundle.js`,'
+ '\n' + descIndent + 'where `<cwd>/my/lang.js` is used as language file.',
].join('\n'))
.option(
'-w, --watch', [
'Watch modifications of files and auto-compile to dist file. For example,',
descIndent + '`echarts/dist/echarts.js`.'
].join('\n'))
.option(
'--lang <language file path or shortcut>', [
'Use the specified file instead of `echarts/src/lang.js`. For example:',
descIndent + '`--lang en` will use `echarts/src/langEN.js`.',
descIndent + '`--lang my/langDE.js` will use `<cwd>/my/langDE.js`. -o must be specified in this case.',
descIndent + '`--lang /my/indexSW.js` will use `/my/indexSW.js`. -o must be specified in this case.'
].join('\n'))
.option(
'--release',
'Build all for release'
)
.option(
'--prepublish',
'Build all for release'
)
.option(
'--removedev',
'Remove __DEV__ code. If --min, __DEV__ always be removed.'
)
.option(
'--min',
'Whether to compress the output file, and remove error-log-print code.'
)
.option(
'--type <type name>', [
'Can be "simple" or "common" or "" (default). For example,',
descIndent + '`--type ""` or `--type "common"`.'
].join('\n'))
.option(
'--sourcemap',
'Whether output sourcemap.'
)
.option(
'--format <format>',
'The format of output bundle. Can be "umd", "amd", "iife", "cjs", "es".'
)
.option(
'-i, --input <input file path>',
'If input file path is specified, output file path must be specified too.'
)
.option(
'-o, --output <output file path>',
'If output file path is specified, input file path must be specified too.'
)
.parse(process.argv);
let isWatch = !!commander.watch;
let isRelease = !!commander.release;
let isPrePublish = !!commander.prepublish;
let opt = {
lang: commander.lang,
min: commander.min,
type: commander.type || '',
input: commander.input,
output: commander.output,
format: commander.format,
sourcemap: commander.sourcemap,
removeDev: commander.removedev,
addBundleVersion: isWatch
};
validateIO(opt.input, opt.output);
validateLang(opt.lang, opt.output);
normalizeParams(opt);
// Clear `echarts/dist`
if (isRelease) {
fsExtra.removeSync(getPath('./dist'));
}
if (isWatch) {
watch(config.createECharts(opt));
}
else if (isPrePublish) {
prePublish();
}
else if (isRelease) {
let configs = [];
let configForCheck;
[
{min: false},
{min: true},
{min: false, lang: 'en'},
{min: true, lang: 'en'}
].forEach(function (opt) {
['', 'simple', 'common'].forEach(function (type) {
let singleOpt = Object.assign({type}, opt);
normalizeParams(singleOpt);
let singleConfig = config.createECharts(singleOpt);
configs.push(singleConfig);
if (singleOpt.min && singleOpt.type === '') {
configForCheck = singleConfig;
}
});
});
configs.push(
config.createBMap(false),
config.createBMap(true),
config.createDataTool(false),
config.createDataTool(true)
);
build(configs)
.then(function () {
checkCode(configForCheck);
prePublish();
}).catch(handleBuildError);
}
else {
let cfg = config.createECharts(opt);
build([cfg])
.then(function () {
if (opt.removeDev) {
checkCode(cfg);
}
})
.catch(handleBuildError);
}
}
function normalizeParams(opt) {
if (opt.sourcemap == null) {
opt.sourcemap = !(opt.min || opt.type);
}
if (opt.removeDev == null) {
opt.removeDev = !!opt.min;
}
}
function handleBuildError(err) {
console.log(err);
}
function checkCode(singleConfig) {
// Make sure __DEV__ is eliminated.
let code = fs.readFileSync(singleConfig.output.file, {encoding: 'utf-8'});
if (!code) {
throw new Error(`${singleConfig.output.file} is empty`);
}
recheckDEV(code);
console.log(color('fgGreen', 'dim')('Check code: correct.'));
}
function validateIO(input, output) {
if ((input != null && output == null)
|| (input == null && output != null)
) {
throw new Error('`input` and `output` must be both set.');
}
}
function validateLang(lang, output) {
if (!lang) {
return;
}
let langInfo = ecLangPlugin.getLangFileInfo(lang);
if (langInfo.isOuter && !output) {
throw new Error('`-o` or `--output` must be specified if using a file path in `--lang`.');
}
if (!langInfo.absolutePath || !fs.statSync(langInfo.absolutePath).isFile()) {
throw new Error(`File ${langInfo.absolutePath} does not exist yet. Contribution is welcome!`);
}
}
/**
* @param {string} relativePath Based on echarts directory.
* @return {string} Absolute path.
*/
function getPath(relativePath) {
return resolve(__dirname, '../', relativePath);
}
run();
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const nodeResolvePlugin = require('rollup-plugin-node-resolve');
const uglifyPlugin = require('rollup-plugin-uglify');
const ecRemoveDevPlugin = require('./rollup-plugin-ec-remove-dev');
const ecLangPlugin = require('./rollup-plugin-ec-lang');
const {resolve} = require('path');
const preamble = require('./preamble');
function getPathBasedOnECharts(path) {
return resolve(__dirname, '../', path);
}
function getPlugins({min, lang, sourcemap, removeDev, addBundleVersion}) {
let plugins = [];
removeDev && plugins.push(
ecRemoveDevPlugin({sourcemap})
);
lang && plugins.push(
ecLangPlugin({lang})
);
plugins.push(
nodeResolvePlugin()
);
addBundleVersion && plugins.push({
outro: function () {
return 'exports.bundleVersion = \'' + (+new Date()) + '\';';
}
});
min && plugins.push(uglifyPlugin({
compress: {
// Eliminate __DEV__ code.
// Currently, in uglify:
// `var vx; if(vx) {...}` can not be removed.
// `if (__DEV__) {...}` can be removed if `__DEV__` is defined as `false` in `global_defs`.
// 'global_defs': {
// __DEV__: false
// },
'dead_code': true
},
output: {
preamble: preamble
}
}));
return plugins;
}
/**
* @param {Object} [opt]
* @param {string} [opt.type=''] '' or 'simple' or 'common'
* @param {boolean} [opt.min=false]
* @param {string} [opt.lang=undefined] null/undefined/'' or 'en' or 'fi' or a file path.
* @param {string} [opt.input=undefined] If set, `opt.output` is required too, and `opt.type` is ignored.
* @param {string} [opt.output=undefined] If set, `opt.input` is required too, and `opt.type` is ignored.
* @param {boolean} [opt.sourcemap] If set, `opt.input` is required too, and `opt.type` is ignored.
* @param {boolean} [opt.removeDev]
* @param {string} [opt.format='umd'] If set, `opt.input` is required too, and `opt.type` is ignored.
* @param {boolean} [opt.addBundleVersion=false] Only for debug in watch, prompt that the two build is different.
*/
exports.createECharts = function (opt = {}) {
let min = opt.min;
let srcType = opt.type ? '.' + opt.type : '.all';
let postfixType = opt.type ? '.' + opt.type : '';
let postfixMin = min ? '.min' : '';
let postfixLang = opt.lang ? '-' + opt.lang.toLowerCase() : '';
let input = opt.input;
let output = opt.output;
let sourcemap = opt.sourcemap;
let format = opt.format || 'umd';
if (input != null || output != null) {
// Based on process.cwd();
input = resolve(input);
output = resolve(output);
}
else {
input = getPathBasedOnECharts(`./echarts${srcType}.js`);
output = getPathBasedOnECharts(`dist/echarts${postfixLang}${postfixType}${postfixMin}.js`);
}
return {
plugins: getPlugins(opt),
input: input,
legacy: true, // Support IE8-
output: {
name: 'echarts',
format: format,
sourcemap: sourcemap,
legacy: true, // Must be declared both in inputOptions and outputOptions.
file: output
},
watch: {
include: [
getPathBasedOnECharts('./src/**'),
getPathBasedOnECharts('./echarts*.js'),
getPathBasedOnECharts('../zrender/src/**')
]
}
};
};
/**
* @param {boolean} [min=false]
*/
exports.createBMap = function (min) {
let postfix = min ? '.min' : '';
return {
plugins: getPlugins({min}),
input: getPathBasedOnECharts(`./extension-src/bmap/bmap.js`),
legacy: true, // Support IE8-
external: ['echarts'],
output: {
name: 'bmap',
format: 'umd',
sourcemap: !min,
legacy: true, // Must be declared both in inputOptions and outputOptions.
globals: {
// For UMD `global.echarts`
echarts: 'echarts'
},
file: getPathBasedOnECharts(`dist/extension/bmap${postfix}.js`)
},
watch: {
include: [getPathBasedOnECharts('./extension-src/bmap/**')]
}
};
};
/**
* @param {boolean} [min=false]
*/
exports.createDataTool = function (min) {
let postfix = min ? '.min' : '';
return {
plugins: getPlugins({min}),
input: getPathBasedOnECharts(`./extension-src/dataTool/index.js`),
legacy: true, // Support IE8-
external: ['echarts'],
output: {
name: 'dataTool',
format: 'umd',
sourcemap: !min,
legacy: true, // Must be declared both in inputOptions and outputOptions.
globals: {
// For UMD `global.echarts`
echarts: 'echarts'
},
file: getPathBasedOnECharts(`dist/extension/dataTool${postfix}.js`)
},
watch: {
include: [getPathBasedOnECharts('./extension-src/dataTool/**')]
}
};
};
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var esprima = require('esprima');
var escodegen = require('escodegen');
var estraverse = require('estraverse');
var SYNTAX = estraverse.Syntax;
var STR_MIN_LENGTH = 5;
var STR_MIN_DIST = 1000;
var STR_MIN_COUNT = 2;
function createDeclaration(declarations) {
return {
type: SYNTAX.VariableDeclaration,
declarations: declarations,
kind: 'var'
};
}
function createDeclarator(id, init) {
return {
type: SYNTAX.VariableDeclarator,
id: {
type: SYNTAX.Identifier,
name: id
},
init: {
type: SYNTAX.Literal,
value: init
}
};
}
function base54Digits() {
return 'etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984';
}
var base54 = (function(){
var DIGITS = base54Digits();
return function(num) {
var ret = '';
var base = 54;
do {
ret += DIGITS.charAt(num % base);
num = Math.floor(num / base);
base = 64;
} while (num > 0);
return ret;
};
})();
function mangleString(source) {
var ast = esprima.parse(source, {
loc: true
});
var stringVariables = {};
var stringRelaceCount = 0;
estraverse.traverse(ast, {
enter: function (node, parent) {
if (node.type === SYNTAX.Literal
&& typeof node.value === 'string'
) {
// Ignore if string is the key of property
if (parent.type === SYNTAX.Property) {
return;
}
var value = node.value;
if (value.length > STR_MIN_LENGTH) {
if (!stringVariables[value]) {
stringVariables[value] = {
count: 0,
lastLoc: node.loc.start.line,
name: '__echartsString__' + base54(stringRelaceCount++)
};
}
var diff = node.loc.start.line - stringVariables[value].lastLoc;
// GZIP ?
if (diff >= STR_MIN_DIST) {
stringVariables[value].lastLoc = node.loc.start.line;
stringVariables[value].count++;
}
}
}
if (node.type === SYNTAX.MemberExpression && !node.computed) {
if (node.property.type === SYNTAX.Identifier) {
var value = node.property.name;
if (value.length > STR_MIN_LENGTH) {
if (!stringVariables[value]) {
stringVariables[value] = {
count: 0,
lastLoc: node.loc.start.line,
name: '__echartsString__' + base54(stringRelaceCount++)
};
}
var diff = node.loc.start.line - stringVariables[value].lastLoc;
if (diff >= STR_MIN_DIST) {
stringVariables[value].lastLoc = node.loc.start.line;
stringVariables[value].count++;
}
}
}
}
}
});
estraverse.replace(ast, {
enter: function (node, parent) {
if ((node.type === SYNTAX.Literal
&& typeof node.value === 'string')
) {
// Ignore if string is the key of property
if (parent.type === SYNTAX.Property) {
return;
}
var str = node.value;
if (stringVariables[str] && stringVariables[str].count > STR_MIN_COUNT) {
return {
type: SYNTAX.Identifier,
name: stringVariables[str].name
};
}
}
if (node.type === SYNTAX.MemberExpression && !node.computed) {
if (node.property.type === SYNTAX.Identifier) {
var str = node.property.name;
if (stringVariables[str] && stringVariables[str].count > STR_MIN_COUNT) {
return {
type: SYNTAX.MemberExpression,
object: node.object,
property: {
type: SYNTAX.Identifier,
name: stringVariables[str].name
},
computed: true
};
}
}
}
}
});
// Add variables in the top
for (var str in stringVariables) {
// Used more than once
if (stringVariables[str].count > STR_MIN_COUNT) {
ast.body.unshift(createDeclaration([
createDeclarator(stringVariables[str].name, str)
]));
}
}
return escodegen.generate(
ast,
{
format: {escapeless: true},
comment: true
}
);
}
exports = module.exports = mangleString;
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var UglifyJS = require('uglify-js');
var fs = require('fs');
var etpl = require('etpl');
var argv = require('optimist').argv;
etpl.config({
commandOpen: '/**',
commandClose: '*/'
});
var mode = argv.m || 'all';
var configPath = mode === 'all' ? 'config/echarts.js' : 'config/echarts.' + mode + '.js';
var outPath = mode === 'all' ? '../dist/echarts.js' : '../dist/echarts.' + mode + '.js';
var config = eval('(' + fs.readFileSync(configPath, 'utf-8') + ')');
var mainCode = fs.readFileSync(outPath, 'utf-8');
var startCode = fs.readFileSync('wrap/start.js', 'utf-8');
var nutCode = fs.readFileSync('wrap/nut.js', 'utf-8');
var endCode = fs.readFileSync('wrap/end.js', 'utf-8');
endCode = etpl.compile(endCode)({
parts: config.include
});
// FIXME
var sourceCode = [startCode, nutCode, require('./mangleString')(mainCode), endCode].join('\n');
var ast = UglifyJS.parse(sourceCode);
/* jshint camelcase: false */
// compressor needs figure_out_scope too
ast.figure_out_scope();
ast = ast.transform(UglifyJS.Compressor( {} ));
// need to figure out scope again so mangler works optimally
ast.figure_out_scope();
ast.compute_char_frequency();
ast.mangle_names();
fs.writeFileSync(outPath, [startCode, nutCode, mainCode, endCode].join('\n'), 'utf-8');
fs.writeFileSync(outPath.replace('.js', '.min.js'), ast.print_to_string(), 'utf-8');
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Compatible with prevoius folder structure: `echarts/lib` exists in `node_modules`
* (1) Build all files to CommonJS to `echarts/lib`.
* (2) Remove __DEV__.
* (3) Mount `echarts/src/export.js` to `echarts/lib/echarts.js`.
*/
const path = require('path');
const fsExtra = require('fs-extra');
const {color, travelSrcDir, prePulishSrc} = require('zrender/build/helper');
const ecDir = path.resolve(__dirname, '..');
const srcDir = path.resolve(__dirname, '../src');
const extensionSrcDir = path.resolve(__dirname, '../extension-src');
const extensionDir = path.resolve(__dirname, '../extension');
const libDir = path.resolve(__dirname, '../lib');
const preamble = require('./preamble');
module.exports = function () {
fsExtra.removeSync(libDir);
fsExtra.ensureDirSync(libDir);
travelSrcDir(srcDir, ({fileName, relativePath, absolutePath}) => {
prePulishSrc({
inputPath: absolutePath,
outputPath: path.resolve(libDir, relativePath, fileName),
transform
});
});
travelSrcDir(extensionSrcDir, ({fileName, relativePath, absolutePath}) => {
prePulishSrc({
inputPath: absolutePath,
outputPath: path.resolve(extensionDir, relativePath, fileName),
transform
});
});
prePulishSrc({
inputPath: path.resolve(ecDir, 'echarts.all.js'),
outputPath: path.resolve(ecDir, 'index.js'),
preamble: preamble
});
prePulishSrc({
inputPath: path.resolve(ecDir, 'echarts.common.js'),
outputPath: path.resolve(ecDir, 'index.common.js'),
preamble: preamble
});
prePulishSrc({
inputPath: path.resolve(ecDir, 'echarts.simple.js'),
outputPath: path.resolve(ecDir, 'index.simple.js'),
preamble: preamble
});
function transform({code, inputPath, outputPath}) {
if (inputPath === path.resolve(ecDir, 'src/echarts.js')) {
// Using `echarts/echarts.blank.js` to overwrite `echarts/lib/echarts.js`
// for including exports API.
code += `
var ___ec_export = require("./export");
(function () {
for (var key in ___ec_export) {
if (___ec_export.hasOwnProperty(key)) {
exports[key] = ___ec_export[key];
}
}
})();`;
}
return code;
}
console.log(color('fgGreen', 'bright')('All done.'));
};
module.exports = `
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
`;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Find language definations.
*
* Usage:
*
* import ecLangPlugin from 'echarts/build/rollup-plugin-ec-lang';
* let rollupConfig = {
* plugins: [
* ecLangPlugin({lang: 'en'}),
* ...
* ]
* };
*/
const {resolve} = require('path');
const {readFileSync} = require('fs');
/**
* @param {Object} [opt]
* @param {string} [opt.lang=null] null/undefined/'' or 'en' or 'fi' or a file path.
*/
function getPlugin(opt) {
let lang = opt && opt.lang || '';
return {
load: function (absolutePath) {
if (/\/src\/lang\.js$/.test(absolutePath)) {
let langPath = getLangFileInfo(lang).absolutePath;
if (langPath) {
absolutePath = langPath;
}
}
return readFileSync(absolutePath, 'utf-8');
}
};
}
/**
* @param {string} lang null/undefined/'' or 'en' or 'fi' or a file path.
* @return {Object} {isOuter, absolutePath}
*/
let getLangFileInfo = getPlugin.getLangFileInfo = function (lang) {
let absolutePath;
let isOuter = false;
if (lang) {
if (/^[a-zA-Z]{2}$/.test(lang)) {
absolutePath = resolve(__dirname, '../', 'src/lang' + lang.toUpperCase() + '.js')
}
else {
isOuter = true;
// `lang` is an absolute path or a relative path based on process.cwd().
absolutePath = resolve(lang);
}
}
return {isOuter, absolutePath};
};
module.exports = getPlugin;
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Remove the code of `if (__DEV__) { ... }`.
*
* Usage:
*
* import ecRemoveDevPlugin from 'echats/build/rollup-plugin-ec-remove-dev';
* let rollupConfig = {
* plugins: [
* ecRemoveDevPlugin(),
* ...
* ]
* };
*/
const babel = require('@babel/core');
const removeDEVPlugin = require('zrender/build/babel-plugin-transform-remove-dev');
/**
* @param {Object} [opt]
* @param {Object} [opt.sourcemap]
*/
module.exports = function ({sourcemap} = {}) {
return {
transform: function (sourceCode) {
let {code, map} = babel.transform(sourceCode, {
plugins: [removeDEVPlugin],
sourceMaps: sourcemap
});
return {code, map};
}
};
};
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("echarts")):"function"==typeof define&&define.amd?define(["exports","echarts"],e):e(t.bmap={},t.echarts)}(this,function(t,e){"use strict";function o(t,e){this._bmap=t,this.dimensions=["lng","lat"],this._mapOffset=[0,0],this._api=e,this._projection=new BMap.MercatorProjection}function n(t,o){return o=o||[0,0],e.util.map([0,1],function(e){var n=o[e],i=t[e]/2,a=[],r=[];return a[e]=n-i,r[e]=n+i,a[1-e]=r[1-e]=o[1-e],Math.abs(this.dataToPoint(a)[e]-this.dataToPoint(r)[e])},this)}function i(){function t(t){this._root=t}return t.prototype=new BMap.Overlay,t.prototype.initialize=function(t){return t.getPanes().labelPane.appendChild(this._root),this._root},t.prototype.draw=function(){},t}function a(t,e){return t&&e&&t[0]===e[0]&&t[1]===e[1]}o.prototype.dimensions=["lng","lat"],o.prototype.setZoom=function(t){this._zoom=t},o.prototype.setCenter=function(t){this._center=this._projection.lngLatToPoint(new BMap.Point(t[0],t[1]))},o.prototype.setMapOffset=function(t){this._mapOffset=t},o.prototype.getBMap=function(){return this._bmap},o.prototype.dataToPoint=function(t){var e=new BMap.Point(t[0],t[1]),o=this._bmap.pointToOverlayPixel(e),n=this._mapOffset;return[o.x-n[0],o.y-n[1]]},o.prototype.pointToData=function(t){var e=this._mapOffset;return[(t=this._bmap.overlayPixelToPoint({x:t[0]+e[0],y:t[1]+e[1]})).lng,t.lat]},o.prototype.getViewRect=function(){var t=this._api;return new e.graphic.BoundingRect(0,0,t.getWidth(),t.getHeight())},o.prototype.getRoamTransform=function(){return e.matrix.create()},o.prototype.prepareCustoms=function(t){var o=this.getViewRect();return{coordSys:{type:"bmap",x:o.x,y:o.y,width:o.width,height:o.height},api:{coord:e.util.bind(this.dataToPoint,this),size:e.util.bind(n,this)}}};var r;o.dimensions=o.prototype.dimensions,o.create=function(t,e){var n,a=e.getDom();t.eachComponent("bmap",function(t){var p=e.getZr().painter,s=p.getViewportRoot();if("undefined"==typeof BMap)throw new Error("BMap api is not loaded");if(r=r||i(),n)throw new Error("Only one bmap component can exist");if(!t.__bmap){var m=a.querySelector(".ec-extension-bmap");m&&(s.style.left="0px",s.style.top="0px",a.removeChild(m)),(m=document.createElement("div")).style.cssText="width:100%;height:100%",m.classList.add("ec-extension-bmap"),a.appendChild(m);var c=t.__bmap=new BMap.Map(m),d=new r(s);c.addOverlay(d),p.getViewportRootOffset=function(){return{offsetLeft:0,offsetTop:0}}}var c=t.__bmap,f=t.get("center"),l=t.get("zoom");if(f&&l){var h=new BMap.Point(f[0],f[1]);c.centerAndZoom(h,l)}(n=new o(c,e)).setMapOffset(t.__mapOffset||[0,0]),n.setZoom(l),n.setCenter(f),t.coordinateSystem=n}),t.eachSeries(function(t){"bmap"===t.get("coordinateSystem")&&(t.coordinateSystem=n)})},e.extendComponentModel({type:"bmap",getBMap:function(){return this.__bmap},setCenterAndZoom:function(t,e){this.option.center=t,this.option.zoom=e},centerOrZoomChanged:function(t,e){var o=this.option;return!(a(t,o.center)&&e===o.zoom)},defaultOption:{center:[104.114129,37.550339],zoom:5,mapStyle:{},roam:!1}}),e.extendComponentView({type:"bmap",render:function(t,e,o){function n(){i||o.dispatchAction({type:"bmapRoam"})}var i=!0,a=t.getBMap(),r=o.getZr().painter.getViewportRoot(),p=t.coordinateSystem,s=function(e,n){if(!i){var a=r.parentNode.parentNode.parentNode,s=[-parseInt(a.style.left,10)||0,-parseInt(a.style.top,10)||0];r.style.left=s[0]+"px",r.style.top=s[1]+"px",p.setMapOffset(s),t.__mapOffset=s,o.dispatchAction({type:"bmapRoam"})}};a.removeEventListener("moving",this._oldMoveHandler),a.removeEventListener("zoomend",this._oldZoomEndHandler),a.addEventListener("moving",s),a.addEventListener("zoomend",n),this._oldMoveHandler=s,this._oldZoomEndHandler=n;var m=t.get("roam");m&&"scale"!==m?a.enableDragging():a.disableDragging(),m&&"move"!==m?(a.enableScrollWheelZoom(),a.enableDoubleClickZoom(),a.enablePinchToZoom()):(a.disableScrollWheelZoom(),a.disableDoubleClickZoom(),a.disablePinchToZoom());var c=t.__mapStyle,d=t.get("mapStyle")||{},f=JSON.stringify(d);JSON.stringify(c)!==f&&(Object.keys(d).length&&a.setMapStyle(d),t.__mapStyle=JSON.parse(f)),i=!1}}),e.registerCoordinateSystem("bmap",o),e.registerAction({type:"bmapRoam",event:"bmapRoam",update:"updateLayout"},function(t,e){e.eachComponent("bmap",function(t){var e=t.getBMap(),o=e.getCenter();t.setCenterAndZoom([o.lng,o.lat],e.getZoom())})});t.version="1.0.0"});
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("echarts")):"function"==typeof define&&define.amd?define(["exports","echarts"],t):t(e.dataTool={},e.echarts)}(this,function(e,t){"use strict";function r(e,t,r){if(e&&t){if(e.map&&e.map===f)return e.map(t,r);for(var a=[],n=0,o=e.length;n<o;n++)a.push(t.call(r,e[n],n,e));return a}}function a(e){return e?r(u(e,"attribute"),function(e){return{id:i(e,"id"),title:i(e,"title"),type:i(e,"type")}}):[]}function n(e,t){return e?r(u(e,"node"),function(e){var r={id:i(e,"id"),name:i(e,"label"),itemStyle:{normal:{}}},a=l(e,"viz:size"),n=l(e,"viz:position"),o=l(e,"viz:color"),s=l(e,"attvalues");if(a&&(r.symbolSize=parseFloat(i(a,"value"))),n&&(r.x=parseFloat(i(n,"x")),r.y=parseFloat(i(n,"y"))),o&&(r.itemStyle.normal.color="rgb("+[0|i(o,"r"),0|i(o,"g"),0|i(o,"b")].join(",")+")"),s){var f=u(s,"attvalue");r.attributes={};for(var c=0;c<f.length;c++){var p=f[c],d=i(p,"for"),v=i(p,"value"),g=t[d];if(g){switch(g.type){case"integer":case"long":v=parseInt(v,10);break;case"float":case"double":v=parseFloat(v);break;case"boolean":v="true"==v.toLowerCase()}r.attributes[d]=v}}}return r}):[]}function o(e){return e?r(u(e,"edge"),function(e){var t={id:i(e,"id"),name:i(e,"label"),source:i(e,"source"),target:i(e,"target"),lineStyle:{normal:{}}},r=t.lineStyle.normal,a=l(e,"viz:thickness"),n=l(e,"viz:color");return a&&(r.width=parseFloat(a.getAttribute("value"))),n&&(r.color="rgb("+[0|i(n,"r"),0|i(n,"g"),0|i(n,"b")].join(",")+")"),t}):[]}function i(e,t){return e.getAttribute(t)}function l(e,t){for(var r=e.firstChild;r;){if(1==r.nodeType&&r.nodeName.toLowerCase()==t.toLowerCase())return r;r=r.nextSibling}return null}function u(e,t){for(var r=e.firstChild,a=[];r;)r.nodeName.toLowerCase()==t.toLowerCase()&&a.push(r),r=r.nextSibling;return a}function s(e){return e.sort(function(e,t){return e-t}),e}var f=Array.prototype.map,c=(Object.freeze||Object)({parse:function(e){var t;if(!(t="string"==typeof e?(new DOMParser).parseFromString(e,"text/xml"):e)||t.getElementsByTagName("parsererror").length)return null;var r=l(t,"gexf");if(!r)return null;for(var i=l(r,"graph"),u=a(l(i,"attributes")),s={},f=0;f<u.length;f++)s[u[f].id]=u[f];return{nodes:n(l(i,"nodes"),s),links:o(l(i,"edges"))}}}),p=function(e,t){var r=(e.length-1)*t+1,a=Math.floor(r),n=+e[a-1],o=r-a;return o?n+o*(e[a]-n):n},d=function(e,t){for(var r=[],a=[],n=[],o=(t=t||[]).boundIQR,i="none"===o||0===o,l=0;l<e.length;l++){n.push(l+"");var u=s(e[l].slice()),f=p(u,.25),c=p(u,.5),d=p(u,.75),v=u[0],g=u[u.length-1],h=(null==o?1.5:o)*(d-f),b=i?v:Math.max(v,f-h),m=i?g:Math.min(g,d+h);r.push([b,f,c,d,m]);for(var y=0;y<u.length;y++){var x=u[y];if(x<b||x>m){var w=[l,x];"vertical"===t.layout&&w.reverse(),a.push(w)}}}return{boxData:r,outliers:a,axisData:n}};t.dataTool&&(t.dataTool.version="1.0.0",t.dataTool.gexf=c,t.dataTool.prepareBoxplotData=d),e.version="1.0.0",e.gexf=c,e.prepareBoxplotData=d});
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export * from './src/echarts';
export * from './src/export';
import './src/component/dataset';
// Import all charts and components
import './src/chart/line';
import './src/chart/bar';
import './src/chart/pie';
import './src/chart/scatter';
import './src/chart/radar';
import './src/chart/map';
import './src/chart/tree';
import './src/chart/treemap';
import './src/chart/graph';
import './src/chart/gauge';
import './src/chart/funnel';
import './src/chart/parallel';
import './src/chart/sankey';
import './src/chart/boxplot';
import './src/chart/candlestick';
import './src/chart/effectScatter';
import './src/chart/lines';
import './src/chart/heatmap';
import './src/chart/pictorialBar';
import './src/chart/themeRiver';
import './src/chart/sunburst';
import './src/chart/custom';
import './src/component/graphic';
import './src/component/grid';
import './src/component/legendScroll';
import './src/component/tooltip';
import './src/component/axisPointer';
import './src/component/polar';
import './src/component/geo';
import './src/component/parallel';
import './src/component/singleAxis';
import './src/component/brush';
import './src/component/calendar';
import './src/component/title';
import './src/component/dataZoom';
import './src/component/visualMap';
import './src/component/markPoint';
import './src/component/markLine';
import './src/component/markArea';
import './src/component/timeline';
import './src/component/toolbox';
import 'zrender/src/vml/vml';
import 'zrender/src/svg/svg';
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export * from './src/echarts';
export * from './src/export';
import './src/component/dataset';
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export * from './src/echarts';
export * from './src/export';
import './src/component/dataset';
import './src/chart/line';
import './src/chart/bar';
import './src/chart/pie';
import './src/chart/scatter';
import './src/component/graphic';
import './src/component/tooltip';
import './src/component/axisPointer';
import './src/component/legendScroll';
import './src/component/grid';
import './src/component/title';
import './src/component/markPoint';
import './src/component/markLine';
import './src/component/markArea';
import './src/component/dataZoom';
import './src/component/toolbox';
import 'zrender/src/vml/vml';
import 'zrender/src/svg/svg';
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export * from './src/echarts';
import './src/component/dataset';
import './src/chart/line';
import './src/chart/bar';
import './src/chart/pie';
import './src/component/gridSimple';
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* global BMap */
import {
util as zrUtil,
graphic,
matrix
} from 'echarts';
function BMapCoordSys(bmap, api) {
this._bmap = bmap;
this.dimensions = ['lng', 'lat'];
this._mapOffset = [0, 0];
this._api = api;
this._projection = new BMap.MercatorProjection();
}
BMapCoordSys.prototype.dimensions = ['lng', 'lat'];
BMapCoordSys.prototype.setZoom = function (zoom) {
this._zoom = zoom;
};
BMapCoordSys.prototype.setCenter = function (center) {
this._center = this._projection.lngLatToPoint(new BMap.Point(center[0], center[1]));
};
BMapCoordSys.prototype.setMapOffset = function (mapOffset) {
this._mapOffset = mapOffset;
};
BMapCoordSys.prototype.getBMap = function () {
return this._bmap;
};
BMapCoordSys.prototype.dataToPoint = function (data) {
var point = new BMap.Point(data[0], data[1]);
// TODO mercator projection is toooooooo slow
// var mercatorPoint = this._projection.lngLatToPoint(point);
// var width = this._api.getZr().getWidth();
// var height = this._api.getZr().getHeight();
// var divider = Math.pow(2, 18 - 10);
// return [
// Math.round((mercatorPoint.x - this._center.x) / divider + width / 2),
// Math.round((this._center.y - mercatorPoint.y) / divider + height / 2)
// ];
var px = this._bmap.pointToOverlayPixel(point);
var mapOffset = this._mapOffset;
return [px.x - mapOffset[0], px.y - mapOffset[1]];
};
BMapCoordSys.prototype.pointToData = function (pt) {
var mapOffset = this._mapOffset;
var pt = this._bmap.overlayPixelToPoint({
x: pt[0] + mapOffset[0],
y: pt[1] + mapOffset[1]
});
return [pt.lng, pt.lat];
};
BMapCoordSys.prototype.getViewRect = function () {
var api = this._api;
return new graphic.BoundingRect(0, 0, api.getWidth(), api.getHeight());
};
BMapCoordSys.prototype.getRoamTransform = function () {
return matrix.create();
};
BMapCoordSys.prototype.prepareCustoms = function (data) {
var rect = this.getViewRect();
return {
coordSys: {
// The name exposed to user is always 'cartesian2d' but not 'grid'.
type: 'bmap',
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height
},
api: {
coord: zrUtil.bind(this.dataToPoint, this),
size: zrUtil.bind(dataToCoordSize, this)
}
};
};
function dataToCoordSize(dataSize, dataItem) {
dataItem = dataItem || [0, 0];
return zrUtil.map([0, 1], function (dimIdx) {
var val = dataItem[dimIdx];
var halfSize = dataSize[dimIdx] / 2;
var p1 = [];
var p2 = [];
p1[dimIdx] = val - halfSize;
p2[dimIdx] = val + halfSize;
p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
}, this);
}
var Overlay;
// For deciding which dimensions to use when creating list data
BMapCoordSys.dimensions = BMapCoordSys.prototype.dimensions;
function createOverlayCtor() {
function Overlay(root) {
this._root = root;
}
Overlay.prototype = new BMap.Overlay();
/**
* 初始化
*
* @param {BMap.Map} map
* @override
*/
Overlay.prototype.initialize = function (map) {
map.getPanes().labelPane.appendChild(this._root);
return this._root;
};
/**
* @override
*/
Overlay.prototype.draw = function () {};
return Overlay;
}
BMapCoordSys.create = function (ecModel, api) {
var bmapCoordSys;
var root = api.getDom();
// TODO Dispose
ecModel.eachComponent('bmap', function (bmapModel) {
var painter = api.getZr().painter;
var viewportRoot = painter.getViewportRoot();
if (typeof BMap === 'undefined') {
throw new Error('BMap api is not loaded');
}
Overlay = Overlay || createOverlayCtor();
if (bmapCoordSys) {
throw new Error('Only one bmap component can exist');
}
if (!bmapModel.__bmap) {
// Not support IE8
var bmapRoot = root.querySelector('.ec-extension-bmap');
if (bmapRoot) {
// Reset viewport left and top, which will be changed
// in moving handler in BMapView
viewportRoot.style.left = '0px';
viewportRoot.style.top = '0px';
root.removeChild(bmapRoot);
}
bmapRoot = document.createElement('div');
bmapRoot.style.cssText = 'width:100%;height:100%';
// Not support IE8
bmapRoot.classList.add('ec-extension-bmap');
root.appendChild(bmapRoot);
var bmap = bmapModel.__bmap = new BMap.Map(bmapRoot);
var overlay = new Overlay(viewportRoot);
bmap.addOverlay(overlay);
// Override
painter.getViewportRootOffset = function () {
return {offsetLeft: 0, offsetTop: 0};
};
}
var bmap = bmapModel.__bmap;
// Set bmap options
// centerAndZoom before layout and render
var center = bmapModel.get('center');
var zoom = bmapModel.get('zoom');
if (center && zoom) {
var pt = new BMap.Point(center[0], center[1]);
bmap.centerAndZoom(pt, zoom);
}
bmapCoordSys = new BMapCoordSys(bmap, api);
bmapCoordSys.setMapOffset(bmapModel.__mapOffset || [0, 0]);
bmapCoordSys.setZoom(zoom);
bmapCoordSys.setCenter(center);
bmapModel.coordinateSystem = bmapCoordSys;
});
ecModel.eachSeries(function (seriesModel) {
if (seriesModel.get('coordinateSystem') === 'bmap') {
seriesModel.coordinateSystem = bmapCoordSys;
}
});
};
export default BMapCoordSys;
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import * as echarts from 'echarts';
function v2Equal(a, b) {
return a && b && a[0] === b[0] && a[1] === b[1];
}
export default echarts.extendComponentModel({
type: 'bmap',
getBMap: function () {
// __bmap is injected when creating BMapCoordSys
return this.__bmap;
},
setCenterAndZoom: function (center, zoom) {
this.option.center = center;
this.option.zoom = zoom;
},
centerOrZoomChanged: function (center, zoom) {
var option = this.option;
return !(v2Equal(center, option.center) && zoom === option.zoom);
},
defaultOption: {
center: [104.114129, 37.550339],
zoom: 5,
mapStyle: {},
roam: false
}
});
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import * as echarts from 'echarts';
export default echarts.extendComponentView({
type: 'bmap',
render: function (bMapModel, ecModel, api) {
var rendering = true;
var bmap = bMapModel.getBMap();
var viewportRoot = api.getZr().painter.getViewportRoot();
var coordSys = bMapModel.coordinateSystem;
var moveHandler = function (type, target) {
if (rendering) {
return;
}
var offsetEl = viewportRoot.parentNode.parentNode.parentNode;
var mapOffset = [
-parseInt(offsetEl.style.left, 10) || 0,
-parseInt(offsetEl.style.top, 10) || 0
];
viewportRoot.style.left = mapOffset[0] + 'px';
viewportRoot.style.top = mapOffset[1] + 'px';
coordSys.setMapOffset(mapOffset);
bMapModel.__mapOffset = mapOffset;
api.dispatchAction({
type: 'bmapRoam'
});
};
function zoomEndHandler() {
if (rendering) {
return;
}
api.dispatchAction({
type: 'bmapRoam'
});
}
bmap.removeEventListener('moving', this._oldMoveHandler);
// FIXME
// Moveend may be triggered by centerAndZoom method when creating coordSys next time
// bmap.removeEventListener('moveend', this._oldMoveHandler);
bmap.removeEventListener('zoomend', this._oldZoomEndHandler);
bmap.addEventListener('moving', moveHandler);
// bmap.addEventListener('moveend', moveHandler);
bmap.addEventListener('zoomend', zoomEndHandler);
this._oldMoveHandler = moveHandler;
this._oldZoomEndHandler = zoomEndHandler;
var roam = bMapModel.get('roam');
if (roam && roam !== 'scale') {
bmap.enableDragging();
}
else {
bmap.disableDragging();
}
if (roam && roam !== 'move') {
bmap.enableScrollWheelZoom();
bmap.enableDoubleClickZoom();
bmap.enablePinchToZoom();
}
else {
bmap.disableScrollWheelZoom();
bmap.disableDoubleClickZoom();
bmap.disablePinchToZoom();
}
var originalStyle = bMapModel.__mapStyle;
var newMapStyle = bMapModel.get('mapStyle') || {};
// FIXME, Not use JSON methods
var mapStyleStr = JSON.stringify(newMapStyle);
if (JSON.stringify(originalStyle) !== mapStyleStr) {
// FIXME May have blank tile when dragging if setMapStyle
if (Object.keys(newMapStyle).length) {
bmap.setMapStyle(newMapStyle);
}
bMapModel.__mapStyle = JSON.parse(mapStyleStr);
}
rendering = false;
}
});
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* BMap component extension
*/
import * as echarts from 'echarts';
import BMapCoordSys from './BMapCoordSys';
import './BMapModel';
import './BMapView';
echarts.registerCoordinateSystem('bmap', BMapCoordSys);
// Action
echarts.registerAction({
type: 'bmapRoam',
event: 'bmapRoam',
update: 'updateLayout'
}, function (payload, ecModel) {
ecModel.eachComponent('bmap', function (bMapModel) {
var bmap = bMapModel.getBMap();
var center = bmap.getCenter();
bMapModel.setCenterAndZoom([center.lng, center.lat], bmap.getZoom());
});
});
export var version = '1.0.0';
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// GEXF File Parser
// http://gexf.net/1.2draft/gexf-12draft-primer.pdf
import * as zrUtil from 'zrender/src/core/util';
export function parse(xml) {
var doc;
if (typeof xml === 'string') {
var parser = new DOMParser();
doc = parser.parseFromString(xml, 'text/xml');
}
else {
doc = xml;
}
if (!doc || doc.getElementsByTagName('parsererror').length) {
return null;
}
var gexfRoot = getChildByTagName(doc, 'gexf');
if (!gexfRoot) {
return null;
}
var graphRoot = getChildByTagName(gexfRoot, 'graph');
var attributes = parseAttributes(getChildByTagName(graphRoot, 'attributes'));
var attributesMap = {};
for (var i = 0; i < attributes.length; i++) {
attributesMap[attributes[i].id] = attributes[i];
}
return {
nodes: parseNodes(getChildByTagName(graphRoot, 'nodes'), attributesMap),
links: parseEdges(getChildByTagName(graphRoot, 'edges'))
};
}
function parseAttributes(parent) {
return parent ? zrUtil.map(getChildrenByTagName(parent, 'attribute'), function (attribDom) {
return {
id: getAttr(attribDom, 'id'),
title: getAttr(attribDom, 'title'),
type: getAttr(attribDom, 'type')
};
}) : [];
}
function parseNodes(parent, attributesMap) {
return parent ? zrUtil.map(getChildrenByTagName(parent, 'node'), function (nodeDom) {
var id = getAttr(nodeDom, 'id');
var label = getAttr(nodeDom, 'label');
var node = {
id: id,
name: label,
itemStyle: {
normal: {}
}
};
var vizSizeDom = getChildByTagName(nodeDom, 'viz:size');
var vizPosDom = getChildByTagName(nodeDom, 'viz:position');
var vizColorDom = getChildByTagName(nodeDom, 'viz:color');
// var vizShapeDom = getChildByTagName(nodeDom, 'viz:shape');
var attvaluesDom = getChildByTagName(nodeDom, 'attvalues');
if (vizSizeDom) {
node.symbolSize = parseFloat(getAttr(vizSizeDom, 'value'));
}
if (vizPosDom) {
node.x = parseFloat(getAttr(vizPosDom, 'x'));
node.y = parseFloat(getAttr(vizPosDom, 'y'));
// z
}
if (vizColorDom) {
node.itemStyle.normal.color = 'rgb(' +[
getAttr(vizColorDom, 'r') | 0,
getAttr(vizColorDom, 'g') | 0,
getAttr(vizColorDom, 'b') | 0
].join(',') + ')';
}
// if (vizShapeDom) {
// node.shape = getAttr(vizShapeDom, 'shape');
// }
if (attvaluesDom) {
var attvalueDomList = getChildrenByTagName(attvaluesDom, 'attvalue');
node.attributes = {};
for (var j = 0; j < attvalueDomList.length; j++) {
var attvalueDom = attvalueDomList[j];
var attId = getAttr(attvalueDom, 'for');
var attValue = getAttr(attvalueDom, 'value');
var attribute = attributesMap[attId];
if (attribute) {
switch (attribute.type) {
case 'integer':
case 'long':
attValue = parseInt(attValue, 10);
break;
case 'float':
case 'double':
attValue = parseFloat(attValue);
break;
case 'boolean':
attValue = attValue.toLowerCase() == 'true';
break;
default:
}
node.attributes[attId] = attValue;
}
}
}
return node;
}) : [];
}
function parseEdges(parent) {
return parent ? zrUtil.map(getChildrenByTagName(parent, 'edge'), function (edgeDom) {
var id = getAttr(edgeDom, 'id');
var label = getAttr(edgeDom, 'label');
var sourceId = getAttr(edgeDom, 'source');
var targetId = getAttr(edgeDom, 'target');
var edge = {
id: id,
name: label,
source: sourceId,
target: targetId,
lineStyle: {
normal: {}
}
};
var lineStyle = edge.lineStyle.normal;
var vizThicknessDom = getChildByTagName(edgeDom, 'viz:thickness');
var vizColorDom = getChildByTagName(edgeDom, 'viz:color');
// var vizShapeDom = getChildByTagName(edgeDom, 'viz:shape');
if (vizThicknessDom) {
lineStyle.width = parseFloat(vizThicknessDom.getAttribute('value'));
}
if (vizColorDom) {
lineStyle.color = 'rgb(' + [
getAttr(vizColorDom, 'r') | 0,
getAttr(vizColorDom, 'g') | 0,
getAttr(vizColorDom, 'b') | 0
].join(',') + ')';
}
// if (vizShapeDom) {
// edge.shape = vizShapeDom.getAttribute('shape');
// }
return edge;
}) : [];
}
function getAttr(el, attrName) {
return el.getAttribute(attrName);
}
function getChildByTagName (parent, tagName) {
var node = parent.firstChild;
while (node) {
if (
node.nodeType != 1 ||
node.nodeName.toLowerCase() != tagName.toLowerCase()
) {
node = node.nextSibling;
} else {
return node;
}
}
return null;
}
function getChildrenByTagName (parent, tagName) {
var node = parent.firstChild;
var children = [];
while (node) {
if (node.nodeName.toLowerCase() == tagName.toLowerCase()) {
children.push(node);
}
node = node.nextSibling;
}
return children;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import * as echarts from 'echarts';
import * as gexf from './gexf';
import prepareBoxplotData from './prepareBoxplotData';
export var version = '1.0.0';
export {gexf};
export {prepareBoxplotData};
// For backward compatibility, where the namespace `dataTool` will
// be mounted on `echarts` is the extension `dataTool` is imported.
// But the old version of echarts do not have `dataTool` namespace,
// so check it before mounting.
if (echarts.dataTool) {
echarts.dataTool.version = version;
echarts.dataTool.gexf = gexf;
echarts.dataTool.prepareBoxplotData = prepareBoxplotData;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import quantile from './quantile';
import * as numberUtil from '../../src/util/number';
/**
* See:
* <https://en.wikipedia.org/wiki/Box_plot#cite_note-frigge_hoaglin_iglewicz-2>
* <http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html>
*
* Helper method for preparing data.
*
* @param {Array.<number>} rawData like
* [
* [12,232,443], (raw data set for the first box)
* [3843,5545,1232], (raw datat set for the second box)
* ...
* ]
* @param {Object} [opt]
*
* @param {(number|string)} [opt.boundIQR=1.5] Data less than min bound is outlier.
* default 1.5, means Q1 - 1.5 * (Q3 - Q1).
* If 'none'/0 passed, min bound will not be used.
* @param {(number|string)} [opt.layout='horizontal']
* Box plot layout, can be 'horizontal' or 'vertical'
* @return {Object} {
* boxData: Array.<Array.<number>>
* outliers: Array.<Array.<number>>
* axisData: Array.<string>
* }
*/
export default function (rawData, opt) {
opt = opt || [];
var boxData = [];
var outliers = [];
var axisData = [];
var boundIQR = opt.boundIQR;
var useExtreme = boundIQR === 'none' || boundIQR === 0;
for (var i = 0; i < rawData.length; i++) {
axisData.push(i + '');
var ascList = numberUtil.asc(rawData[i].slice());
var Q1 = quantile(ascList, 0.25);
var Q2 = quantile(ascList, 0.5);
var Q3 = quantile(ascList, 0.75);
var min = ascList[0];
var max = ascList[ascList.length - 1];
var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
var low = useExtreme
? min
: Math.max(min, Q1 - bound);
var high = useExtreme
? max
: Math.min(max, Q3 + bound);
boxData.push([low, Q1, Q2, Q3, high]);
for (var j = 0; j < ascList.length; j++) {
var dataItem = ascList[j];
if (dataItem < low || dataItem > high) {
var outlier = [i, dataItem];
opt.layout === 'vertical' && outlier.reverse();
outliers.push(outlier);
}
}
}
return {
boxData: boxData,
outliers: outliers,
axisData: axisData
};
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Copyright (c) 2010-2015, Michael Bostock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * The name Michael Bostock may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @see <https://github.com/mbostock/d3/blob/master/src/arrays/quantile.js>
* @see <http://en.wikipedia.org/wiki/Quantile>
* @param {Array.<number>} ascArr
*/
export default function(ascArr, p) {
var H = (ascArr.length - 1) * p + 1,
h = Math.floor(H),
v = +ascArr[h - 1],
e = H - h;
return e ? v + e * (ascArr[h] - v) : v;
}
var _echarts = require("echarts");
var zrUtil = _echarts.util;
var graphic = _echarts.graphic;
var matrix = _echarts.matrix;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* global BMap */
function BMapCoordSys(bmap, api) {
this._bmap = bmap;
this.dimensions = ['lng', 'lat'];
this._mapOffset = [0, 0];
this._api = api;
this._projection = new BMap.MercatorProjection();
}
BMapCoordSys.prototype.dimensions = ['lng', 'lat'];
BMapCoordSys.prototype.setZoom = function (zoom) {
this._zoom = zoom;
};
BMapCoordSys.prototype.setCenter = function (center) {
this._center = this._projection.lngLatToPoint(new BMap.Point(center[0], center[1]));
};
BMapCoordSys.prototype.setMapOffset = function (mapOffset) {
this._mapOffset = mapOffset;
};
BMapCoordSys.prototype.getBMap = function () {
return this._bmap;
};
BMapCoordSys.prototype.dataToPoint = function (data) {
var point = new BMap.Point(data[0], data[1]); // TODO mercator projection is toooooooo slow
// var mercatorPoint = this._projection.lngLatToPoint(point);
// var width = this._api.getZr().getWidth();
// var height = this._api.getZr().getHeight();
// var divider = Math.pow(2, 18 - 10);
// return [
// Math.round((mercatorPoint.x - this._center.x) / divider + width / 2),
// Math.round((this._center.y - mercatorPoint.y) / divider + height / 2)
// ];
var px = this._bmap.pointToOverlayPixel(point);
var mapOffset = this._mapOffset;
return [px.x - mapOffset[0], px.y - mapOffset[1]];
};
BMapCoordSys.prototype.pointToData = function (pt) {
var mapOffset = this._mapOffset;
var pt = this._bmap.overlayPixelToPoint({
x: pt[0] + mapOffset[0],
y: pt[1] + mapOffset[1]
});
return [pt.lng, pt.lat];
};
BMapCoordSys.prototype.getViewRect = function () {
var api = this._api;
return new graphic.BoundingRect(0, 0, api.getWidth(), api.getHeight());
};
BMapCoordSys.prototype.getRoamTransform = function () {
return matrix.create();
};
BMapCoordSys.prototype.prepareCustoms = function (data) {
var rect = this.getViewRect();
return {
coordSys: {
// The name exposed to user is always 'cartesian2d' but not 'grid'.
type: 'bmap',
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height
},
api: {
coord: zrUtil.bind(this.dataToPoint, this),
size: zrUtil.bind(dataToCoordSize, this)
}
};
};
function dataToCoordSize(dataSize, dataItem) {
dataItem = dataItem || [0, 0];
return zrUtil.map([0, 1], function (dimIdx) {
var val = dataItem[dimIdx];
var halfSize = dataSize[dimIdx] / 2;
var p1 = [];
var p2 = [];
p1[dimIdx] = val - halfSize;
p2[dimIdx] = val + halfSize;
p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
}, this);
}
var Overlay; // For deciding which dimensions to use when creating list data
BMapCoordSys.dimensions = BMapCoordSys.prototype.dimensions;
function createOverlayCtor() {
function Overlay(root) {
this._root = root;
}
Overlay.prototype = new BMap.Overlay();
/**
* 初始化
*
* @param {BMap.Map} map
* @override
*/
Overlay.prototype.initialize = function (map) {
map.getPanes().labelPane.appendChild(this._root);
return this._root;
};
/**
* @override
*/
Overlay.prototype.draw = function () {};
return Overlay;
}
BMapCoordSys.create = function (ecModel, api) {
var bmapCoordSys;
var root = api.getDom(); // TODO Dispose
ecModel.eachComponent('bmap', function (bmapModel) {
var painter = api.getZr().painter;
var viewportRoot = painter.getViewportRoot();
if (typeof BMap === 'undefined') {
throw new Error('BMap api is not loaded');
}
Overlay = Overlay || createOverlayCtor();
if (bmapCoordSys) {
throw new Error('Only one bmap component can exist');
}
if (!bmapModel.__bmap) {
// Not support IE8
var bmapRoot = root.querySelector('.ec-extension-bmap');
if (bmapRoot) {
// Reset viewport left and top, which will be changed
// in moving handler in BMapView
viewportRoot.style.left = '0px';
viewportRoot.style.top = '0px';
root.removeChild(bmapRoot);
}
bmapRoot = document.createElement('div');
bmapRoot.style.cssText = 'width:100%;height:100%'; // Not support IE8
bmapRoot.classList.add('ec-extension-bmap');
root.appendChild(bmapRoot);
var bmap = bmapModel.__bmap = new BMap.Map(bmapRoot);
var overlay = new Overlay(viewportRoot);
bmap.addOverlay(overlay); // Override
painter.getViewportRootOffset = function () {
return {
offsetLeft: 0,
offsetTop: 0
};
};
}
var bmap = bmapModel.__bmap; // Set bmap options
// centerAndZoom before layout and render
var center = bmapModel.get('center');
var zoom = bmapModel.get('zoom');
if (center && zoom) {
var pt = new BMap.Point(center[0], center[1]);
bmap.centerAndZoom(pt, zoom);
}
bmapCoordSys = new BMapCoordSys(bmap, api);
bmapCoordSys.setMapOffset(bmapModel.__mapOffset || [0, 0]);
bmapCoordSys.setZoom(zoom);
bmapCoordSys.setCenter(center);
bmapModel.coordinateSystem = bmapCoordSys;
});
ecModel.eachSeries(function (seriesModel) {
if (seriesModel.get('coordinateSystem') === 'bmap') {
seriesModel.coordinateSystem = bmapCoordSys;
}
});
};
var _default = BMapCoordSys;
module.exports = _default;
\ No newline at end of file \ No newline at end of file
var echarts = require("echarts");
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function v2Equal(a, b) {
return a && b && a[0] === b[0] && a[1] === b[1];
}
var _default = echarts.extendComponentModel({
type: 'bmap',
getBMap: function () {
// __bmap is injected when creating BMapCoordSys
return this.__bmap;
},
setCenterAndZoom: function (center, zoom) {
this.option.center = center;
this.option.zoom = zoom;
},
centerOrZoomChanged: function (center, zoom) {
var option = this.option;
return !(v2Equal(center, option.center) && zoom === option.zoom);
},
defaultOption: {
center: [104.114129, 37.550339],
zoom: 5,
mapStyle: {},
roam: false
}
});
module.exports = _default;
\ No newline at end of file \ No newline at end of file
var echarts = require("echarts");
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var _default = echarts.extendComponentView({
type: 'bmap',
render: function (bMapModel, ecModel, api) {
var rendering = true;
var bmap = bMapModel.getBMap();
var viewportRoot = api.getZr().painter.getViewportRoot();
var coordSys = bMapModel.coordinateSystem;
var moveHandler = function (type, target) {
if (rendering) {
return;
}
var offsetEl = viewportRoot.parentNode.parentNode.parentNode;
var mapOffset = [-parseInt(offsetEl.style.left, 10) || 0, -parseInt(offsetEl.style.top, 10) || 0];
viewportRoot.style.left = mapOffset[0] + 'px';
viewportRoot.style.top = mapOffset[1] + 'px';
coordSys.setMapOffset(mapOffset);
bMapModel.__mapOffset = mapOffset;
api.dispatchAction({
type: 'bmapRoam'
});
};
function zoomEndHandler() {
if (rendering) {
return;
}
api.dispatchAction({
type: 'bmapRoam'
});
}
bmap.removeEventListener('moving', this._oldMoveHandler); // FIXME
// Moveend may be triggered by centerAndZoom method when creating coordSys next time
// bmap.removeEventListener('moveend', this._oldMoveHandler);
bmap.removeEventListener('zoomend', this._oldZoomEndHandler);
bmap.addEventListener('moving', moveHandler); // bmap.addEventListener('moveend', moveHandler);
bmap.addEventListener('zoomend', zoomEndHandler);
this._oldMoveHandler = moveHandler;
this._oldZoomEndHandler = zoomEndHandler;
var roam = bMapModel.get('roam');
if (roam && roam !== 'scale') {
bmap.enableDragging();
} else {
bmap.disableDragging();
}
if (roam && roam !== 'move') {
bmap.enableScrollWheelZoom();
bmap.enableDoubleClickZoom();
bmap.enablePinchToZoom();
} else {
bmap.disableScrollWheelZoom();
bmap.disableDoubleClickZoom();
bmap.disablePinchToZoom();
}
var originalStyle = bMapModel.__mapStyle;
var newMapStyle = bMapModel.get('mapStyle') || {}; // FIXME, Not use JSON methods
var mapStyleStr = JSON.stringify(newMapStyle);
if (JSON.stringify(originalStyle) !== mapStyleStr) {
// FIXME May have blank tile when dragging if setMapStyle
if (Object.keys(newMapStyle).length) {
bmap.setMapStyle(newMapStyle);
}
bMapModel.__mapStyle = JSON.parse(mapStyleStr);
}
rendering = false;
}
});
module.exports = _default;
\ No newline at end of file \ No newline at end of file
## 百度地图扩展
ECharts 百度地图扩展,可以在百度地图上展现 [点图](http://echarts.baidu.com/option.html#series-scatter)[线图](http://echarts.baidu.com/option.html#series-line)[热力图](http://echarts.baidu.com/option.html#series-heatmap) 等可视化。
### 示例
[全国主要城市空气质量](http://echarts.baidu.com/demo.html#effectScatter-bmap)
[北京公交路线](http://echarts.baidu.com/demo.html#lines-bmap-bus)
[北京公交路线特效](http://echarts.baidu.com/demo.html#lines-bmap-effect)
[北京公交路线特效](http://echarts.baidu.com/demo.html#lines-bmap-effect)
[杭州热门步行路线](http://echarts.baidu.com/demo.html#heatmap-bmap)
### 引入
可以直接引入打包好的扩展文件和百度地图的 jssdk
```html
<!--引入百度地图的jssdk,这里需要使用你在百度地图开发者平台申请的 ak-->
<script src="http://api.map.baidu.com/api?v=2.0&ak="></script>
<!-- 引入 ECharts -->
<script src="dist/echarts.min.js"></script>
<!-- 引入百度地图扩展 -->
<script src="dist/extension/bmap.min.js"></script>
```
如果是 webpack 打包,也可以 require 引入
```js
require('echarts');
require('echarts/extension/bmap/bmap');
```
插件会自动注册相应的组件。
### 使用
扩展主要提供了跟 geo 一样的坐标系和底图的绘制,因此配置方式非常简单,如下
```js
option = {
// 加载 bmap 组件
bmap: {
// 百度地图中心经纬度
center: [120.13066322374, 30.240018034923],
// 百度地图缩放
zoom: 14,
// 是否开启拖拽缩放,可以只设置 'scale' 或者 'move'
roam: true,
// 百度地图的自定义样式,见 http://developer.baidu.com/map/jsdevelop-11.htm
mapStyle: {}
},
series: [{
type: 'scatter',
// 使用百度地图坐标系
coordinateSystem: 'bmap',
// 数据格式跟在 geo 坐标系上一样,每一项都是 [经度,纬度,数值大小,其它维度...]
data: [ [120, 30, 1] ]
}]
}
// 获取百度地图实例,使用百度地图自带的控件
var bmap = chart.getModel().getComponent('bmap').getBMap();
bmap.addControl(new BMap.MapTypeControl());
```
var echarts = require("echarts");
var BMapCoordSys = require("./BMapCoordSys");
require("./BMapModel");
require("./BMapView");
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* BMap component extension
*/
echarts.registerCoordinateSystem('bmap', BMapCoordSys); // Action
echarts.registerAction({
type: 'bmapRoam',
event: 'bmapRoam',
update: 'updateLayout'
}, function (payload, ecModel) {
ecModel.eachComponent('bmap', function (bMapModel) {
var bmap = bMapModel.getBMap();
var center = bmap.getCenter();
bMapModel.setCenterAndZoom([center.lng, center.lat], bmap.getZoom());
});
});
var version = '1.0.0';
exports.version = version;
\ No newline at end of file \ No newline at end of file
var zrUtil = require("zrender/lib/core/util");
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// GEXF File Parser
// http://gexf.net/1.2draft/gexf-12draft-primer.pdf
function parse(xml) {
var doc;
if (typeof xml === 'string') {
var parser = new DOMParser();
doc = parser.parseFromString(xml, 'text/xml');
} else {
doc = xml;
}
if (!doc || doc.getElementsByTagName('parsererror').length) {
return null;
}
var gexfRoot = getChildByTagName(doc, 'gexf');
if (!gexfRoot) {
return null;
}
var graphRoot = getChildByTagName(gexfRoot, 'graph');
var attributes = parseAttributes(getChildByTagName(graphRoot, 'attributes'));
var attributesMap = {};
for (var i = 0; i < attributes.length; i++) {
attributesMap[attributes[i].id] = attributes[i];
}
return {
nodes: parseNodes(getChildByTagName(graphRoot, 'nodes'), attributesMap),
links: parseEdges(getChildByTagName(graphRoot, 'edges'))
};
}
function parseAttributes(parent) {
return parent ? zrUtil.map(getChildrenByTagName(parent, 'attribute'), function (attribDom) {
return {
id: getAttr(attribDom, 'id'),
title: getAttr(attribDom, 'title'),
type: getAttr(attribDom, 'type')
};
}) : [];
}
function parseNodes(parent, attributesMap) {
return parent ? zrUtil.map(getChildrenByTagName(parent, 'node'), function (nodeDom) {
var id = getAttr(nodeDom, 'id');
var label = getAttr(nodeDom, 'label');
var node = {
id: id,
name: label,
itemStyle: {
normal: {}
}
};
var vizSizeDom = getChildByTagName(nodeDom, 'viz:size');
var vizPosDom = getChildByTagName(nodeDom, 'viz:position');
var vizColorDom = getChildByTagName(nodeDom, 'viz:color'); // var vizShapeDom = getChildByTagName(nodeDom, 'viz:shape');
var attvaluesDom = getChildByTagName(nodeDom, 'attvalues');
if (vizSizeDom) {
node.symbolSize = parseFloat(getAttr(vizSizeDom, 'value'));
}
if (vizPosDom) {
node.x = parseFloat(getAttr(vizPosDom, 'x'));
node.y = parseFloat(getAttr(vizPosDom, 'y')); // z
}
if (vizColorDom) {
node.itemStyle.normal.color = 'rgb(' + [getAttr(vizColorDom, 'r') | 0, getAttr(vizColorDom, 'g') | 0, getAttr(vizColorDom, 'b') | 0].join(',') + ')';
} // if (vizShapeDom) {
// node.shape = getAttr(vizShapeDom, 'shape');
// }
if (attvaluesDom) {
var attvalueDomList = getChildrenByTagName(attvaluesDom, 'attvalue');
node.attributes = {};
for (var j = 0; j < attvalueDomList.length; j++) {
var attvalueDom = attvalueDomList[j];
var attId = getAttr(attvalueDom, 'for');
var attValue = getAttr(attvalueDom, 'value');
var attribute = attributesMap[attId];
if (attribute) {
switch (attribute.type) {
case 'integer':
case 'long':
attValue = parseInt(attValue, 10);
break;
case 'float':
case 'double':
attValue = parseFloat(attValue);
break;
case 'boolean':
attValue = attValue.toLowerCase() == 'true';
break;
default:
}
node.attributes[attId] = attValue;
}
}
}
return node;
}) : [];
}
function parseEdges(parent) {
return parent ? zrUtil.map(getChildrenByTagName(parent, 'edge'), function (edgeDom) {
var id = getAttr(edgeDom, 'id');
var label = getAttr(edgeDom, 'label');
var sourceId = getAttr(edgeDom, 'source');
var targetId = getAttr(edgeDom, 'target');
var edge = {
id: id,
name: label,
source: sourceId,
target: targetId,
lineStyle: {
normal: {}
}
};
var lineStyle = edge.lineStyle.normal;
var vizThicknessDom = getChildByTagName(edgeDom, 'viz:thickness');
var vizColorDom = getChildByTagName(edgeDom, 'viz:color'); // var vizShapeDom = getChildByTagName(edgeDom, 'viz:shape');
if (vizThicknessDom) {
lineStyle.width = parseFloat(vizThicknessDom.getAttribute('value'));
}
if (vizColorDom) {
lineStyle.color = 'rgb(' + [getAttr(vizColorDom, 'r') | 0, getAttr(vizColorDom, 'g') | 0, getAttr(vizColorDom, 'b') | 0].join(',') + ')';
} // if (vizShapeDom) {
// edge.shape = vizShapeDom.getAttribute('shape');
// }
return edge;
}) : [];
}
function getAttr(el, attrName) {
return el.getAttribute(attrName);
}
function getChildByTagName(parent, tagName) {
var node = parent.firstChild;
while (node) {
if (node.nodeType != 1 || node.nodeName.toLowerCase() != tagName.toLowerCase()) {
node = node.nextSibling;
} else {
return node;
}
}
return null;
}
function getChildrenByTagName(parent, tagName) {
var node = parent.firstChild;
var children = [];
while (node) {
if (node.nodeName.toLowerCase() == tagName.toLowerCase()) {
children.push(node);
}
node = node.nextSibling;
}
return children;
}
exports.parse = parse;
\ No newline at end of file \ No newline at end of file
var echarts = require("echarts");
var gexf = require("./gexf");
exports.gexf = gexf;
var prepareBoxplotData = require("./prepareBoxplotData");
exports.prepareBoxplotData = prepareBoxplotData;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var version = '1.0.0';
// For backward compatibility, where the namespace `dataTool` will
// be mounted on `echarts` is the extension `dataTool` is imported.
// But the old version of echarts do not have `dataTool` namespace,
// so check it before mounting.
if (echarts.dataTool) {
echarts.dataTool.version = version;
echarts.dataTool.gexf = gexf;
echarts.dataTool.prepareBoxplotData = prepareBoxplotData;
}
exports.version = version;
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!