├── src
├── images
│ └── remind_2x.png
├── less
│ ├── reset.less
│ └── task.less
├── js
│ ├── detail.js
│ ├── add.js
│ ├── index.js
│ ├── dingtalk.js
│ └── fastclick.js
├── index.html
├── detail.html
└── add.html
├── .gitignore
├── README.md
├── dist
├── js
│ ├── test.js
│ ├── detail.js
│ ├── add.js
│ ├── index.js
│ ├── index-temp.js
│ ├── dingtalk.js
│ └── fastclick.js
├── index.html
├── css
│ ├── reset.css
│ └── task.css
├── detail.html
└── add.html
├── package.json
└── gulpfile.js
/src/images/remind_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/outlookxie/app-todolist/HEAD/src/images/remind_2x.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .project
2 | .settings
3 | *~
4 | *.diff
5 | *.patch
6 | .DS_Store
7 | .bower.json
8 | .sizecache.json
9 |
10 |
11 | node_modules
12 | /hpm
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 操作指南
2 |
3 | ### 第一步先安装node环境
4 |
5 | 先从node官网[下载](https://nodejs.org/en/download/)对应的安装包
6 |
7 | ### 第二步 安装gulp
8 | sudo npm install --global gulp
9 | ### 第三步 clone代码到本地
10 | git clone git@github.com:outlookxie/app-todolist.git
11 | ### 第四步 进入demo目录,并执行如下命令
12 | npm install
13 | ### 第五步 启动环境
14 | gulp
15 |
--------------------------------------------------------------------------------
/src/less/reset.less:
--------------------------------------------------------------------------------
1 | body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,figcaption,figure,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0}
2 | body,button,input,select,textarea{font:12px/1 Lucida Grande,'Microsoft YaHei',"Lucida Grande","Lucida Sans Unicode",Helvetica,Arial,Verdana,sans-serif}
3 | h1{font-size:18px;font-weight:normal}
4 | h2{font-size:16px;font-weight:normal}
5 | h3{font-size:14px;font-weight:normal}
6 | h4,h5,h6{font-size:100%;font-weight:normal}
7 | address,cite,dfn,em,var{font-style:normal}
8 | code,kbd,pre,samp,tt{font-family:"Courier New",Courier,monospace}
9 | small{font-size:12px}
10 | ul,ol,li{list-style:none}
11 | a{text-decoration:none}
12 | abbr[title],acronym[title]{border-bottom:1px dotted;cursor:help}
13 | q:before,q:after{content:''}
14 | legend{color:#000}
15 | fieldset,img{border:0}
16 | table{border-collapse:collapse;border-spacing:0}
17 | hr{border:0;height:1px}
18 | *{-ms-word-break:break-all;word-break:break-all;-ms-word-wrap:break-word;word-wrap:break-word;-webkit-tap-highlight-color:rgba(0,0,0,0)}
--------------------------------------------------------------------------------
/dist/js/test.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 | var Page = {
3 | init:function(){
4 | var that = this;
5 | //防止300毫秒点击延迟
6 | FastClick.attach(document.body);
7 |
8 | //绑定点击事件
9 | $('.a1').on('click',function(){
10 | dd.device.geolocation.get({
11 | targetAccuracy : 200,
12 | onSuccess : function(result) {
13 | /*
14 | {
15 | longitude : Number,
16 | latitude : Number,
17 | accuracy : Number,
18 | isWifiEnabled : Boolean,
19 | isGpsEnabled : Boolean,
20 | isFromMock : Boolean,
21 | provider : wifi|lbs|gps,
22 | accuracy : Number,
23 | isMobileEnabled : Boolean,
24 | errorMessage : String,
25 | errorCode : Number
26 | }
27 | */
28 | alert(JSON.stringify(result));
29 | },
30 | onFail : function(err) {}
31 | });
32 |
33 |
34 | });
35 | },
36 | test:function(){
37 | alert(11);
38 | }
39 | };
40 | //为了能够在PC端进行测试
41 | if(dd.version){
42 | dd.ready(function(){
43 | Page.init();
44 | });
45 | }else{
46 | Page.init();
47 | }
48 | })();
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "webapp-demo",
3 | "version": "1.0.0",
4 | "description": "demo",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "git@github.com:outlookxie/app-todolist.git"
12 | },
13 | "author": "guizhong",
14 | "license": "ISC",
15 | "bugs": {
16 | "url": ""
17 | },
18 | "homepage": "http://www.dingtalk.com",
19 | "devDependencies": {
20 | "marked": "^0.3.2",
21 | "babel": "^5.8.3",
22 | "babel-eslint": "^4.0.5",
23 | "del": "^1.2.0",
24 | "glob": "^4.0.6",
25 | "gulp-util": "^3.0.5",
26 | "gulp": "^3.8.8",
27 | "gulp-less": "^1.3.6",
28 | "gulp-livereload": "^2.1.1",
29 | "gulp-load-plugins": "^0.7.0",
30 | "gulp-minify-css": "^0.3.10",
31 | "gulp-rename": "^1.2.0",
32 | "gulp-autoprefixer":"^2.3.1",
33 | "merge-stream": "^0.1.6",
34 | "webpack": "^1.4.4",
35 | "webpack-bower-resolver": "0.0.1",
36 | "browser-sync":"^2.8.2",
37 | "gulp-uglify":"^1.2.0",
38 | "gulp-babel":"^5.2.0",
39 | "gulp-concat":"^2.6.0",
40 | "gulp-jshint":"^1.11.2",
41 | "gulp-imagemin": "^2.3.0",
42 | "imagemin-pngquant": "^4.1.0"
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/dist/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/dist/css/reset.css:
--------------------------------------------------------------------------------
1 | body,
2 | h1,
3 | h2,
4 | h3,
5 | h4,
6 | h5,
7 | h6,
8 | hr,
9 | p,
10 | blockquote,
11 | dl,
12 | dt,
13 | dd,
14 | ul,
15 | ol,
16 | li,
17 | pre,
18 | figcaption,
19 | figure,
20 | fieldset,
21 | legend,
22 | button,
23 | input,
24 | textarea,
25 | th,
26 | td {
27 | margin: 0;
28 | padding: 0;
29 | }
30 | body,
31 | button,
32 | input,
33 | select,
34 | textarea {
35 | font: 12px/1 Lucida Grande, 'Microsoft YaHei', "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
36 | }
37 | h1 {
38 | font-size: 18px;
39 | font-weight: normal;
40 | }
41 | h2 {
42 | font-size: 16px;
43 | font-weight: normal;
44 | }
45 | h3 {
46 | font-size: 14px;
47 | font-weight: normal;
48 | }
49 | h4,
50 | h5,
51 | h6 {
52 | font-size: 100%;
53 | font-weight: normal;
54 | }
55 | address,
56 | cite,
57 | dfn,
58 | em,
59 | var {
60 | font-style: normal;
61 | }
62 | code,
63 | kbd,
64 | pre,
65 | samp,
66 | tt {
67 | font-family: "Courier New", Courier, monospace;
68 | }
69 | small {
70 | font-size: 12px;
71 | }
72 | ul,
73 | ol,
74 | li {
75 | list-style: none;
76 | }
77 | a {
78 | text-decoration: none;
79 | }
80 | abbr[title],
81 | acronym[title] {
82 | border-bottom: 1px dotted;
83 | cursor: help;
84 | }
85 | q:before,
86 | q:after {
87 | content: '';
88 | }
89 | legend {
90 | color: #000000;
91 | }
92 | fieldset,
93 | img {
94 | border: 0;
95 | }
96 | table {
97 | border-collapse: collapse;
98 | border-spacing: 0;
99 | }
100 | hr {
101 | border: 0;
102 | height: 1px;
103 | }
104 | * {
105 | -ms-word-break: break-all;
106 | word-break: break-all;
107 | -ms-word-wrap: break-word;
108 | word-wrap: break-word;
109 | -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
110 | }
111 |
--------------------------------------------------------------------------------
/dist/js/detail.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 |
3 | var Util = {
4 | getQuery:function(param){
5 | var url = window.location.href;
6 | var searchIndex = url.indexOf('?');
7 | var searchParams = url.slice(searchIndex + 1).split('&');
8 | for (var i = 0; i < searchParams.length; i++) {
9 | var items = searchParams[i].split('=');
10 | if (items[0].trim() == param) {
11 | return items[1].trim();
12 | }
13 | }
14 | }
15 | };
16 |
17 | var Page = {
18 | init:function(){
19 | var that = this;
20 | var taskId = Util.getQuery('taskId');
21 | var taskType = Util.getQuery('taskType');
22 | //防止300毫秒点击延迟
23 | FastClick.attach(document.body);
24 | //绑定事件
25 | this.renerTaskDetail(taskId,taskType);
26 | },
27 | renerTaskDetail:function(taskId,taskType){
28 | var data = localStorage.getItem('taskData');
29 | data = JSON.parse(data);
30 | var res = data.res;
31 | var curTask;
32 | //alert(taskId);
33 | for(var i=0;i 0) {
63 | var s = changed.pop();
64 | console.log(s);
65 | $.livereload.changed(s);
66 | bs.reload();
67 | }
68 | }
69 | });
70 |
71 | gulp.task('build', ['less','html','js']);
72 |
73 | gulp.task("default",function(){
74 |
75 | bs(
76 | {
77 | server: "./dist"
78 | }
79 | );
80 | gulp.start('watch');
81 | });
82 |
83 |
84 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
32 |
33 |
34 |
35 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/dist/detail.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 查看任务
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/dist/add.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 新增任务
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/src/detail.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 查看任务
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
48 |
49 |
50 |
51 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/src/add.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 新增任务
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
49 |
50 |
51 |
52 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/src/less/task.less:
--------------------------------------------------------------------------------
1 | @import "reset.less";
2 | html{
3 |
4 | font-size:100px;
5 | }
6 | body{
7 | -webkit-touch-callout: none;
8 | -webkit-user-select: none;
9 | }
10 | html,body{
11 | height:100%;
12 | }
13 | .doc{
14 |
15 | }
16 | .doc,
17 | .task-list,
18 | .task-detail,
19 | .task-add{
20 |
21 | }
22 | .task-detail,
23 | .task-add{
24 | background-color:#fff;
25 | /*display:none;*/
26 | }
27 | .itemlist{
28 | margin-bottom:0.2rem;
29 | .hd{
30 | height:44px;
31 | line-height:44px;
32 | font-size:16px;
33 | padding-left:0.1rem;
34 | background-color:#5ec9f6;
35 | color:#fff;
36 | &.done{
37 | background-color:#78c06e;
38 | }
39 | }
40 | .item{
41 | position:relative;
42 | padding-bottom:0.16rem;
43 | padding-top:0.16rem;
44 | padding-left:0.2rem;
45 | li{
46 |
47 | }
48 | h3{
49 | font-size:14px;
50 | }
51 | i{
52 | font-size:12px;
53 | padding:4px;
54 | border-radius: 4px;
55 | font-style:normal;
56 | color:#fff;
57 | margin-left:8px;
58 | &.p1{
59 | background-color:#f65e5e;
60 | }
61 | &.p2{
62 | background-color:#ff943e;
63 | }
64 | &.p3{
65 | background-color:#c5cb63;
66 | }
67 | }
68 | &.active{
69 | background-color:#eee;
70 | }
71 |
72 | }
73 | .item:after{
74 | content: " ";
75 | position: absolute;
76 | left: 0;
77 | bottom: 0;
78 | width: 100%;
79 | height: 1px;
80 | border-bottom: 1px solid #ccc;
81 | transform-origin: 0 100%;
82 | transform: scaleY(0.5);
83 | }
84 | }
85 | .cells{
86 | margin-top: 0;
87 | background-color: #FFFFFF;
88 | line-height: 1.41176471;
89 | font-size: 17px;
90 | overflow: hidden;
91 | position: relative;
92 | .cell{
93 | padding: 10px 15px;
94 | display: block;
95 | position: relative;
96 | .cell-hd,
97 | .cell-bd,
98 | .cell-ft {
99 | display: table-cell;
100 | vertical-align: middle;
101 | word-wrap: break-word;
102 | word-break: break-all;
103 | white-space: nowrap;
104 | }
105 | .label {
106 | display: block;
107 | width: 5em;
108 | }
109 | .cell-primary {
110 | width: 2000px;
111 | white-space: normal;
112 | }
113 | .input {
114 | width: 100%;
115 | border: 0;
116 | outline: 0;
117 | -webkit-appearance: none;
118 | background-color: transparent;
119 | font-size: inherit;
120 | color: inherit;
121 | height: 1.41176471em;
122 | line-height: 1.41176471;
123 | }
124 | &:before{
125 | content: " ";
126 | position: absolute;
127 | left: 0;
128 | top: 0;
129 | width: 100%;
130 | height: 1px;
131 | border-top: 1px solid #D9D9D9;
132 | -webkit-transform-origin: 0 0;
133 | -ms-transform-origin: 0 0;
134 | transform-origin: 0 0;
135 | -webkit-transform: scaleY(0.5);
136 | -ms-transform: scaleY(0.5);
137 | transform: scaleY(0.5);
138 | left: 15px;
139 | }
140 | .date{
141 | &:after{
142 | content: "";
143 | display: inline-block;
144 | transform: rotate(45deg);
145 | height: 6px;
146 | width: 6px;
147 | border-width: 2px 2px 0 0;
148 | border-color: #C8C8CD;
149 | border-style: solid;
150 | position: relative;
151 | top: -2px;
152 | position: absolute;
153 | top: 50%;
154 | right: 15px;
155 | margin-top: -3px;
156 | }
157 | }
158 | .select{
159 | &:after{
160 | content: "";
161 | display: inline-block;
162 | transform: rotate(45deg);
163 | height: 6px;
164 | width: 6px;
165 | border-width: 2px 2px 0 0;
166 | border-color: #C8C8CD;
167 | border-style: solid;
168 | position: relative;
169 | top: -2px;
170 | position: absolute;
171 | top: 50%;
172 | right: 15px;
173 | margin-top: -3px;
174 | }
175 | }
176 |
177 | }
178 | &:after{
179 | content: " ";
180 | position: absolute;
181 | left: 0;
182 | bottom: 0;
183 | width: 100%;
184 | height: 1px;
185 | border-bottom: 1px solid #D9D9D9;
186 | transform-origin: 0 100%;
187 | transform: scaleY(0.5);
188 | }
189 | }
190 |
191 |
--------------------------------------------------------------------------------
/dist/js/add.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 | var Page = {
3 | init:function(){
4 | var that = this;
5 | //防止300毫秒点击延迟
6 | FastClick.attach(document.body);
7 | //绑定事件
8 | this.bind();
9 | //绑定左上角返回事件
10 | this.setLeft();
11 | //初始化导航的title,采用事件的方式实现解耦
12 | $('body').trigger('navigation.title.change',[{
13 | "title":"新增任务"
14 | }]);
15 | $('body').trigger('navigation.rightButton.change',[{
16 | "text":"保存",
17 | "callback":function(){
18 | var obj = {};
19 | obj.taskId = +(new Date());
20 | obj.taskName = $('#taskName').val();
21 |
22 | if(!obj.taskName){
23 | dd.device.notification.toast({
24 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
25 | text: "请输入任务描述", //提示信息
26 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
27 | delay: 0, //延迟显示,单位秒,默认0
28 | onSuccess : function(result) {
29 | /*{}*/
30 | },
31 | onFail : function(err) {}
32 | });
33 | return;
34 | }
35 | obj.startDate = $('#start-date').html();
36 | if(!obj.startDate){
37 | dd.device.notification.toast({
38 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
39 | text: "请选择开始时间", //提示信息
40 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
41 | delay: 0, //延迟显示,单位秒,默认0
42 | onSuccess : function(result) {
43 | /*{}*/
44 | },
45 | onFail : function(err) {}
46 | });
47 | return;
48 | }
49 | obj.endDate = $('#end-date').html();
50 | if(!obj.endDate){
51 | dd.device.notification.toast({
52 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
53 | text: "请选择结束时间", //提示信息
54 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
55 | delay: 0, //延迟显示,单位秒,默认0
56 | onSuccess : function(result) {
57 | /*{}*/
58 | },
59 | onFail : function(err) {}
60 | });
61 | return;
62 | }
63 | obj.level = $('#taskType').val();
64 | if(!obj.level){
65 | dd.device.notification.toast({
66 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
67 | text: "请选择优先级", //提示信息
68 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
69 | delay: 0, //延迟显示,单位秒,默认0
70 | onSuccess : function(result) {
71 | /*{}*/
72 | },
73 | onFail : function(err) {}
74 | });
75 | return;
76 | }
77 | obj.state = 1;
78 | var originDate = localStorage.getItem('taskData');
79 | originDate = JSON.parse(originDate);
80 | originDate.res.push(obj);
81 | localStorage.setItem('taskData',JSON.stringify(originDate));
82 | localStorage.setItem('_t_',obj.taskId);
83 | dd.biz.navigation.close();
84 | }
85 | }]);
86 | },
87 | bind:function(){
88 | //采用事件监听的方式是为了能够在统一一个地方设置导航的Title
89 | $('body').on('navigation.title.change',function(e,res){
90 | dd.biz.navigation.setTitle({
91 | title : res.title
92 | });
93 | });
94 | //采用事件监听的方式是为了能够在统一一个地方设置导航的右上角按钮文案及点击事件
95 | $('body').on('navigation.rightButton.change',function(e,res){
96 | dd.biz.navigation.setRight({
97 | show: res.show,//控制按钮显示, true 显示, false 隐藏, 默认true
98 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
99 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
100 | text: res.text,
101 | onSuccess:function(){
102 | res.callback&&res.callback();
103 | }
104 | });
105 | });
106 | $('#task-add .datepicker').on('click',function(){
107 | var node = $(this).find('.date');
108 | var v = node.html().trim();
109 | dd.biz.util.datepicker({
110 | format: 'yyyy-MM-dd',
111 | value: v, //默认显示日期
112 | onSuccess : function(result) {
113 | /*{
114 | value: "2015-02-10"
115 | }
116 | */
117 | node.html(result.value);
118 | },
119 | onFail : function() {}
120 | });
121 | });
122 |
123 | $('#task-add .select-type').on('click',function(){
124 | var node = $(this).find('.select');
125 | var s = $(this).find('input[name=taskType]');
126 | var v = node.html().trim();
127 | dd.biz.util.chosen({
128 | source:[{
129 | key: '非常紧急', //显示文本
130 | value: 1
131 | },{
132 | key: '紧急',
133 | value: 2
134 | },{
135 | key: '一般',
136 | value: 3
137 | }],
138 | selectedKey:v,
139 | onSuccess : function(result) {
140 | /*
141 | {
142 | key: '选项2',
143 | value: '234'
144 | }
145 | */
146 | node.html(result.key);
147 | s.val(result.value);
148 | },
149 | onFail : function() {}
150 | })
151 | });
152 | },
153 | setLeft:function(){
154 | var that = this;
155 | dd.biz.navigation.setLeft({
156 | show: true,//控制按钮显示, true 显示, false 隐藏, 默认true
157 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
158 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
159 | onSuccess : function(result) {
160 | dd.device.notification.confirm({
161 | message: "新增任务还未保存",
162 | title: "提示",
163 | buttonLabels: ['不保存', '继续'],
164 | onSuccess : function(result) {
165 | /*
166 | {
167 | buttonIndex: 0 //被点击按钮的索引值,Number类型,从0开始
168 | }
169 | */
170 | if(result.buttonIndex==0){
171 | dd.biz.navigation.close();
172 | }
173 | },
174 | onFail : function(err) {}
175 | });
176 | },
177 | onFail : function(err) {}
178 | });
179 |
180 |
181 | }
182 | };
183 | //为了能够在PC端进行测试
184 | if(dd.version){
185 | dd.ready(function(){
186 | Page.init();
187 | });
188 | }else{
189 | Page.init();
190 | }
191 | })();
--------------------------------------------------------------------------------
/src/js/add.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 | var Page = {
3 | init:function(){
4 | var that = this;
5 | //防止300毫秒点击延迟
6 | FastClick.attach(document.body);
7 | //绑定事件
8 | this.bind();
9 | //绑定左上角返回事件
10 | this.setLeft();
11 | //初始化导航的title,采用事件的方式实现解耦
12 | $('body').trigger('navigation.title.change',[{
13 | "title":"新增任务"
14 | }]);
15 | $('body').trigger('navigation.rightButton.change',[{
16 | "text":"保存",
17 | "callback":function(){
18 | var obj = {};
19 | obj.taskId = +(new Date());
20 | obj.taskName = $('#taskName').val();
21 |
22 | if(!obj.taskName){
23 | dd.device.notification.toast({
24 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
25 | text: "请输入任务描述", //提示信息
26 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
27 | delay: 0, //延迟显示,单位秒,默认0
28 | onSuccess : function(result) {
29 | /*{}*/
30 | },
31 | onFail : function(err) {}
32 | });
33 | return;
34 | }
35 | obj.startDate = $('#start-date').html();
36 | if(!obj.startDate){
37 | dd.device.notification.toast({
38 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
39 | text: "请选择开始时间", //提示信息
40 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
41 | delay: 0, //延迟显示,单位秒,默认0
42 | onSuccess : function(result) {
43 | /*{}*/
44 | },
45 | onFail : function(err) {}
46 | });
47 | return;
48 | }
49 | obj.endDate = $('#end-date').html();
50 | if(!obj.endDate){
51 | dd.device.notification.toast({
52 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
53 | text: "请选择结束时间", //提示信息
54 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
55 | delay: 0, //延迟显示,单位秒,默认0
56 | onSuccess : function(result) {
57 | /*{}*/
58 | },
59 | onFail : function(err) {}
60 | });
61 | return;
62 | }
63 | obj.level = $('#taskType').val();
64 | if(!obj.level){
65 | dd.device.notification.toast({
66 | icon: 'error', //icon样式,有success和error,默认为空 0.0.2
67 | text: "请选择优先级", //提示信息
68 | duration: 2, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)]
69 | delay: 0, //延迟显示,单位秒,默认0
70 | onSuccess : function(result) {
71 | /*{}*/
72 | },
73 | onFail : function(err) {}
74 | });
75 | return;
76 | }
77 | obj.state = 1;
78 | var originDate = localStorage.getItem('taskData');
79 | originDate = JSON.parse(originDate);
80 | originDate.res.push(obj);
81 | localStorage.setItem('taskData',JSON.stringify(originDate));
82 | localStorage.setItem('_t_',obj.taskId);
83 | dd.biz.navigation.close();
84 | }
85 | }]);
86 | },
87 | bind:function(){
88 | //采用事件监听的方式是为了能够在统一一个地方设置导航的Title
89 | $('body').on('navigation.title.change',function(e,res){
90 | dd.biz.navigation.setTitle({
91 | title : res.title
92 | });
93 | });
94 | //采用事件监听的方式是为了能够在统一一个地方设置导航的右上角按钮文案及点击事件
95 | $('body').on('navigation.rightButton.change',function(e,res){
96 | dd.biz.navigation.setRight({
97 | show: res.show,//控制按钮显示, true 显示, false 隐藏, 默认true
98 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
99 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
100 | text: res.text,
101 | onSuccess:function(){
102 | res.callback&&res.callback();
103 | }
104 | });
105 | });
106 | $('#task-add .datepicker').on('click',function(){
107 | var node = $(this).find('.date');
108 | var v = node.html().trim();
109 | dd.biz.util.datepicker({
110 | format: 'yyyy-MM-dd',
111 | value: v, //默认显示日期
112 | onSuccess : function(result) {
113 | /*{
114 | value: "2015-02-10"
115 | }
116 | */
117 | node.html(result.value);
118 | },
119 | onFail : function() {}
120 | });
121 | });
122 |
123 | $('#task-add .select-type').on('click',function(){
124 | var node = $(this).find('.select');
125 | var s = $(this).find('input[name=taskType]');
126 | var v = node.html().trim();
127 | dd.biz.util.chosen({
128 | source:[{
129 | key: '非常紧急', //显示文本
130 | value: 1
131 | },{
132 | key: '紧急',
133 | value: 2
134 | },{
135 | key: '一般',
136 | value: 3
137 | }],
138 | selectedKey:v,
139 | onSuccess : function(result) {
140 | /*
141 | {
142 | key: '选项2',
143 | value: '234'
144 | }
145 | */
146 | node.html(result.key);
147 | s.val(result.value);
148 | },
149 | onFail : function() {}
150 | })
151 | });
152 | },
153 | setLeft:function(){
154 | var that = this;
155 | dd.biz.navigation.setLeft({
156 | show: true,//控制按钮显示, true 显示, false 隐藏, 默认true
157 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
158 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
159 | onSuccess : function(result) {
160 | dd.device.notification.confirm({
161 | message: "新增任务还未保存",
162 | title: "提示",
163 | buttonLabels: ['不保存', '继续'],
164 | onSuccess : function(result) {
165 | /*
166 | {
167 | buttonIndex: 0 //被点击按钮的索引值,Number类型,从0开始
168 | }
169 | */
170 | if(result.buttonIndex==0){
171 | dd.biz.navigation.close();
172 | }
173 | },
174 | onFail : function(err) {}
175 | });
176 | },
177 | onFail : function(err) {}
178 | });
179 |
180 |
181 | }
182 | };
183 | //为了能够在PC端进行测试
184 | if(dd.version){
185 | dd.ready(function(){
186 | Page.init();
187 | });
188 | }else{
189 | Page.init();
190 | }
191 | })();
--------------------------------------------------------------------------------
/dist/css/task.css:
--------------------------------------------------------------------------------
1 | body,
2 | h1,
3 | h2,
4 | h3,
5 | h4,
6 | h5,
7 | h6,
8 | hr,
9 | p,
10 | blockquote,
11 | dl,
12 | dt,
13 | dd,
14 | ul,
15 | ol,
16 | li,
17 | pre,
18 | figcaption,
19 | figure,
20 | fieldset,
21 | legend,
22 | button,
23 | input,
24 | textarea,
25 | th,
26 | td {
27 | margin: 0;
28 | padding: 0;
29 | }
30 | body,
31 | button,
32 | input,
33 | select,
34 | textarea {
35 | font: 12px/1 Lucida Grande, 'Microsoft YaHei', "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
36 | }
37 | h1 {
38 | font-size: 18px;
39 | font-weight: normal;
40 | }
41 | h2 {
42 | font-size: 16px;
43 | font-weight: normal;
44 | }
45 | h3 {
46 | font-size: 14px;
47 | font-weight: normal;
48 | }
49 | h4,
50 | h5,
51 | h6 {
52 | font-size: 100%;
53 | font-weight: normal;
54 | }
55 | address,
56 | cite,
57 | dfn,
58 | em,
59 | var {
60 | font-style: normal;
61 | }
62 | code,
63 | kbd,
64 | pre,
65 | samp,
66 | tt {
67 | font-family: "Courier New", Courier, monospace;
68 | }
69 | small {
70 | font-size: 12px;
71 | }
72 | ul,
73 | ol,
74 | li {
75 | list-style: none;
76 | }
77 | a {
78 | text-decoration: none;
79 | }
80 | abbr[title],
81 | acronym[title] {
82 | border-bottom: 1px dotted;
83 | cursor: help;
84 | }
85 | q:before,
86 | q:after {
87 | content: '';
88 | }
89 | legend {
90 | color: #000000;
91 | }
92 | fieldset,
93 | img {
94 | border: 0;
95 | }
96 | table {
97 | border-collapse: collapse;
98 | border-spacing: 0;
99 | }
100 | hr {
101 | border: 0;
102 | height: 1px;
103 | }
104 | * {
105 | -ms-word-break: break-all;
106 | word-break: break-all;
107 | -ms-word-wrap: break-word;
108 | word-wrap: break-word;
109 | -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
110 | }
111 | html {
112 | font-size: 100px;
113 | }
114 | body {
115 | -webkit-touch-callout: none;
116 | -webkit-user-select: none;
117 | }
118 | html,
119 | body {
120 | height: 100%;
121 | }
122 | .task-detail,
123 | .task-add {
124 | background-color: #fff;
125 | /*display:none;*/
126 | }
127 | .itemlist {
128 | margin-bottom: 0.2rem;
129 | }
130 | .itemlist .hd {
131 | height: 44px;
132 | line-height: 44px;
133 | font-size: 16px;
134 | padding-left: 0.1rem;
135 | background-color: #5ec9f6;
136 | color: #fff;
137 | }
138 | .itemlist .hd.done {
139 | background-color: #78c06e;
140 | }
141 | .itemlist .item {
142 | position: relative;
143 | padding-bottom: 0.16rem;
144 | padding-top: 0.16rem;
145 | padding-left: 0.2rem;
146 | }
147 | .itemlist .item h3 {
148 | font-size: 14px;
149 | }
150 | .itemlist .item i {
151 | font-size: 12px;
152 | padding: 4px;
153 | border-radius: 4px;
154 | font-style: normal;
155 | color: #fff;
156 | margin-left: 8px;
157 | }
158 | .itemlist .item i.p1 {
159 | background-color: #f65e5e;
160 | }
161 | .itemlist .item i.p2 {
162 | background-color: #ff943e;
163 | }
164 | .itemlist .item i.p3 {
165 | background-color: #c5cb63;
166 | }
167 | .itemlist .item.active {
168 | background-color: #eee;
169 | }
170 | .itemlist .item:after {
171 | content: " ";
172 | position: absolute;
173 | left: 0;
174 | bottom: 0;
175 | width: 100%;
176 | height: 1px;
177 | border-bottom: 1px solid #ccc;
178 | -webkit-transform-origin: 0 100%;
179 | -ms-transform-origin: 0 100%;
180 | transform-origin: 0 100%;
181 | -webkit-transform: scaleY(0.5);
182 | -ms-transform: scaleY(0.5);
183 | transform: scaleY(0.5);
184 | }
185 | .cells {
186 | margin-top: 0;
187 | background-color: #FFFFFF;
188 | line-height: 1.41176471;
189 | font-size: 17px;
190 | overflow: hidden;
191 | position: relative;
192 | }
193 | .cells .cell {
194 | padding: 10px 15px;
195 | display: block;
196 | position: relative;
197 | }
198 | .cells .cell .cell-hd,
199 | .cells .cell .cell-bd,
200 | .cells .cell .cell-ft {
201 | display: table-cell;
202 | vertical-align: middle;
203 | word-wrap: break-word;
204 | word-break: break-all;
205 | white-space: nowrap;
206 | }
207 | .cells .cell .label {
208 | display: block;
209 | width: 5em;
210 | }
211 | .cells .cell .cell-primary {
212 | width: 2000px;
213 | white-space: normal;
214 | }
215 | .cells .cell .input {
216 | width: 100%;
217 | border: 0;
218 | outline: 0;
219 | -webkit-appearance: none;
220 | background-color: transparent;
221 | font-size: inherit;
222 | color: inherit;
223 | height: 1.41176471em;
224 | line-height: 1.41176471;
225 | }
226 | .cells .cell:before {
227 | content: " ";
228 | position: absolute;
229 | left: 0;
230 | top: 0;
231 | width: 100%;
232 | height: 1px;
233 | border-top: 1px solid #D9D9D9;
234 | -webkit-transform-origin: 0 0;
235 | -ms-transform-origin: 0 0;
236 | transform-origin: 0 0;
237 | -webkit-transform: scaleY(0.5);
238 | -ms-transform: scaleY(0.5);
239 | transform: scaleY(0.5);
240 | left: 15px;
241 | }
242 | .cells .cell .date:after {
243 | content: "";
244 | display: inline-block;
245 | -webkit-transform: rotate(45deg);
246 | -ms-transform: rotate(45deg);
247 | transform: rotate(45deg);
248 | height: 6px;
249 | width: 6px;
250 | border-width: 2px 2px 0 0;
251 | border-color: #C8C8CD;
252 | border-style: solid;
253 | position: relative;
254 | top: -2px;
255 | position: absolute;
256 | top: 50%;
257 | right: 15px;
258 | margin-top: -3px;
259 | }
260 | .cells .cell .select:after {
261 | content: "";
262 | display: inline-block;
263 | -webkit-transform: rotate(45deg);
264 | -ms-transform: rotate(45deg);
265 | transform: rotate(45deg);
266 | height: 6px;
267 | width: 6px;
268 | border-width: 2px 2px 0 0;
269 | border-color: #C8C8CD;
270 | border-style: solid;
271 | position: relative;
272 | top: -2px;
273 | position: absolute;
274 | top: 50%;
275 | right: 15px;
276 | margin-top: -3px;
277 | }
278 | .cells:after {
279 | content: " ";
280 | position: absolute;
281 | left: 0;
282 | bottom: 0;
283 | width: 100%;
284 | height: 1px;
285 | border-bottom: 1px solid #D9D9D9;
286 | -webkit-transform-origin: 0 100%;
287 | -ms-transform-origin: 0 100%;
288 | transform-origin: 0 100%;
289 | -webkit-transform: scaleY(0.5);
290 | -ms-transform: scaleY(0.5);
291 | transform: scaleY(0.5);
292 | }
293 |
--------------------------------------------------------------------------------
/dist/js/index.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 | var hash;
3 | var isShow = true;
4 | var t = 0;
5 | var pullDtd;
6 |
7 | //模拟数据
8 | var data = {
9 | res:[
10 | {
11 | taskId:4,
12 | taskName:'完成微应用设计方案',
13 | startDate:"2015-11-11",
14 | endDate:"2015-11-12",
15 | level:1,
16 | state:1
17 | },
18 | {
19 | taskId:5,
20 | taskName:'完成微应用代码开发',
21 | startDate:"2015-11-11",
22 | endDate:"2015-11-12",
23 | level:2,
24 | state:1
25 | },
26 | {
27 | taskId:6,
28 | taskName:'微应用发布上线',
29 | startDate:"2015-11-11",
30 | endDate:"2015-11-12",
31 | level:2,
32 | state:1
33 | },
34 | {
35 | taskId:1,
36 | taskName:'了解钉钉微应用开发文档',
37 | startDate:"2015-11-11",
38 | endDate:"2015-11-12",
39 | level:1,
40 | state:2
41 | },
42 | {
43 | taskId:2,
44 | taskName:'下载钉钉微应用开发demo',
45 | startDate:"2015-11-11",
46 | endDate:"2015-11-12",
47 | level:3,
48 | state:2
49 | }
50 | ]
51 | };
52 | alert(111);
53 | //模拟数据
54 | if(!localStorage.getItem('taskData')){
55 | localStorage.setItem('taskData',JSON.stringify(data));
56 | }
57 | var Util = {
58 | getQuery:function(param){
59 | var url = window.location.href;
60 | var searchIndex = url.indexOf('?');
61 | var searchParams = url.slice(searchIndex + 1).split('&');
62 | for (var i = 0; i < searchParams.length; i++) {
63 | var items = searchParams[i].split('=');
64 | if (items[0].trim() == param) {
65 | return items[1].trim();
66 | }
67 | }
68 | },
69 | getTargetUrl:function(replaceUrl,targetUrl){
70 | var protocol = location.protocol;
71 | var host = location.host;
72 | var pathname = location.pathname.replace(replaceUrl,targetUrl);
73 | return protocol+'//'+host+pathname;
74 | }
75 |
76 | };
77 |
78 | var Page = {
79 | init:function(){
80 | var that = this;
81 | //防止300毫秒点击延迟
82 | FastClick.attach(document.body);
83 | this.initData();
84 | //绑定事件
85 | this.bind();
86 | //初始化导航的title,采用事件的方式实现解耦
87 | $('body').trigger('navigation.title.change',[{
88 | "title":"我的任务"
89 | }]);
90 | //初始化导航的右上角,采用事件的方式实现解耦
91 | $('body').trigger('navigation.rightButton.change',[{
92 | "text":"新增",
93 | "show":true,
94 | "callback":function(){
95 | that.go('add');
96 | }
97 | }]);
98 | //绑定下拉事件
99 | dd.ui.pullToRefresh.enable({
100 | onSuccess: function() {
101 | setTimeout(function(){
102 | //todo 相关数据更新操作
103 | dd.ui.pullToRefresh.stop();
104 | },2000);
105 | },
106 | onFail: function() {
107 | }
108 | });
109 | //绑定每个任务的点击事件,事件采用代理的方式
110 | $('.doc').on('click','.item',function(){
111 | var _this = $(this);
112 | _this.addClass('active');
113 | setTimeout(function(){
114 | that.go('detail',_this.data('taskid'),_this.data('task-type'));
115 | _this.removeClass('active');
116 | },100);
117 | //alert(_this.data('task-type'));
118 |
119 | });
120 |
121 | var t3 = localStorage.getItem('_t_');
122 | //
123 | if(!t3){
124 | localStorage.setItem('_t_',t);
125 | }else{
126 | t = t3;
127 | }
128 | document.addEventListener('resume', function(e) {
129 | e.preventDefault();
130 | //判断是否有数据更新
131 | var t2 = localStorage.getItem('_t_');
132 | if(t2!=t){
133 | t = t2;
134 | that.initData();
135 | }
136 | }, false);
137 | },
138 | test:function(){
139 | alert(11);
140 | },
141 | initData:function(){
142 | var toDoHtml = [];
143 | var doneHtml = [];
144 | var that = this;
145 | var data = localStorage.getItem('taskData');
146 | data = JSON.parse(data);
147 | var todoCount=0;
148 | var doneCount=0;
149 | for(var i=0;i').html(toDoHtml.join('')).appendTo($('#todolist .bd'));
158 |
159 | $('#todolist .hd span').text('('+todoCount+')');
160 |
161 | for(var i=0;i').html(doneHtml.join('')).appendTo($('#donelist .bd'));
170 | $('#donelist .hd span').text('('+doneCount+')');
171 | },
172 | renderItem:function(item,type){
173 | var html = '';
174 | var levelName = '';
175 | switch(parseInt(item.level)){
176 | case 1:levelName='非常紧急';break;
177 | case 2:levelName='紧急';break;
178 | case 3:levelName='一般';break;
179 | }
180 | html = ''+item.taskName+''+levelName+'
';
181 | return html;
182 | },
183 | bind:function(){
184 | //采用事件监听的方式是为了能够在统一一个地方设置导航的Title
185 | $('body').on('navigation.title.change',function(e,res){
186 | dd.biz.navigation.setTitle({
187 | title : res.title
188 | });
189 | });
190 | //采用事件监听的方式是为了能够在统一一个地方设置导航的右上角按钮文案及点击事件
191 | $('body').on('navigation.rightButton.change',function(e,res){
192 | dd.biz.navigation.setRight({
193 | show: res.show,//控制按钮显示, true 显示, false 隐藏, 默认true
194 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
195 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
196 | text: res.text,
197 | onSuccess:function(){
198 | res.callback&&res.callback();
199 | }
200 | });
201 | });
202 | },
203 | getLevelName:function(level){
204 | var levelName = '';
205 | switch(level){
206 | case 1:levelName='非常紧急';break;
207 | case 2:levelName='紧急';break;
208 | case 3:levelName='一般';break;
209 | }
210 | return levelName;
211 | },
212 | go:function(page,taskId,taskType){
213 | var that = this;
214 | if(page=='add'){
215 | //这里替换为对应的页面url
216 | dd.biz.util.openLink({
217 | url:Util.getTargetUrl('index.html','add.html')
218 | });
219 | return;
220 |
221 | }else if(page=='detail'){
222 | dd.biz.util.openLink({
223 | url:Util.getTargetUrl('index.html','detail.html')+'?taskId='+taskId+'&taskType='+taskType
224 | });
225 | return;
226 | }
227 | }
228 | };
229 | if(dd.version){
230 | dd.ready(function(){
231 | Page.init();
232 | });
233 | }else{
234 | Page.init();
235 | }
236 | })();
--------------------------------------------------------------------------------
/src/js/index.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 | var hash;
3 | var isShow = true;
4 | var t = 0;
5 | var pullDtd;
6 |
7 | //模拟数据
8 | var data = {
9 | res:[
10 | {
11 | taskId:4,
12 | taskName:'完成微应用设计方案',
13 | startDate:"2015-11-11",
14 | endDate:"2015-11-12",
15 | level:1,
16 | state:1
17 | },
18 | {
19 | taskId:5,
20 | taskName:'完成微应用代码开发',
21 | startDate:"2015-11-11",
22 | endDate:"2015-11-12",
23 | level:2,
24 | state:1
25 | },
26 | {
27 | taskId:6,
28 | taskName:'微应用发布上线',
29 | startDate:"2015-11-11",
30 | endDate:"2015-11-12",
31 | level:2,
32 | state:1
33 | },
34 | {
35 | taskId:1,
36 | taskName:'了解钉钉微应用开发文档',
37 | startDate:"2015-11-11",
38 | endDate:"2015-11-12",
39 | level:1,
40 | state:2
41 | },
42 | {
43 | taskId:2,
44 | taskName:'下载钉钉微应用开发demo',
45 | startDate:"2015-11-11",
46 | endDate:"2015-11-12",
47 | level:3,
48 | state:2
49 | }
50 | ]
51 | };
52 | alert(111);
53 | //模拟数据
54 | if(!localStorage.getItem('taskData')){
55 | localStorage.setItem('taskData',JSON.stringify(data));
56 | }
57 | var Util = {
58 | getQuery:function(param){
59 | var url = window.location.href;
60 | var searchIndex = url.indexOf('?');
61 | var searchParams = url.slice(searchIndex + 1).split('&');
62 | for (var i = 0; i < searchParams.length; i++) {
63 | var items = searchParams[i].split('=');
64 | if (items[0].trim() == param) {
65 | return items[1].trim();
66 | }
67 | }
68 | },
69 | getTargetUrl:function(replaceUrl,targetUrl){
70 | var protocol = location.protocol;
71 | var host = location.host;
72 | var pathname = location.pathname.replace(replaceUrl,targetUrl);
73 | return protocol+'//'+host+pathname;
74 | }
75 |
76 | };
77 |
78 | var Page = {
79 | init:function(){
80 | var that = this;
81 | //防止300毫秒点击延迟
82 | FastClick.attach(document.body);
83 | this.initData();
84 | //绑定事件
85 | this.bind();
86 | //初始化导航的title,采用事件的方式实现解耦
87 | $('body').trigger('navigation.title.change',[{
88 | "title":"我的任务"
89 | }]);
90 | //初始化导航的右上角,采用事件的方式实现解耦
91 | $('body').trigger('navigation.rightButton.change',[{
92 | "text":"新增",
93 | "show":true,
94 | "callback":function(){
95 | that.go('add');
96 | }
97 | }]);
98 | //绑定下拉事件
99 | dd.ui.pullToRefresh.enable({
100 | onSuccess: function() {
101 | setTimeout(function(){
102 | //todo 相关数据更新操作
103 | dd.ui.pullToRefresh.stop();
104 | },2000);
105 | },
106 | onFail: function() {
107 | }
108 | });
109 | //绑定每个任务的点击事件,事件采用代理的方式
110 | $('.doc').on('click','.item',function(){
111 | var _this = $(this);
112 | _this.addClass('active');
113 | setTimeout(function(){
114 | that.go('detail',_this.data('taskid'),_this.data('task-type'));
115 | _this.removeClass('active');
116 | },100);
117 | //alert(_this.data('task-type'));
118 |
119 | });
120 |
121 | var t3 = localStorage.getItem('_t_');
122 | //
123 | if(!t3){
124 | localStorage.setItem('_t_',t);
125 | }else{
126 | t = t3;
127 | }
128 | document.addEventListener('resume', function(e) {
129 | e.preventDefault();
130 | //判断是否有数据更新
131 | var t2 = localStorage.getItem('_t_');
132 | if(t2!=t){
133 | t = t2;
134 | that.initData();
135 | }
136 | }, false);
137 | },
138 | test:function(){
139 | alert(11);
140 | },
141 | initData:function(){
142 | var toDoHtml = [];
143 | var doneHtml = [];
144 | var that = this;
145 | var data = localStorage.getItem('taskData');
146 | data = JSON.parse(data);
147 | var todoCount=0;
148 | var doneCount=0;
149 | for(var i=0;i').html(toDoHtml.join('')).appendTo($('#todolist .bd'));
158 |
159 | $('#todolist .hd span').text('('+todoCount+')');
160 |
161 | for(var i=0;i').html(doneHtml.join('')).appendTo($('#donelist .bd'));
170 | $('#donelist .hd span').text('('+doneCount+')');
171 | },
172 | renderItem:function(item,type){
173 | var html = '';
174 | var levelName = '';
175 | switch(parseInt(item.level)){
176 | case 1:levelName='非常紧急';break;
177 | case 2:levelName='紧急';break;
178 | case 3:levelName='一般';break;
179 | }
180 | html = ''+item.taskName+''+levelName+'
';
181 | return html;
182 | },
183 | bind:function(){
184 | //采用事件监听的方式是为了能够在统一一个地方设置导航的Title
185 | $('body').on('navigation.title.change',function(e,res){
186 | dd.biz.navigation.setTitle({
187 | title : res.title
188 | });
189 | });
190 | //采用事件监听的方式是为了能够在统一一个地方设置导航的右上角按钮文案及点击事件
191 | $('body').on('navigation.rightButton.change',function(e,res){
192 | dd.biz.navigation.setRight({
193 | show: res.show,//控制按钮显示, true 显示, false 隐藏, 默认true
194 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
195 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
196 | text: res.text,
197 | onSuccess:function(){
198 | res.callback&&res.callback();
199 | }
200 | });
201 | });
202 | },
203 | getLevelName:function(level){
204 | var levelName = '';
205 | switch(level){
206 | case 1:levelName='非常紧急';break;
207 | case 2:levelName='紧急';break;
208 | case 3:levelName='一般';break;
209 | }
210 | return levelName;
211 | },
212 | go:function(page,taskId,taskType){
213 | var that = this;
214 | if(page=='add'){
215 | //这里替换为对应的页面url
216 | dd.biz.util.openLink({
217 | url:Util.getTargetUrl('index.html','add.html')
218 | });
219 | return;
220 |
221 | }else if(page=='detail'){
222 | dd.biz.util.openLink({
223 | url:Util.getTargetUrl('index.html','detail.html')+'?taskId='+taskId+'&taskType='+taskType
224 | });
225 | return;
226 | }
227 | }
228 | };
229 | if(dd.version){
230 | dd.ready(function(){
231 | Page.init();
232 | });
233 | }else{
234 | Page.init();
235 | }
236 | })();
--------------------------------------------------------------------------------
/dist/js/index-temp.js:
--------------------------------------------------------------------------------
1 | ;(function(){
2 | var hash;
3 | var isShow = true;
4 |
5 | //模拟数据
6 | var data = {
7 | todo:[
8 | {
9 | taskId:4,
10 | taskName:'完成微应用设计方案',
11 | startDate:"2015-11-11",
12 | endDate:"2015-11-12",
13 | level:1
14 | },
15 | {
16 | taskId:5,
17 | taskName:'完成微应用代码开发',
18 | startDate:"2015-11-11",
19 | endDate:"2015-11-12",
20 | level:2
21 | },
22 | {
23 | taskId:6,
24 | taskName:'微应用发布上线',
25 | startDate:"2015-11-11",
26 | endDate:"2015-11-12",
27 | level:2
28 | }
29 | ],
30 | done:[
31 | {
32 | taskId:1,
33 | taskName:'了解钉钉微应用开发文档',
34 | startDate:"2015-11-11",
35 | endDate:"2015-11-12",
36 | level:1
37 | },
38 | {
39 | taskId:2,
40 | taskName:'下载钉钉微应用开发demo',
41 | startDate:"2015-11-11",
42 | endDate:"2015-11-12",
43 | level:3
44 | }
45 | ]
46 | };
47 |
48 | var Page = {
49 | init:function(){
50 | var that = this;
51 | //防止300毫秒点击延迟
52 | FastClick.attach(document.body);
53 | this.initData();
54 | //绑定事件
55 | this.bind();
56 | //绑定左上角返回事件
57 | this.setLeft();
58 | //初始化导航的title,采用事件的方式实现解耦
59 | $('body').trigger('navigation.title.change',[{
60 | "title":"我的任务"
61 | }]);
62 | //初始化导航的右上角,采用事件的方式实现解耦
63 | $('body').trigger('navigation.rightButton.change',[{
64 | "text":"新增",
65 | "show":true,
66 | "callback":function(){
67 | that.go('add');
68 | }
69 | }]);
70 | //绑定下拉事件
71 | dd.ui.pullToRefresh.enable({
72 | onSuccess: function() {
73 | setTimeout(function(){
74 | dd.ui.pullToRefresh.stop();
75 | },3000);
76 | },
77 | onFail: function() {
78 | }
79 | });
80 | //绑定每个任务的点击事件,事件采用代理的方式
81 | $('.doc').on('click','.item',function(){
82 | var _this = $(this);
83 | _this.addClass('active');
84 | setTimeout(function(){
85 | _this.removeClass('active');
86 | },300);
87 | //alert(_this.data('task-type'));
88 | that.go('detail',_this.data('taskid'),_this.data('task-type'));
89 | });
90 | },
91 | initData:function(){
92 | var toDoHtml = [];
93 | var doneHtml = [];
94 | var that = this;
95 | for(var i=0;i').html(toDoHtml.join('')).appendTo($('#todolist'));
99 |
100 | $('#todolist .hd span').text('('+data.todo.length+')');
101 |
102 | for(var i=0;i').html(doneHtml.join('')).appendTo($('#donelist'));
106 | $('#donelist .hd span').text('('+data.done.length+')');
107 | },
108 | renderItem:function(item,type){
109 | var html = '';
110 | var levelName = '';
111 | switch(item.level){
112 | case 1:levelName='非常紧急';break;
113 | case 2:levelName='紧急';break;
114 | case 3:levelName='一般';break;
115 | }
116 | html = ''+item.taskName+''+levelName+'
';
117 | return html;
118 | },
119 | bind:function(){
120 | //采用事件监听的方式是为了能够在统一一个地方设置导航的Title
121 | $('body').on('navigation.title.change',function(e,res){
122 | dd.biz.navigation.setTitle({
123 | title : res.title
124 | });
125 | });
126 | //采用事件监听的方式是为了能够在统一一个地方设置导航的右上角按钮文案及点击事件
127 | $('body').on('navigation.rightButton.change',function(e,res){
128 | dd.biz.navigation.setRight({
129 | show: res.show,//控制按钮显示, true 显示, false 隐藏, 默认true
130 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
131 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
132 | text: res.text,
133 | onSuccess:function(){
134 | res.callback&&res.callback();
135 | }
136 | });
137 | });
138 | },
139 | setLeft:function(){
140 | var that = this;
141 | dd.biz.navigation.setLeft({
142 | show: true,//控制按钮显示, true 显示, false 隐藏, 默认true
143 | control: true,//是否控制点击事件,true 控制,false 不控制, 默认false
144 | showIcon: true,//是否显示icon,true 显示, false 不显示,默认true; 注:具体UI以客户端为准
145 | onSuccess : function(result) {
146 | hash = location.hash.substring(1);
147 | if(hash=='add'){
148 | isShow = false;
149 | $('#task-add').addClass('slideOut').on('animationend', function () {
150 | if(!isShow){
151 | $(this).hide().removeClass('slideOut');
152 | }
153 | }).on('webkitAnimationEnd', function () {
154 | if(!isShow){
155 | $(this).hide().removeClass('slideOut');
156 | }
157 | });
158 | location.hash="#";
159 | that.go('');
160 | }else if(hash=='detail') {
161 | isShow = false;
162 | $('#task-detail').addClass('slideOut').on('animationend', function () {
163 | if(!isShow){
164 | $(this).hide().removeClass('slideOut');
165 | }
166 |
167 | }).on('webkitAnimationEnd', function () {
168 | if(!isShow){
169 | $(this).hide().removeClass('slideOut');
170 | }
171 | });
172 | location.hash="#";
173 | that.go('');
174 | }else{
175 | dd.biz.navigation.close();
176 | }
177 | },
178 | onFail : function(err) {}
179 | });
180 | },
181 | renerTaskDetail:function(taskId,taskType){
182 | //alert(taskType);
183 | var d = data[taskType];
184 | var curTask;
185 | for(var i=0;i[=] oldVersion
371 | **/
372 | compareVersion: function(oldVersion, newVersion, containEqual) {
373 | if (typeof oldVersion !== 'string' || typeof newVersion !== 'string') {
374 | return false;
375 | }
376 | //分割字符串为['1', '0', '1']格式
377 | var oldArray = oldVersion.split('.');
378 | var newArray = newVersion.split('.');
379 | var o, n;
380 | //从左向右对比值,值相同则跳过,不同则返回不同的值
381 | while (o === n && newArray.length > 0) {
382 | o = oldArray.shift();
383 | n = newArray.shift();
384 | }
385 | //返回不同值的比较结果
386 | if (containEqual) {
387 | return (n | 0) >= (o | 0);
388 | } else {
389 | return (n | 0) > (o | 0);
390 | }
391 | }
392 | };
393 | //注册命名空间,"device.notification.alert"生成dd.device.notification.alert
394 | var ns = function(method, fn) {
395 | var arr = method.split('.');
396 | var namespace = dd;
397 | for (var i = 0, k = arr.length; i < k; i++) {
398 | if (i === k - 1) {
399 | namespace[arr[i]] = fn;
400 | }
401 | if (typeof namespace[arr[i]] === 'undefined') {
402 | namespace[arr[i]] = {};
403 | }
404 | namespace = namespace[arr[i]];
405 | }
406 | };
407 | //设置默认属性
408 | function setDefaultValue(obj, defaults,flag) {
409 | for (var i in defaults) {
410 | if(flag){
411 | obj[i] = defaults[i];
412 | }else{
413 | obj[i] = obj[i] !== undefined ? obj[i] : defaults[i];
414 | }
415 | }
416 | }
417 | //生成器,处理传参、回调以及对特定方法特殊处理
418 | function generator(method, param) {
419 | //门神位置
420 | if (typeof WebViewJavascriptBridge === 'undefined') {
421 | return console.log('WebViewJavascriptBridge未定义,请在钉钉app打开该页面');
422 | }
423 | //开始干活
424 | //console.log('调用方法:', method, '传参:', param);
425 | var p = param || {};
426 | var successCallback = function(res) {
427 | console.log('默认成功回调', method, res);
428 | };
429 | var failCallback = function(err) {
430 | console.log('默认失败回调', method, err)
431 | };
432 | var cancelCallback = function() {};
433 | if (p.onSuccess) {
434 | successCallback = p.onSuccess;
435 | delete p.onSuccess;
436 | }
437 | if (p.onFail) {
438 | failCallback = p.onFail;
439 | delete p.onFail;
440 | }
441 | if (p.onCancel) {
442 | cancelCallback = p.onCancel;
443 | delete p.onCancel;
444 | }
445 | //统一回调处理
446 | var callback = function(response) {
447 | //console.log('统一响应:', response);
448 | var data = response || {};
449 | var code = data.errorCode;
450 | var result = data.result;
451 | if (code === '0') {
452 | successCallback && successCallback.call(null, result);
453 | } else if (code === '-1') {
454 | cancelCallback && cancelCallback.call(null, result);
455 | } else {
456 | failCallback && failCallback.call(null, result,code);
457 | }
458 | };
459 | var watch = false; //是否为监听操作, 如果是监听操作,后面要注册事件
460 | //前端包装
461 | switch (method) {
462 | case 'device.notification.alert':
463 | setDefaultValue(p, {
464 | title: '',
465 | buttonName: '确定'
466 | });
467 | break;
468 | case 'device.notification.confirm':
469 | case 'device.notification.prompt':
470 | setDefaultValue(p, {
471 | title: '',
472 | buttonLabels: ['确定', '取消']
473 | });
474 | break;
475 | case 'device.notification.vibrate':
476 | setDefaultValue(p, {
477 | duration: 300
478 | });
479 | break;
480 | //监听类方法加watch标记,和iOS客户端约定通过js注册事件的方式实现
481 | case 'device.accelerometer.watchShake':
482 | if (dd.ios) {
483 | watch = true;
484 | p.sensitivity = 3.2; //ios计算的值有偏差,特殊处理
485 | }
486 | break;
487 | case 'biz.util.openLink':
488 | setDefaultValue(p, {
489 | credible: true,
490 | showMenuBar: true
491 | });
492 | break;
493 | case 'biz.contact.choose':
494 | setDefaultValue(p, {
495 | multiple: true,
496 | startWithDepartmentId: 0,
497 | users: [],
498 | corpId: (config && config.corpId) || ''
499 | });
500 | break;
501 | case 'biz.contact.complexChoose':
502 | setDefaultValue(p, {
503 | startWithDepartmentId: 0,
504 | selectedUsers: [],
505 | selectedDepartments: [],
506 | corpId: (config && config.corpId) || ''
507 | });
508 | break;
509 | case 'biz.navigation.setLeft':
510 | case 'biz.navigation.setRight':
511 | if (dd.ios) {
512 | watch = true;
513 | }
514 | //默认值
515 | setDefaultValue(p, {
516 | show: true,
517 | control: false,
518 | showIcon: true,
519 | text: ''
520 | });
521 | break;
522 | case 'ui.pullToRefresh.enable':
523 | if (dd.ios) {
524 | watch = true;
525 | }
526 | break;
527 | case 'device.notification.toast':
528 | setDefaultValue(p, {
529 | text: 'toast',
530 | duration: (dd.android ? ((dd.duration - 3 > 0) + 0) : 3), //android设备只有大于3s和小于等于3s两种选择; iOS默认3s
531 | delay: 0
532 | });
533 | break;
534 | case 'device.notification.showPreloader':
535 | setDefaultValue(p, {
536 | text: '加载中...',
537 | showIcon: true
538 | });
539 | break;
540 | case 'biz.util.uploadImage':
541 | setDefaultValue(p, {
542 | multiple: false
543 | });
544 | break;
545 | case 'biz.util.scan':
546 | setDefaultValue(p, {
547 | type: 'qrCode'
548 | });
549 | break;
550 | case 'biz.map.search':
551 | setDefaultValue(p, {
552 | scope: 500,
553 | });
554 | break;
555 | case 'biz.util.ut':
556 | var tempValue = p.value;
557 | var tempStr=[];
558 | if(tempValue&&dd.type(tempValue)=='Object'&&window.JSON){
559 | if(dd.ios){
560 | tempValue = JSON.stringify(tempValue);
561 | }else if(dd.android){
562 | for(var i in tempValue){
563 | tempStr.push(i+"="+tempValue[i]);
564 | }
565 | tempValue = tempStr.join(',');
566 | }
567 | }else if(!window.JSON){
568 | tempValue = '';
569 | }
570 |
571 |
572 | setDefaultValue(p, {
573 | value: tempValue
574 | },true);
575 | break;
576 | case 'internal.util.encryData':
577 | var str = p.data;
578 | var tempStr=[];
579 | if(dd.type(str)=='Object'){
580 | for(var i in str){
581 | tempStr.push(i+"="+str[i]);
582 | }
583 | str = tempStr.join('&');
584 | }
585 | setDefaultValue(p, {
586 | data: str
587 | },true);
588 | break;
589 | case 'internal.request.lwp':
590 | var str = p.body;
591 | str = JSON.stringify(str);
592 |
593 | setDefaultValue(p, {
594 | body: str
595 | },true);
596 | break;
597 | case 'biz.navigation.setIcon':
598 | if (dd.ios) {
599 | watch = true;
600 | }
601 | //默认值
602 | setDefaultValue(p, {
603 | showIcon: true,
604 | iconIndex:'1'
605 | });
606 | break;
607 | case 'biz.customContact.multipleChoose':
608 | case 'biz.customContact.choose':
609 | //默认值
610 | setDefaultValue(p, {
611 | isShowCompanyName: false
612 | });
613 | break;
614 | case 'biz.navigation.setMenu':
615 | if (dd.ios) {
616 | watch = true;
617 | }
618 | break;
619 | }
620 |
621 | //消息接入:android和iOS区分处理
622 | if (dd.android) {
623 | var arr = method.split('.');
624 | var suff = arr.pop();
625 | var pre = arr.join('.');
626 | //console.log('Android对接:', pre, suff, p);
627 | WebViewJavascriptBridgeAndroid(successCallback, failCallback, pre, suff, p);
628 | //console.log(successCallback, failCallback, pre, suff, p);
629 | } else if (dd.ios) {
630 | //console.log(method, p, callback)
631 | if (watch) {
632 | WebViewJavascriptBridge.registerHandler(method, function(data, responseCallback) {
633 | callback({
634 | errorCode: '0',
635 | errorMessage: '成功',
636 | result: data
637 | });
638 | //回传给客户端,可选
639 | responseCallback && responseCallback({
640 | errorCode: '0',
641 | errorMessage: '成功'
642 | });
643 | });
644 | WebViewJavascriptBridge.callHandler(method, p);
645 | } else {
646 | WebViewJavascriptBridge.callHandler(method, p, callback);
647 | }
648 | }
649 | }
650 | //动态生成api
651 | METHODS.forEach(function(method) {
652 | ns(method, function(param) {
653 | generator(method, param);
654 | });
655 | });
656 |
657 | dd.__ns = ns;
658 |
659 | dd.biz.util.pageClick = function(obj){
660 | var k = 'open_micro_log_record_client';
661 | var visitTime = +new Date();
662 | var corpId = obj.corpId;
663 | var agentId = obj.agentId;
664 | if(!corpId){
665 | corpId = (config&&config.corpId)||'';
666 | }
667 | if (!agentId) {
668 | agentId = (config&&config.agentId)||'';
669 | };
670 |
671 | var defaultObj = {
672 | visitTime:visitTime,
673 | clickType:2,
674 | clickButton:obj.clickButton||'',
675 | url:location.href,
676 | corpId:corpId,
677 | agentId:agentId
678 | };
679 | dd.biz.util.ut({
680 | key:k,
681 | value:defaultObj
682 | });
683 | }
684 |
685 | win.dd = dd;
686 |
687 | //国际范儿
688 | if (typeof module === 'object' && module && typeof module.exports === 'object') {
689 | module.exports = dd;
690 | } else if (typeof define === 'function' && (define.amd || define.cmd)) {
691 | define(function() {
692 | return dd;
693 | })
694 | }
695 | }(this));
--------------------------------------------------------------------------------
/src/js/dingtalk.js:
--------------------------------------------------------------------------------
1 | (function(win) {
2 | 'use strict';
3 | //客户端事件
4 | var EVENTS = [
5 | 'backbutton',
6 | 'online',
7 | 'offline',
8 | 'pause',
9 | 'resume',
10 | 'swipeRefresh' //0.0.5
11 | ];
12 | //方法列表
13 | var METHODS = [
14 | 'device.notification.alert',
15 | 'device.notification.confirm',
16 | 'device.notification.prompt',
17 | 'device.notification.vibrate',
18 | 'device.accelerometer.watchShake',
19 | 'device.accelerometer.clearShake',
20 | 'biz.util.open',
21 | 'biz.util.openLink',
22 | 'biz.util.share',
23 | 'biz.util.ut',
24 | 'biz.util.datepicker', //android
25 | 'biz.util.timepicker', //android
26 | 'biz.user.get',
27 | 'biz.navigation.setLeft',
28 | 'biz.navigation.setRight',
29 | 'biz.navigation.setTitle',
30 | 'biz.navigation.back',
31 | // v0.0.1
32 | 'device.notification.toast',
33 | 'device.notification.showPreloader',
34 | 'device.notification.hidePreloader',
35 | 'device.geolocation.get',
36 | 'biz.util.uploadImage',
37 | 'biz.util.previewImage',
38 | //v0.0.2
39 | /**
40 | * ios日期选择器
41 | * 'biz.util.textarea' 改为 ui.input.plain
42 | **/
43 | 'ui.input.plain',
44 | 'device.notification.actionSheet',
45 | 'biz.util.qrcode',
46 | 'device.connection.getNetworkType',
47 | 'runtime.info',
48 | //v0.0.3
49 | /**
50 | * 发钉 biz.ding.post
51 | * 打电话 biz.telephone.call
52 | * 选群组 biz.chat.chooseConversation
53 | **/
54 | 'biz.ding.post',
55 | 'biz.telephone.call',
56 | 'biz.chat.chooseConversation',
57 | //v0.0.4
58 | /**
59 | * 拉起联系人添加页面 biz.util.open contactAdd
60 | * 消息会话+号企业群聊天 biz.contact.createGroup
61 | * select组件 biz.util.chosen
62 | * 日期+时间 biz.util.datetimepicker
63 | **/
64 | 'biz.contact.createGroup',
65 | //'biz.util.chosen', //有bug,0.0.5版开启
66 | 'biz.util.datetimepicker',
67 | //v0.0.5
68 | /**
69 | * 下拉组件iOS bugfix,上一版废弃
70 | * 获取通用唯一识别码
71 | * 获取热点接入信息
72 | * 检测应用是否安装
73 | * 启动第三方app
74 | * 设置导航进度条颜色
75 | * 新增事件 swipeRefresh
76 | * 请求授权码,免登改造用
77 | * 启用下拉刷新功能
78 | * 收起下拉刷新控件
79 | * 禁用下拉刷新功能
80 | * 启用webview下拉弹性效果
81 | * 禁用webview下拉弹性效果
82 | **/
83 | 'biz.util.chosen', //下拉组件
84 | 'device.base.getUUID', //获取通用唯一识别码
85 | 'device.base.getInterface', //获取热点接入信息
86 | 'device.launcher.checkInstalledApps', //检测应用是否安装
87 | 'device.launcher.launchApp', //启动第三方app
88 |
89 | 'ui.progressBar.setColors', //设置顶部进度条颜色
90 | 'runtime.permission.requestAuthCode', //请求授权码,免登改造用
91 | 'runtime.permission.requestJsApis', //轻轻jsapi,隐藏方法,只限sdk内部调用,TODO: 上线时注释掉
92 |
93 | 'ui.pullToRefresh.enable', //启用下拉刷新功能
94 | 'ui.pullToRefresh.stop', //收起下拉刷新控件
95 | 'ui.pullToRefresh.disable', //禁用下拉刷新功能
96 | 'ui.webViewBounce.enable', //启用webview下拉弹性效果
97 | 'ui.webViewBounce.disable', //禁用webview下拉弹性效果
98 |
99 | //v0.0.6
100 | /**
101 | * 获取会话信息
102 | * 地图搜索
103 | * 地图定位
104 | * 扫码
105 | * 修改企业通讯录选人
106 | * 企业通讯录同时选人,选部门
107 | **/
108 | 'biz.chat.getConversationInfo', //获取会话信息
109 | 'biz.map.search', //地图搜索
110 | 'biz.map.locate', //地图定位
111 | 'biz.util.scan', //扫码
112 | 'biz.contact.choose', //修改企业通讯录选人
113 | 'biz.contact.complexChoose', //企业通讯录同时选人,选部门
114 | 'util.localStorage.getItem', //本地存储读
115 | 'util.localStorage.setItem', //本地存储写
116 | 'util.localStorage.removeItem', //本地存储移除操作
117 | 'biz.navigation.createEditor', //创建通用组件
118 | 'biz.navigation.finishEditor', //销毁通用组件
119 |
120 | //v0.0.7
121 | /**
122 | **/
123 | 'biz.chat.pickConversation', //选群组
124 |
125 | //0.0.8
126 | 'device.notification.modal', //弹浮层
127 | 'biz.navigation.setIcon', //设置导航icon
128 | 'biz.navigation.close', //关闭webview
129 | 'biz.util.uploadImageFromCamera',
130 |
131 | //0.0.9
132 | 'internal.lwp.call',//lwp接口
133 | //0.1.0
134 | 'device.geolocation.openGps',//打开设置,只有android有效
135 | 'biz.util.test', //测试接口
136 | 'internal.microapp.checkInstalled',//检测微应用是否安装
137 | 'internal.user.getRole', //获取角色
138 |
139 | //0.1.1
140 | 'device.notification.extendModal', //谈层,支持多张图片
141 | 'internal.request.lwp', //lwp通道
142 | 'biz.user.secretID', //获取用户登录唯一标识
143 | 'internal.util.encryData', //参数加密生成key
144 | 'biz.customContact.choose', //自定义选人组件
145 | 'biz.customContact.multipleChoose', //自定义选人组件(多选)
146 | 'biz.util.pageClick', //页面打点
147 |
148 | //0.1.2
149 | 'biz.chat.chooseConversationByCorpId', //选择企业会话v2.6新增
150 | 'biz.chat.toConversation', //跳转至对应的会话v2.6新增
151 | 'device.base.getSettings', //获取手机设置待定
152 | 'internal.log.upload', //上传日志v2.6新增
153 |
154 | 'biz.navigation.goBack',
155 |
156 | 'ui.nav.preload',
157 | 'ui.nav.go',
158 | 'ui.nav.recycle',
159 | 'ui.nav.close',
160 | 'ui.nav.getCurrentId',
161 |
162 | 'runtime.message.post',
163 | 'runtime.message.fetch',
164 |
165 | 'biz.navigation.setMenu',
166 |
167 | 'ui.drawer.init',
168 | 'ui.drawer.config',
169 | 'ui.drawer.enable',
170 | 'ui.drawer.disable',
171 | 'ui.drawer.open',
172 | 'ui.drawer.close',
173 | 'ui.drawer.close2'
174 | ];
175 | var JSSDK_VERSION = "0.6.0";
176 | var ua = win.navigator.userAgent;
177 | var matches = ua.match(/AliApp\(\w+\/([a-zA-Z0-9.-]+)\)/);
178 | //android兼容处理
179 | if (matches === null) {
180 | matches = ua.match(/DingTalk\/([a-zA-Z0-9.-]+)/);
181 | }
182 | var version = matches && matches[1];
183 | var authorised = false; //是否已校验通过
184 | var already = false; //是否已初始化
185 | var config = null; //缓存config参数
186 | var authMethod = 'runtime.permission.requestJsApis'; //权限校验方法名
187 | var errorHandle = null; //缓存error回调
188 | var bridgeReady = false;
189 | var dd = {
190 | ios: (/iPhone|iPad|iPod/i).test(ua),
191 | android: (/Android/i).test(ua),
192 | version: version,
193 | support: version === '1.2.2' || version === '1.3.2',
194 | ability: '', //空为初始值,具体值从客户端读取,格式为x.x.x
195 | config: function(obj) {
196 | //这里对用户传进来的参数进行过滤
197 | if (!obj) {
198 | return;
199 | }
200 | //TODO: 参数名待确认
201 | config = {
202 | corpId: obj.corpId,
203 | appId:obj.appId||-1,
204 | timeStamp: obj.timeStamp,
205 | nonceStr: obj.nonceStr,
206 | signature: obj.signature,
207 | jsApiList: obj.jsApiList
208 | };
209 | if(obj.agentId){
210 | config.agentId = obj.agentId;
211 | }
212 | },
213 | error: function(fn) {
214 | errorHandle = fn;
215 | },
216 | ready: function(callback) {
217 | //总控
218 | var fn = function(bridge) {
219 | if (!bridge) {
220 | return console.log('bridge初始化失败')
221 | }
222 | //callback(bridge);
223 | //TODO: 判断config,进行权限校验
224 | if (config === null||!config.signature) {
225 | //console.log('没有配置dd.config')
226 | callback(bridge);
227 | } else {
228 | //console.log('配置了dd.config', config)
229 | //权限校验
230 | if (dd.ios) {
231 | bridge.callHandler(authMethod, config, function(response) {
232 | var data = response || {};
233 | var code = data.errorCode;
234 | var msg = data.errorMessage || '';
235 | var result = data.result;
236 | if (code === '0') {
237 | callback(bridge);
238 | } else {
239 | setTimeout(function() {
240 | errorHandle && errorHandle({
241 | message: '权限校验失败 ' + msg,
242 | errorCode: 3
243 | });
244 | });
245 | }
246 | });
247 | } else if (dd.android) {
248 | var arr = authMethod.split('.');
249 | var suff = arr.pop();
250 | var pre = arr.join('.');
251 | bridge(function() {
252 | callback(bridge);
253 | }, function(err) {
254 | setTimeout(function() {
255 | var msg = err&&err.errorMessage || '';
256 | errorHandle && errorHandle({
257 | message: '权限校验失败 ' + msg,
258 | errorCode: 3
259 | });
260 | });
261 | }, pre, suff, config);
262 | }
263 | }
264 | //callback(bridge);
265 | //第一次初始化后要做的事情
266 | if (already === false) {
267 | already = true;
268 | //自定义事件
269 | EVENTS.forEach(function(evt) {
270 | if (dd.ios) {
271 | bridge.registerHandler(evt, function(data, responseCallback) {
272 | //console.log('注册事件默认回调', data, responseCallback);
273 | var e = document.createEvent('HTMLEvents');
274 | e.data = data;
275 | e.initEvent(evt);
276 | document.dispatchEvent(e);
277 | responseCallback && responseCallback({
278 | errorCode: '0',
279 | errorMessage: '成功'
280 | })
281 | });
282 | }
283 | });
284 |
285 | if (config === null) {
286 | var conf = {
287 | url: encodeURIComponent(window.location.href),
288 | js: JSSDK_VERSION,
289 | cid: config && config.corpId || ''
290 | };
291 | //打点
292 | dd.biz.util.ut({
293 | key: 'dd_open_js_monitor',
294 | value: JSON.stringify(conf),
295 | onSuccess: function(res) {
296 | //console.log('dd_open_js_monitor ut打点成功', res);
297 | }
298 | });
299 | }
300 | }
301 | };
302 | //已经完成初始化的情况
303 | if (dd.ios && win.WebViewJavascriptBridge) {
304 | //防止ready延迟导致的问题
305 | //init后,register的方法才能收到回调,重现方法:首次触发dd.ready延时
306 | try {
307 | WebViewJavascriptBridge.init(function(data, responseCallback) {
308 | //客户端send
309 | //console.log('WebViewJavascriptBridge init: ', data, responseCallback);
310 | });
311 | } catch (e) {
312 | console.log(e.message);
313 | }
314 | return fn(WebViewJavascriptBridge);
315 | } else if (dd.android && win.WebViewJavascriptBridgeAndroid) {
316 | return fn(WebViewJavascriptBridgeAndroid);
317 | }
318 | //初始化主流程
319 | if (dd.ios) {
320 | //console.log('开始监听WebViewJavascriptBridgeReady事件');
321 | document.addEventListener('WebViewJavascriptBridgeReady', function() {
322 | if (typeof WebViewJavascriptBridge === 'undefined') {
323 | return console.log('WebViewJavascriptBridge 未定义');
324 | }
325 | try {
326 | WebViewJavascriptBridge.init(function(data, responseCallback) {
327 | //客户端send
328 | //console.log('WebViewJavascriptBridge init: ', data, responseCallback);
329 | });
330 | } catch (e) {
331 | console.log(e.message);
332 | }
333 | bridgeReady = true;
334 | fn(WebViewJavascriptBridge);
335 |
336 | }, false);
337 | } else if (dd.android) {
338 | var _run = function() {
339 | try {
340 | win.WebViewJavascriptBridgeAndroid = win.nuva.require();
341 | bridgeReady = true;
342 | fn(WebViewJavascriptBridgeAndroid);
343 | } catch (e) {
344 | console.log('window.nuva.require出错', e.message);
345 | fn(null);
346 | }
347 | };
348 | //兼容
349 | if (win.nuva) {
350 | _run();
351 | } else {
352 | document.addEventListener('runtimeready', function() {
353 | _run();
354 | }, false);
355 | }
356 | //
357 | } else {
358 | return console.log('很抱歉,尚未支持您所持设备');
359 | }
360 | },
361 | type:function(obj){
362 | //"Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window" ,"Constructor"
363 | return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
364 | },
365 | //版本号对比方法,比如判断1.5.0和1.11.0的大小
366 | /**
367 | * oldVersion 老版本
368 | * newVersion 新版本
369 | * containEqual 是否包含相等的情况
370 | * result: newVersion >[=] oldVersion
371 | **/
372 | compareVersion: function(oldVersion, newVersion, containEqual) {
373 | if (typeof oldVersion !== 'string' || typeof newVersion !== 'string') {
374 | return false;
375 | }
376 | //分割字符串为['1', '0', '1']格式
377 | var oldArray = oldVersion.split('.');
378 | var newArray = newVersion.split('.');
379 | var o, n;
380 | //从左向右对比值,值相同则跳过,不同则返回不同的值
381 | while (o === n && newArray.length > 0) {
382 | o = oldArray.shift();
383 | n = newArray.shift();
384 | }
385 | //返回不同值的比较结果
386 | if (containEqual) {
387 | return (n | 0) >= (o | 0);
388 | } else {
389 | return (n | 0) > (o | 0);
390 | }
391 | }
392 | };
393 | //注册命名空间,"device.notification.alert"生成dd.device.notification.alert
394 | var ns = function(method, fn) {
395 | var arr = method.split('.');
396 | var namespace = dd;
397 | for (var i = 0, k = arr.length; i < k; i++) {
398 | if (i === k - 1) {
399 | namespace[arr[i]] = fn;
400 | }
401 | if (typeof namespace[arr[i]] === 'undefined') {
402 | namespace[arr[i]] = {};
403 | }
404 | namespace = namespace[arr[i]];
405 | }
406 | };
407 | //设置默认属性
408 | function setDefaultValue(obj, defaults,flag) {
409 | for (var i in defaults) {
410 | if(flag){
411 | obj[i] = defaults[i];
412 | }else{
413 | obj[i] = obj[i] !== undefined ? obj[i] : defaults[i];
414 | }
415 | }
416 | }
417 | //生成器,处理传参、回调以及对特定方法特殊处理
418 | function generator(method, param) {
419 | //门神位置
420 | if (typeof WebViewJavascriptBridge === 'undefined') {
421 | return console.log('WebViewJavascriptBridge未定义,请在钉钉app打开该页面');
422 | }
423 | //开始干活
424 | //console.log('调用方法:', method, '传参:', param);
425 | var p = param || {};
426 | var successCallback = function(res) {
427 | console.log('默认成功回调', method, res);
428 | };
429 | var failCallback = function(err) {
430 | console.log('默认失败回调', method, err)
431 | };
432 | var cancelCallback = function() {};
433 | if (p.onSuccess) {
434 | successCallback = p.onSuccess;
435 | delete p.onSuccess;
436 | }
437 | if (p.onFail) {
438 | failCallback = p.onFail;
439 | delete p.onFail;
440 | }
441 | if (p.onCancel) {
442 | cancelCallback = p.onCancel;
443 | delete p.onCancel;
444 | }
445 | //统一回调处理
446 | var callback = function(response) {
447 | //console.log('统一响应:', response);
448 | var data = response || {};
449 | var code = data.errorCode;
450 | var result = data.result;
451 | if (code === '0') {
452 | successCallback && successCallback.call(null, result);
453 | } else if (code === '-1') {
454 | cancelCallback && cancelCallback.call(null, result);
455 | } else {
456 | failCallback && failCallback.call(null, result,code);
457 | }
458 | };
459 | var watch = false; //是否为监听操作, 如果是监听操作,后面要注册事件
460 | //前端包装
461 | switch (method) {
462 | case 'device.notification.alert':
463 | setDefaultValue(p, {
464 | title: '',
465 | buttonName: '确定'
466 | });
467 | break;
468 | case 'device.notification.confirm':
469 | case 'device.notification.prompt':
470 | setDefaultValue(p, {
471 | title: '',
472 | buttonLabels: ['确定', '取消']
473 | });
474 | break;
475 | case 'device.notification.vibrate':
476 | setDefaultValue(p, {
477 | duration: 300
478 | });
479 | break;
480 | //监听类方法加watch标记,和iOS客户端约定通过js注册事件的方式实现
481 | case 'device.accelerometer.watchShake':
482 | if (dd.ios) {
483 | watch = true;
484 | p.sensitivity = 3.2; //ios计算的值有偏差,特殊处理
485 | }
486 | break;
487 | case 'biz.util.openLink':
488 | setDefaultValue(p, {
489 | credible: true,
490 | showMenuBar: true
491 | });
492 | break;
493 | case 'biz.contact.choose':
494 | setDefaultValue(p, {
495 | multiple: true,
496 | startWithDepartmentId: 0,
497 | users: [],
498 | corpId: (config && config.corpId) || ''
499 | });
500 | break;
501 | case 'biz.contact.complexChoose':
502 | setDefaultValue(p, {
503 | startWithDepartmentId: 0,
504 | selectedUsers: [],
505 | selectedDepartments: [],
506 | corpId: (config && config.corpId) || ''
507 | });
508 | break;
509 | case 'biz.navigation.setLeft':
510 | case 'biz.navigation.setRight':
511 | if (dd.ios) {
512 | watch = true;
513 | }
514 | //默认值
515 | setDefaultValue(p, {
516 | show: true,
517 | control: false,
518 | showIcon: true,
519 | text: ''
520 | });
521 | break;
522 | case 'ui.pullToRefresh.enable':
523 | if (dd.ios) {
524 | watch = true;
525 | }
526 | break;
527 | case 'device.notification.toast':
528 | setDefaultValue(p, {
529 | text: 'toast',
530 | duration: (dd.android ? ((dd.duration - 3 > 0) + 0) : 3), //android设备只有大于3s和小于等于3s两种选择; iOS默认3s
531 | delay: 0
532 | });
533 | break;
534 | case 'device.notification.showPreloader':
535 | setDefaultValue(p, {
536 | text: '加载中...',
537 | showIcon: true
538 | });
539 | break;
540 | case 'biz.util.uploadImage':
541 | setDefaultValue(p, {
542 | multiple: false
543 | });
544 | break;
545 | case 'biz.util.scan':
546 | setDefaultValue(p, {
547 | type: 'qrCode'
548 | });
549 | break;
550 | case 'biz.map.search':
551 | setDefaultValue(p, {
552 | scope: 500,
553 | });
554 | break;
555 | case 'biz.util.ut':
556 | var tempValue = p.value;
557 | var tempStr=[];
558 | if(tempValue&&dd.type(tempValue)=='Object'&&window.JSON){
559 | if(dd.ios){
560 | tempValue = JSON.stringify(tempValue);
561 | }else if(dd.android){
562 | for(var i in tempValue){
563 | tempStr.push(i+"="+tempValue[i]);
564 | }
565 | tempValue = tempStr.join(',');
566 | }
567 | }else if(!window.JSON){
568 | tempValue = '';
569 | }
570 |
571 |
572 | setDefaultValue(p, {
573 | value: tempValue
574 | },true);
575 | break;
576 | case 'internal.util.encryData':
577 | var str = p.data;
578 | var tempStr=[];
579 | if(dd.type(str)=='Object'){
580 | for(var i in str){
581 | tempStr.push(i+"="+str[i]);
582 | }
583 | str = tempStr.join('&');
584 | }
585 | setDefaultValue(p, {
586 | data: str
587 | },true);
588 | break;
589 | case 'internal.request.lwp':
590 | var str = p.body;
591 | str = JSON.stringify(str);
592 |
593 | setDefaultValue(p, {
594 | body: str
595 | },true);
596 | break;
597 | case 'biz.navigation.setIcon':
598 | if (dd.ios) {
599 | watch = true;
600 | }
601 | //默认值
602 | setDefaultValue(p, {
603 | showIcon: true,
604 | iconIndex:'1'
605 | });
606 | break;
607 | case 'biz.customContact.multipleChoose':
608 | case 'biz.customContact.choose':
609 | //默认值
610 | setDefaultValue(p, {
611 | isShowCompanyName: false
612 | });
613 | break;
614 | case 'biz.navigation.setMenu':
615 | if (dd.ios) {
616 | watch = true;
617 | }
618 | break;
619 | }
620 |
621 | //消息接入:android和iOS区分处理
622 | if (dd.android) {
623 | var arr = method.split('.');
624 | var suff = arr.pop();
625 | var pre = arr.join('.');
626 | //console.log('Android对接:', pre, suff, p);
627 | WebViewJavascriptBridgeAndroid(successCallback, failCallback, pre, suff, p);
628 | //console.log(successCallback, failCallback, pre, suff, p);
629 | } else if (dd.ios) {
630 | //console.log(method, p, callback)
631 | if (watch) {
632 | WebViewJavascriptBridge.registerHandler(method, function(data, responseCallback) {
633 | callback({
634 | errorCode: '0',
635 | errorMessage: '成功',
636 | result: data
637 | });
638 | //回传给客户端,可选
639 | responseCallback && responseCallback({
640 | errorCode: '0',
641 | errorMessage: '成功'
642 | });
643 | });
644 | WebViewJavascriptBridge.callHandler(method, p);
645 | } else {
646 | WebViewJavascriptBridge.callHandler(method, p, callback);
647 | }
648 | }
649 | }
650 | //动态生成api
651 | METHODS.forEach(function(method) {
652 | ns(method, function(param) {
653 | generator(method, param);
654 | });
655 | });
656 |
657 | dd.__ns = ns;
658 |
659 | dd.biz.util.pageClick = function(obj){
660 | var k = 'open_micro_log_record_client';
661 | var visitTime = +new Date();
662 | var corpId = obj.corpId;
663 | var agentId = obj.agentId;
664 | if(!corpId){
665 | corpId = (config&&config.corpId)||'';
666 | }
667 | if (!agentId) {
668 | agentId = (config&&config.agentId)||'';
669 | };
670 |
671 | var defaultObj = {
672 | visitTime:visitTime,
673 | clickType:2,
674 | clickButton:obj.clickButton||'',
675 | url:location.href,
676 | corpId:corpId,
677 | agentId:agentId
678 | };
679 | dd.biz.util.ut({
680 | key:k,
681 | value:defaultObj
682 | });
683 | }
684 |
685 | win.dd = dd;
686 |
687 | //国际范儿
688 | if (typeof module === 'object' && module && typeof module.exports === 'object') {
689 | module.exports = dd;
690 | } else if (typeof define === 'function' && (define.amd || define.cmd)) {
691 | define(function() {
692 | return dd;
693 | })
694 | }
695 | }(this));
--------------------------------------------------------------------------------
/dist/js/fastclick.js:
--------------------------------------------------------------------------------
1 | ;(function () {
2 | 'use strict';
3 |
4 | /**
5 | * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
6 | *
7 | * @codingstandard ftlabs-jsv2
8 | * @copyright The Financial Times Limited [All Rights Reserved]
9 | * @license MIT License (see LICENSE.txt)
10 | */
11 |
12 | /*jslint browser:true, node:true*/
13 | /*global define, Event, Node*/
14 |
15 |
16 | /**
17 | * Instantiate fast-clicking listeners on the specified layer.
18 | *
19 | * @constructor
20 | * @param {Element} layer The layer to listen on
21 | * @param {Object} [options={}] The options to override the defaults
22 | */
23 | function FastClick(layer, options) {
24 | var oldOnClick;
25 |
26 | options = options || {};
27 |
28 | /**
29 | * Whether a click is currently being tracked.
30 | *
31 | * @type boolean
32 | */
33 | this.trackingClick = false;
34 |
35 |
36 | /**
37 | * Timestamp for when click tracking started.
38 | *
39 | * @type number
40 | */
41 | this.trackingClickStart = 0;
42 |
43 |
44 | /**
45 | * The element being tracked for a click.
46 | *
47 | * @type EventTarget
48 | */
49 | this.targetElement = null;
50 |
51 |
52 | /**
53 | * X-coordinate of touch start event.
54 | *
55 | * @type number
56 | */
57 | this.touchStartX = 0;
58 |
59 |
60 | /**
61 | * Y-coordinate of touch start event.
62 | *
63 | * @type number
64 | */
65 | this.touchStartY = 0;
66 |
67 |
68 | /**
69 | * ID of the last touch, retrieved from Touch.identifier.
70 | *
71 | * @type number
72 | */
73 | this.lastTouchIdentifier = 0;
74 |
75 |
76 | /**
77 | * Touchmove boundary, beyond which a click will be cancelled.
78 | *
79 | * @type number
80 | */
81 | this.touchBoundary = options.touchBoundary || 10;
82 |
83 |
84 | /**
85 | * The FastClick layer.
86 | *
87 | * @type Element
88 | */
89 | this.layer = layer;
90 |
91 | /**
92 | * The minimum time between tap(touchstart and touchend) events
93 | *
94 | * @type number
95 | */
96 | this.tapDelay = options.tapDelay || 200;
97 |
98 | /**
99 | * The maximum time for a tap
100 | *
101 | * @type number
102 | */
103 | this.tapTimeout = options.tapTimeout || 700;
104 |
105 | if (FastClick.notNeeded(layer)) {
106 | return;
107 | }
108 |
109 | // Some old versions of Android don't have Function.prototype.bind
110 | function bind(method, context) {
111 | return function() { return method.apply(context, arguments); };
112 | }
113 |
114 |
115 | var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
116 | var context = this;
117 | for (var i = 0, l = methods.length; i < l; i++) {
118 | context[methods[i]] = bind(context[methods[i]], context);
119 | }
120 |
121 | // Set up event handlers as required
122 | if (deviceIsAndroid) {
123 | layer.addEventListener('mouseover', this.onMouse, true);
124 | layer.addEventListener('mousedown', this.onMouse, true);
125 | layer.addEventListener('mouseup', this.onMouse, true);
126 | }
127 |
128 | layer.addEventListener('click', this.onClick, true);
129 | layer.addEventListener('touchstart', this.onTouchStart, false);
130 | layer.addEventListener('touchmove', this.onTouchMove, false);
131 | layer.addEventListener('touchend', this.onTouchEnd, false);
132 | layer.addEventListener('touchcancel', this.onTouchCancel, false);
133 |
134 | // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
135 | // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
136 | // layer when they are cancelled.
137 | if (!Event.prototype.stopImmediatePropagation) {
138 | layer.removeEventListener = function(type, callback, capture) {
139 | var rmv = Node.prototype.removeEventListener;
140 | if (type === 'click') {
141 | rmv.call(layer, type, callback.hijacked || callback, capture);
142 | } else {
143 | rmv.call(layer, type, callback, capture);
144 | }
145 | };
146 |
147 | layer.addEventListener = function(type, callback, capture) {
148 | var adv = Node.prototype.addEventListener;
149 | if (type === 'click') {
150 | adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
151 | if (!event.propagationStopped) {
152 | callback(event);
153 | }
154 | }), capture);
155 | } else {
156 | adv.call(layer, type, callback, capture);
157 | }
158 | };
159 | }
160 |
161 | // If a handler is already declared in the element's onclick attribute, it will be fired before
162 | // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
163 | // adding it as listener.
164 | if (typeof layer.onclick === 'function') {
165 |
166 | // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
167 | // - the old one won't work if passed to addEventListener directly.
168 | oldOnClick = layer.onclick;
169 | layer.addEventListener('click', function(event) {
170 | oldOnClick(event);
171 | }, false);
172 | layer.onclick = null;
173 | }
174 | }
175 |
176 | /**
177 | * Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
178 | *
179 | * @type boolean
180 | */
181 | var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;
182 |
183 | /**
184 | * Android requires exceptions.
185 | *
186 | * @type boolean
187 | */
188 | var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;
189 |
190 |
191 | /**
192 | * iOS requires exceptions.
193 | *
194 | * @type boolean
195 | */
196 | var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;
197 |
198 |
199 | /**
200 | * iOS 4 requires an exception for select elements.
201 | *
202 | * @type boolean
203 | */
204 | var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
205 |
206 |
207 | /**
208 | * iOS 6.0-7.* requires the target element to be manually derived
209 | *
210 | * @type boolean
211 | */
212 | var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);
213 |
214 | /**
215 | * BlackBerry requires exceptions.
216 | *
217 | * @type boolean
218 | */
219 | var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;
220 |
221 | /**
222 | * Determine whether a given element requires a native click.
223 | *
224 | * @param {EventTarget|Element} target Target DOM element
225 | * @returns {boolean} Returns true if the element needs a native click
226 | */
227 | FastClick.prototype.needsClick = function(target) {
228 | switch (target.nodeName.toLowerCase()) {
229 |
230 | // Don't send a synthetic click to disabled inputs (issue #62)
231 | case 'button':
232 | case 'select':
233 | case 'textarea':
234 | if (target.disabled) {
235 | return true;
236 | }
237 |
238 | break;
239 | case 'input':
240 |
241 | // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
242 | if ((deviceIsIOS && target.type === 'file') || target.disabled) {
243 | return true;
244 | }
245 |
246 | break;
247 | case 'label':
248 | case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
249 | case 'video':
250 | return true;
251 | }
252 |
253 | return (/\bneedsclick\b/).test(target.className);
254 | };
255 |
256 |
257 | /**
258 | * Determine whether a given element requires a call to focus to simulate click into element.
259 | *
260 | * @param {EventTarget|Element} target Target DOM element
261 | * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
262 | */
263 | FastClick.prototype.needsFocus = function(target) {
264 | switch (target.nodeName.toLowerCase()) {
265 | case 'textarea':
266 | return true;
267 | case 'select':
268 | return !deviceIsAndroid;
269 | case 'input':
270 | switch (target.type) {
271 | case 'button':
272 | case 'checkbox':
273 | case 'file':
274 | case 'image':
275 | case 'radio':
276 | case 'submit':
277 | return false;
278 | }
279 |
280 | // No point in attempting to focus disabled inputs
281 | return !target.disabled && !target.readOnly;
282 | default:
283 | return (/\bneedsfocus\b/).test(target.className);
284 | }
285 | };
286 |
287 |
288 | /**
289 | * Send a click event to the specified element.
290 | *
291 | * @param {EventTarget|Element} targetElement
292 | * @param {Event} event
293 | */
294 | FastClick.prototype.sendClick = function(targetElement, event) {
295 | var clickEvent, touch;
296 |
297 | // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
298 | if (document.activeElement && document.activeElement !== targetElement) {
299 | document.activeElement.blur();
300 | }
301 |
302 | touch = event.changedTouches[0];
303 |
304 | // Synthesise a click event, with an extra attribute so it can be tracked
305 | clickEvent = document.createEvent('MouseEvents');
306 | clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
307 | clickEvent.forwardedTouchEvent = true;
308 | targetElement.dispatchEvent(clickEvent);
309 | };
310 |
311 | FastClick.prototype.determineEventType = function(targetElement) {
312 |
313 | //Issue #159: Android Chrome Select Box does not open with a synthetic click event
314 | if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
315 | return 'mousedown';
316 | }
317 |
318 | return 'click';
319 | };
320 |
321 |
322 | /**
323 | * @param {EventTarget|Element} targetElement
324 | */
325 | FastClick.prototype.focus = function(targetElement) {
326 | var length;
327 |
328 | // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
329 | if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
330 | length = targetElement.value.length;
331 | targetElement.setSelectionRange(length, length);
332 | } else {
333 | targetElement.focus();
334 | }
335 | };
336 |
337 |
338 | /**
339 | * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
340 | *
341 | * @param {EventTarget|Element} targetElement
342 | */
343 | FastClick.prototype.updateScrollParent = function(targetElement) {
344 | var scrollParent, parentElement;
345 |
346 | scrollParent = targetElement.fastClickScrollParent;
347 |
348 | // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
349 | // target element was moved to another parent.
350 | if (!scrollParent || !scrollParent.contains(targetElement)) {
351 | parentElement = targetElement;
352 | do {
353 | if (parentElement.scrollHeight > parentElement.offsetHeight) {
354 | scrollParent = parentElement;
355 | targetElement.fastClickScrollParent = parentElement;
356 | break;
357 | }
358 |
359 | parentElement = parentElement.parentElement;
360 | } while (parentElement);
361 | }
362 |
363 | // Always update the scroll top tracker if possible.
364 | if (scrollParent) {
365 | scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
366 | }
367 | };
368 |
369 |
370 | /**
371 | * @param {EventTarget} targetElement
372 | * @returns {Element|EventTarget}
373 | */
374 | FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
375 |
376 | // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
377 | if (eventTarget.nodeType === Node.TEXT_NODE) {
378 | return eventTarget.parentNode;
379 | }
380 |
381 | return eventTarget;
382 | };
383 |
384 |
385 | /**
386 | * On touch start, record the position and scroll offset.
387 | *
388 | * @param {Event} event
389 | * @returns {boolean}
390 | */
391 | FastClick.prototype.onTouchStart = function(event) {
392 | var targetElement, touch, selection;
393 |
394 | // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
395 | if (event.targetTouches.length > 1) {
396 | return true;
397 | }
398 |
399 | targetElement = this.getTargetElementFromEventTarget(event.target);
400 | touch = event.targetTouches[0];
401 |
402 | if (deviceIsIOS) {
403 |
404 | // Only trusted events will deselect text on iOS (issue #49)
405 | selection = window.getSelection();
406 | if (selection.rangeCount && !selection.isCollapsed) {
407 | return true;
408 | }
409 |
410 | if (!deviceIsIOS4) {
411 |
412 | // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
413 | // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
414 | // with the same identifier as the touch event that previously triggered the click that triggered the alert.
415 | // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
416 | // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
417 | // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
418 | // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
419 | // random integers, it's safe to to continue if the identifier is 0 here.
420 | if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
421 | event.preventDefault();
422 | return false;
423 | }
424 |
425 | this.lastTouchIdentifier = touch.identifier;
426 |
427 | // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
428 | // 1) the user does a fling scroll on the scrollable layer
429 | // 2) the user stops the fling scroll with another tap
430 | // then the event.target of the last 'touchend' event will be the element that was under the user's finger
431 | // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
432 | // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
433 | this.updateScrollParent(targetElement);
434 | }
435 | }
436 |
437 | this.trackingClick = true;
438 | this.trackingClickStart = event.timeStamp;
439 | this.targetElement = targetElement;
440 |
441 | this.touchStartX = touch.pageX;
442 | this.touchStartY = touch.pageY;
443 |
444 | // Prevent phantom clicks on fast double-tap (issue #36)
445 | if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
446 | event.preventDefault();
447 | }
448 |
449 | return true;
450 | };
451 |
452 |
453 | /**
454 | * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
455 | *
456 | * @param {Event} event
457 | * @returns {boolean}
458 | */
459 | FastClick.prototype.touchHasMoved = function(event) {
460 | var touch = event.changedTouches[0], boundary = this.touchBoundary;
461 |
462 | if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
463 | return true;
464 | }
465 |
466 | return false;
467 | };
468 |
469 |
470 | /**
471 | * Update the last position.
472 | *
473 | * @param {Event} event
474 | * @returns {boolean}
475 | */
476 | FastClick.prototype.onTouchMove = function(event) {
477 | if (!this.trackingClick) {
478 | return true;
479 | }
480 |
481 | // If the touch has moved, cancel the click tracking
482 | if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
483 | this.trackingClick = false;
484 | this.targetElement = null;
485 | }
486 |
487 | return true;
488 | };
489 |
490 |
491 | /**
492 | * Attempt to find the labelled control for the given label element.
493 | *
494 | * @param {EventTarget|HTMLLabelElement} labelElement
495 | * @returns {Element|null}
496 | */
497 | FastClick.prototype.findControl = function(labelElement) {
498 |
499 | // Fast path for newer browsers supporting the HTML5 control attribute
500 | if (labelElement.control !== undefined) {
501 | return labelElement.control;
502 | }
503 |
504 | // All browsers under test that support touch events also support the HTML5 htmlFor attribute
505 | if (labelElement.htmlFor) {
506 | return document.getElementById(labelElement.htmlFor);
507 | }
508 |
509 | // If no for attribute exists, attempt to retrieve the first labellable descendant element
510 | // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
511 | return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
512 | };
513 |
514 |
515 | /**
516 | * On touch end, determine whether to send a click event at once.
517 | *
518 | * @param {Event} event
519 | * @returns {boolean}
520 | */
521 | FastClick.prototype.onTouchEnd = function(event) {
522 | var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
523 |
524 | if (!this.trackingClick) {
525 | return true;
526 | }
527 |
528 | // Prevent phantom clicks on fast double-tap (issue #36)
529 | if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
530 | this.cancelNextClick = true;
531 | return true;
532 | }
533 |
534 | if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
535 | return true;
536 | }
537 |
538 | // Reset to prevent wrong click cancel on input (issue #156).
539 | this.cancelNextClick = false;
540 |
541 | this.lastClickTime = event.timeStamp;
542 |
543 | trackingClickStart = this.trackingClickStart;
544 | this.trackingClick = false;
545 | this.trackingClickStart = 0;
546 |
547 | // On some iOS devices, the targetElement supplied with the event is invalid if the layer
548 | // is performing a transition or scroll, and has to be re-detected manually. Note that
549 | // for this to function correctly, it must be called *after* the event target is checked!
550 | // See issue #57; also filed as rdar://13048589 .
551 | if (deviceIsIOSWithBadTarget) {
552 | touch = event.changedTouches[0];
553 |
554 | // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
555 | targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
556 | targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
557 | }
558 |
559 | targetTagName = targetElement.tagName.toLowerCase();
560 | if (targetTagName === 'label') {
561 | forElement = this.findControl(targetElement);
562 | if (forElement) {
563 | this.focus(targetElement);
564 | if (deviceIsAndroid) {
565 | return false;
566 | }
567 |
568 | targetElement = forElement;
569 | }
570 | } else if (this.needsFocus(targetElement)) {
571 |
572 | // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
573 | // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
574 | if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
575 | this.targetElement = null;
576 | return false;
577 | }
578 |
579 | this.focus(targetElement);
580 | this.sendClick(targetElement, event);
581 |
582 | // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
583 | // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
584 | if (!deviceIsIOS || targetTagName !== 'select') {
585 | this.targetElement = null;
586 | event.preventDefault();
587 | }
588 |
589 | return false;
590 | }
591 |
592 | if (deviceIsIOS && !deviceIsIOS4) {
593 |
594 | // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
595 | // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
596 | scrollParent = targetElement.fastClickScrollParent;
597 | if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
598 | return true;
599 | }
600 | }
601 |
602 | // Prevent the actual click from going though - unless the target node is marked as requiring
603 | // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
604 | if (!this.needsClick(targetElement)) {
605 | event.preventDefault();
606 | this.sendClick(targetElement, event);
607 | }
608 |
609 | return false;
610 | };
611 |
612 |
613 | /**
614 | * On touch cancel, stop tracking the click.
615 | *
616 | * @returns {void}
617 | */
618 | FastClick.prototype.onTouchCancel = function() {
619 | this.trackingClick = false;
620 | this.targetElement = null;
621 | };
622 |
623 |
624 | /**
625 | * Determine mouse events which should be permitted.
626 | *
627 | * @param {Event} event
628 | * @returns {boolean}
629 | */
630 | FastClick.prototype.onMouse = function(event) {
631 |
632 | // If a target element was never set (because a touch event was never fired) allow the event
633 | if (!this.targetElement) {
634 | return true;
635 | }
636 |
637 | if (event.forwardedTouchEvent) {
638 | return true;
639 | }
640 |
641 | // Programmatically generated events targeting a specific element should be permitted
642 | if (!event.cancelable) {
643 | return true;
644 | }
645 |
646 | // Derive and check the target element to see whether the mouse event needs to be permitted;
647 | // unless explicitly enabled, prevent non-touch click events from triggering actions,
648 | // to prevent ghost/doubleclicks.
649 | if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
650 |
651 | // Prevent any user-added listeners declared on FastClick element from being fired.
652 | if (event.stopImmediatePropagation) {
653 | event.stopImmediatePropagation();
654 | } else {
655 |
656 | // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
657 | event.propagationStopped = true;
658 | }
659 |
660 | // Cancel the event
661 | event.stopPropagation();
662 | event.preventDefault();
663 |
664 | return false;
665 | }
666 |
667 | // If the mouse event is permitted, return true for the action to go through.
668 | return true;
669 | };
670 |
671 |
672 | /**
673 | * On actual clicks, determine whether this is a touch-generated click, a click action occurring
674 | * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
675 | * an actual click which should be permitted.
676 | *
677 | * @param {Event} event
678 | * @returns {boolean}
679 | */
680 | FastClick.prototype.onClick = function(event) {
681 | var permitted;
682 |
683 | // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
684 | if (this.trackingClick) {
685 | this.targetElement = null;
686 | this.trackingClick = false;
687 | return true;
688 | }
689 |
690 | // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
691 | if (event.target.type === 'submit' && event.detail === 0) {
692 | return true;
693 | }
694 |
695 | permitted = this.onMouse(event);
696 |
697 | // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
698 | if (!permitted) {
699 | this.targetElement = null;
700 | }
701 |
702 | // If clicks are permitted, return true for the action to go through.
703 | return permitted;
704 | };
705 |
706 |
707 | /**
708 | * Remove all FastClick's event listeners.
709 | *
710 | * @returns {void}
711 | */
712 | FastClick.prototype.destroy = function() {
713 | var layer = this.layer;
714 |
715 | if (deviceIsAndroid) {
716 | layer.removeEventListener('mouseover', this.onMouse, true);
717 | layer.removeEventListener('mousedown', this.onMouse, true);
718 | layer.removeEventListener('mouseup', this.onMouse, true);
719 | }
720 |
721 | layer.removeEventListener('click', this.onClick, true);
722 | layer.removeEventListener('touchstart', this.onTouchStart, false);
723 | layer.removeEventListener('touchmove', this.onTouchMove, false);
724 | layer.removeEventListener('touchend', this.onTouchEnd, false);
725 | layer.removeEventListener('touchcancel', this.onTouchCancel, false);
726 | };
727 |
728 |
729 | /**
730 | * Check whether FastClick is needed.
731 | *
732 | * @param {Element} layer The layer to listen on
733 | */
734 | FastClick.notNeeded = function(layer) {
735 | var metaViewport;
736 | var chromeVersion;
737 | var blackberryVersion;
738 | var firefoxVersion;
739 |
740 | // Devices that don't support touch don't need FastClick
741 | if (typeof window.ontouchstart === 'undefined') {
742 | return true;
743 | }
744 |
745 | // Chrome version - zero for other browsers
746 | chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
747 |
748 | if (chromeVersion) {
749 |
750 | if (deviceIsAndroid) {
751 | metaViewport = document.querySelector('meta[name=viewport]');
752 |
753 | if (metaViewport) {
754 | // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
755 | if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
756 | return true;
757 | }
758 | // Chrome 32 and above with width=device-width or less don't need FastClick
759 | if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
760 | return true;
761 | }
762 | }
763 |
764 | // Chrome desktop doesn't need FastClick (issue #15)
765 | } else {
766 | return true;
767 | }
768 | }
769 |
770 | if (deviceIsBlackBerry10) {
771 | blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
772 |
773 | // BlackBerry 10.3+ does not require Fastclick library.
774 | // https://github.com/ftlabs/fastclick/issues/251
775 | if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
776 | metaViewport = document.querySelector('meta[name=viewport]');
777 |
778 | if (metaViewport) {
779 | // user-scalable=no eliminates click delay.
780 | if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
781 | return true;
782 | }
783 | // width=device-width (or less than device-width) eliminates click delay.
784 | if (document.documentElement.scrollWidth <= window.outerWidth) {
785 | return true;
786 | }
787 | }
788 | }
789 | }
790 |
791 | // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
792 | if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
793 | return true;
794 | }
795 |
796 | // Firefox version - zero for other browsers
797 | firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
798 |
799 | if (firefoxVersion >= 27) {
800 | // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896
801 |
802 | metaViewport = document.querySelector('meta[name=viewport]');
803 | if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
804 | return true;
805 | }
806 | }
807 |
808 | // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
809 | // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
810 | if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
811 | return true;
812 | }
813 |
814 | return false;
815 | };
816 |
817 |
818 | /**
819 | * Factory method for creating a FastClick object
820 | *
821 | * @param {Element} layer The layer to listen on
822 | * @param {Object} [options={}] The options to override the defaults
823 | */
824 | FastClick.attach = function(layer, options) {
825 | return new FastClick(layer, options);
826 | };
827 |
828 |
829 | if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
830 |
831 | // AMD. Register as an anonymous module.
832 | define(function() {
833 | return FastClick;
834 | });
835 | } else if (typeof module !== 'undefined' && module.exports) {
836 | module.exports = FastClick.attach;
837 | module.exports.FastClick = FastClick;
838 | } else {
839 | window.FastClick = FastClick;
840 | }
841 | }());
--------------------------------------------------------------------------------
/src/js/fastclick.js:
--------------------------------------------------------------------------------
1 | ;(function () {
2 | 'use strict';
3 |
4 | /**
5 | * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
6 | *
7 | * @codingstandard ftlabs-jsv2
8 | * @copyright The Financial Times Limited [All Rights Reserved]
9 | * @license MIT License (see LICENSE.txt)
10 | */
11 |
12 | /*jslint browser:true, node:true*/
13 | /*global define, Event, Node*/
14 |
15 |
16 | /**
17 | * Instantiate fast-clicking listeners on the specified layer.
18 | *
19 | * @constructor
20 | * @param {Element} layer The layer to listen on
21 | * @param {Object} [options={}] The options to override the defaults
22 | */
23 | function FastClick(layer, options) {
24 | var oldOnClick;
25 |
26 | options = options || {};
27 |
28 | /**
29 | * Whether a click is currently being tracked.
30 | *
31 | * @type boolean
32 | */
33 | this.trackingClick = false;
34 |
35 |
36 | /**
37 | * Timestamp for when click tracking started.
38 | *
39 | * @type number
40 | */
41 | this.trackingClickStart = 0;
42 |
43 |
44 | /**
45 | * The element being tracked for a click.
46 | *
47 | * @type EventTarget
48 | */
49 | this.targetElement = null;
50 |
51 |
52 | /**
53 | * X-coordinate of touch start event.
54 | *
55 | * @type number
56 | */
57 | this.touchStartX = 0;
58 |
59 |
60 | /**
61 | * Y-coordinate of touch start event.
62 | *
63 | * @type number
64 | */
65 | this.touchStartY = 0;
66 |
67 |
68 | /**
69 | * ID of the last touch, retrieved from Touch.identifier.
70 | *
71 | * @type number
72 | */
73 | this.lastTouchIdentifier = 0;
74 |
75 |
76 | /**
77 | * Touchmove boundary, beyond which a click will be cancelled.
78 | *
79 | * @type number
80 | */
81 | this.touchBoundary = options.touchBoundary || 10;
82 |
83 |
84 | /**
85 | * The FastClick layer.
86 | *
87 | * @type Element
88 | */
89 | this.layer = layer;
90 |
91 | /**
92 | * The minimum time between tap(touchstart and touchend) events
93 | *
94 | * @type number
95 | */
96 | this.tapDelay = options.tapDelay || 200;
97 |
98 | /**
99 | * The maximum time for a tap
100 | *
101 | * @type number
102 | */
103 | this.tapTimeout = options.tapTimeout || 700;
104 |
105 | if (FastClick.notNeeded(layer)) {
106 | return;
107 | }
108 |
109 | // Some old versions of Android don't have Function.prototype.bind
110 | function bind(method, context) {
111 | return function() { return method.apply(context, arguments); };
112 | }
113 |
114 |
115 | var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
116 | var context = this;
117 | for (var i = 0, l = methods.length; i < l; i++) {
118 | context[methods[i]] = bind(context[methods[i]], context);
119 | }
120 |
121 | // Set up event handlers as required
122 | if (deviceIsAndroid) {
123 | layer.addEventListener('mouseover', this.onMouse, true);
124 | layer.addEventListener('mousedown', this.onMouse, true);
125 | layer.addEventListener('mouseup', this.onMouse, true);
126 | }
127 |
128 | layer.addEventListener('click', this.onClick, true);
129 | layer.addEventListener('touchstart', this.onTouchStart, false);
130 | layer.addEventListener('touchmove', this.onTouchMove, false);
131 | layer.addEventListener('touchend', this.onTouchEnd, false);
132 | layer.addEventListener('touchcancel', this.onTouchCancel, false);
133 |
134 | // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
135 | // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
136 | // layer when they are cancelled.
137 | if (!Event.prototype.stopImmediatePropagation) {
138 | layer.removeEventListener = function(type, callback, capture) {
139 | var rmv = Node.prototype.removeEventListener;
140 | if (type === 'click') {
141 | rmv.call(layer, type, callback.hijacked || callback, capture);
142 | } else {
143 | rmv.call(layer, type, callback, capture);
144 | }
145 | };
146 |
147 | layer.addEventListener = function(type, callback, capture) {
148 | var adv = Node.prototype.addEventListener;
149 | if (type === 'click') {
150 | adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
151 | if (!event.propagationStopped) {
152 | callback(event);
153 | }
154 | }), capture);
155 | } else {
156 | adv.call(layer, type, callback, capture);
157 | }
158 | };
159 | }
160 |
161 | // If a handler is already declared in the element's onclick attribute, it will be fired before
162 | // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
163 | // adding it as listener.
164 | if (typeof layer.onclick === 'function') {
165 |
166 | // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
167 | // - the old one won't work if passed to addEventListener directly.
168 | oldOnClick = layer.onclick;
169 | layer.addEventListener('click', function(event) {
170 | oldOnClick(event);
171 | }, false);
172 | layer.onclick = null;
173 | }
174 | }
175 |
176 | /**
177 | * Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
178 | *
179 | * @type boolean
180 | */
181 | var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;
182 |
183 | /**
184 | * Android requires exceptions.
185 | *
186 | * @type boolean
187 | */
188 | var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;
189 |
190 |
191 | /**
192 | * iOS requires exceptions.
193 | *
194 | * @type boolean
195 | */
196 | var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;
197 |
198 |
199 | /**
200 | * iOS 4 requires an exception for select elements.
201 | *
202 | * @type boolean
203 | */
204 | var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
205 |
206 |
207 | /**
208 | * iOS 6.0-7.* requires the target element to be manually derived
209 | *
210 | * @type boolean
211 | */
212 | var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);
213 |
214 | /**
215 | * BlackBerry requires exceptions.
216 | *
217 | * @type boolean
218 | */
219 | var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;
220 |
221 | /**
222 | * Determine whether a given element requires a native click.
223 | *
224 | * @param {EventTarget|Element} target Target DOM element
225 | * @returns {boolean} Returns true if the element needs a native click
226 | */
227 | FastClick.prototype.needsClick = function(target) {
228 | switch (target.nodeName.toLowerCase()) {
229 |
230 | // Don't send a synthetic click to disabled inputs (issue #62)
231 | case 'button':
232 | case 'select':
233 | case 'textarea':
234 | if (target.disabled) {
235 | return true;
236 | }
237 |
238 | break;
239 | case 'input':
240 |
241 | // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
242 | if ((deviceIsIOS && target.type === 'file') || target.disabled) {
243 | return true;
244 | }
245 |
246 | break;
247 | case 'label':
248 | case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
249 | case 'video':
250 | return true;
251 | }
252 |
253 | return (/\bneedsclick\b/).test(target.className);
254 | };
255 |
256 |
257 | /**
258 | * Determine whether a given element requires a call to focus to simulate click into element.
259 | *
260 | * @param {EventTarget|Element} target Target DOM element
261 | * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
262 | */
263 | FastClick.prototype.needsFocus = function(target) {
264 | switch (target.nodeName.toLowerCase()) {
265 | case 'textarea':
266 | return true;
267 | case 'select':
268 | return !deviceIsAndroid;
269 | case 'input':
270 | switch (target.type) {
271 | case 'button':
272 | case 'checkbox':
273 | case 'file':
274 | case 'image':
275 | case 'radio':
276 | case 'submit':
277 | return false;
278 | }
279 |
280 | // No point in attempting to focus disabled inputs
281 | return !target.disabled && !target.readOnly;
282 | default:
283 | return (/\bneedsfocus\b/).test(target.className);
284 | }
285 | };
286 |
287 |
288 | /**
289 | * Send a click event to the specified element.
290 | *
291 | * @param {EventTarget|Element} targetElement
292 | * @param {Event} event
293 | */
294 | FastClick.prototype.sendClick = function(targetElement, event) {
295 | var clickEvent, touch;
296 |
297 | // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
298 | if (document.activeElement && document.activeElement !== targetElement) {
299 | document.activeElement.blur();
300 | }
301 |
302 | touch = event.changedTouches[0];
303 |
304 | // Synthesise a click event, with an extra attribute so it can be tracked
305 | clickEvent = document.createEvent('MouseEvents');
306 | clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
307 | clickEvent.forwardedTouchEvent = true;
308 | targetElement.dispatchEvent(clickEvent);
309 | };
310 |
311 | FastClick.prototype.determineEventType = function(targetElement) {
312 |
313 | //Issue #159: Android Chrome Select Box does not open with a synthetic click event
314 | if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
315 | return 'mousedown';
316 | }
317 |
318 | return 'click';
319 | };
320 |
321 |
322 | /**
323 | * @param {EventTarget|Element} targetElement
324 | */
325 | FastClick.prototype.focus = function(targetElement) {
326 | var length;
327 |
328 | // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
329 | if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
330 | length = targetElement.value.length;
331 | targetElement.setSelectionRange(length, length);
332 | } else {
333 | targetElement.focus();
334 | }
335 | };
336 |
337 |
338 | /**
339 | * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
340 | *
341 | * @param {EventTarget|Element} targetElement
342 | */
343 | FastClick.prototype.updateScrollParent = function(targetElement) {
344 | var scrollParent, parentElement;
345 |
346 | scrollParent = targetElement.fastClickScrollParent;
347 |
348 | // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
349 | // target element was moved to another parent.
350 | if (!scrollParent || !scrollParent.contains(targetElement)) {
351 | parentElement = targetElement;
352 | do {
353 | if (parentElement.scrollHeight > parentElement.offsetHeight) {
354 | scrollParent = parentElement;
355 | targetElement.fastClickScrollParent = parentElement;
356 | break;
357 | }
358 |
359 | parentElement = parentElement.parentElement;
360 | } while (parentElement);
361 | }
362 |
363 | // Always update the scroll top tracker if possible.
364 | if (scrollParent) {
365 | scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
366 | }
367 | };
368 |
369 |
370 | /**
371 | * @param {EventTarget} targetElement
372 | * @returns {Element|EventTarget}
373 | */
374 | FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
375 |
376 | // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
377 | if (eventTarget.nodeType === Node.TEXT_NODE) {
378 | return eventTarget.parentNode;
379 | }
380 |
381 | return eventTarget;
382 | };
383 |
384 |
385 | /**
386 | * On touch start, record the position and scroll offset.
387 | *
388 | * @param {Event} event
389 | * @returns {boolean}
390 | */
391 | FastClick.prototype.onTouchStart = function(event) {
392 | var targetElement, touch, selection;
393 |
394 | // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
395 | if (event.targetTouches.length > 1) {
396 | return true;
397 | }
398 |
399 | targetElement = this.getTargetElementFromEventTarget(event.target);
400 | touch = event.targetTouches[0];
401 |
402 | if (deviceIsIOS) {
403 |
404 | // Only trusted events will deselect text on iOS (issue #49)
405 | selection = window.getSelection();
406 | if (selection.rangeCount && !selection.isCollapsed) {
407 | return true;
408 | }
409 |
410 | if (!deviceIsIOS4) {
411 |
412 | // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
413 | // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
414 | // with the same identifier as the touch event that previously triggered the click that triggered the alert.
415 | // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
416 | // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
417 | // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
418 | // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
419 | // random integers, it's safe to to continue if the identifier is 0 here.
420 | if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
421 | event.preventDefault();
422 | return false;
423 | }
424 |
425 | this.lastTouchIdentifier = touch.identifier;
426 |
427 | // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
428 | // 1) the user does a fling scroll on the scrollable layer
429 | // 2) the user stops the fling scroll with another tap
430 | // then the event.target of the last 'touchend' event will be the element that was under the user's finger
431 | // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
432 | // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
433 | this.updateScrollParent(targetElement);
434 | }
435 | }
436 |
437 | this.trackingClick = true;
438 | this.trackingClickStart = event.timeStamp;
439 | this.targetElement = targetElement;
440 |
441 | this.touchStartX = touch.pageX;
442 | this.touchStartY = touch.pageY;
443 |
444 | // Prevent phantom clicks on fast double-tap (issue #36)
445 | if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
446 | event.preventDefault();
447 | }
448 |
449 | return true;
450 | };
451 |
452 |
453 | /**
454 | * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
455 | *
456 | * @param {Event} event
457 | * @returns {boolean}
458 | */
459 | FastClick.prototype.touchHasMoved = function(event) {
460 | var touch = event.changedTouches[0], boundary = this.touchBoundary;
461 |
462 | if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
463 | return true;
464 | }
465 |
466 | return false;
467 | };
468 |
469 |
470 | /**
471 | * Update the last position.
472 | *
473 | * @param {Event} event
474 | * @returns {boolean}
475 | */
476 | FastClick.prototype.onTouchMove = function(event) {
477 | if (!this.trackingClick) {
478 | return true;
479 | }
480 |
481 | // If the touch has moved, cancel the click tracking
482 | if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
483 | this.trackingClick = false;
484 | this.targetElement = null;
485 | }
486 |
487 | return true;
488 | };
489 |
490 |
491 | /**
492 | * Attempt to find the labelled control for the given label element.
493 | *
494 | * @param {EventTarget|HTMLLabelElement} labelElement
495 | * @returns {Element|null}
496 | */
497 | FastClick.prototype.findControl = function(labelElement) {
498 |
499 | // Fast path for newer browsers supporting the HTML5 control attribute
500 | if (labelElement.control !== undefined) {
501 | return labelElement.control;
502 | }
503 |
504 | // All browsers under test that support touch events also support the HTML5 htmlFor attribute
505 | if (labelElement.htmlFor) {
506 | return document.getElementById(labelElement.htmlFor);
507 | }
508 |
509 | // If no for attribute exists, attempt to retrieve the first labellable descendant element
510 | // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
511 | return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
512 | };
513 |
514 |
515 | /**
516 | * On touch end, determine whether to send a click event at once.
517 | *
518 | * @param {Event} event
519 | * @returns {boolean}
520 | */
521 | FastClick.prototype.onTouchEnd = function(event) {
522 | var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
523 |
524 | if (!this.trackingClick) {
525 | return true;
526 | }
527 |
528 | // Prevent phantom clicks on fast double-tap (issue #36)
529 | if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
530 | this.cancelNextClick = true;
531 | return true;
532 | }
533 |
534 | if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
535 | return true;
536 | }
537 |
538 | // Reset to prevent wrong click cancel on input (issue #156).
539 | this.cancelNextClick = false;
540 |
541 | this.lastClickTime = event.timeStamp;
542 |
543 | trackingClickStart = this.trackingClickStart;
544 | this.trackingClick = false;
545 | this.trackingClickStart = 0;
546 |
547 | // On some iOS devices, the targetElement supplied with the event is invalid if the layer
548 | // is performing a transition or scroll, and has to be re-detected manually. Note that
549 | // for this to function correctly, it must be called *after* the event target is checked!
550 | // See issue #57; also filed as rdar://13048589 .
551 | if (deviceIsIOSWithBadTarget) {
552 | touch = event.changedTouches[0];
553 |
554 | // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
555 | targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
556 | targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
557 | }
558 |
559 | targetTagName = targetElement.tagName.toLowerCase();
560 | if (targetTagName === 'label') {
561 | forElement = this.findControl(targetElement);
562 | if (forElement) {
563 | this.focus(targetElement);
564 | if (deviceIsAndroid) {
565 | return false;
566 | }
567 |
568 | targetElement = forElement;
569 | }
570 | } else if (this.needsFocus(targetElement)) {
571 |
572 | // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
573 | // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
574 | if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
575 | this.targetElement = null;
576 | return false;
577 | }
578 |
579 | this.focus(targetElement);
580 | this.sendClick(targetElement, event);
581 |
582 | // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
583 | // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
584 | if (!deviceIsIOS || targetTagName !== 'select') {
585 | this.targetElement = null;
586 | event.preventDefault();
587 | }
588 |
589 | return false;
590 | }
591 |
592 | if (deviceIsIOS && !deviceIsIOS4) {
593 |
594 | // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
595 | // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
596 | scrollParent = targetElement.fastClickScrollParent;
597 | if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
598 | return true;
599 | }
600 | }
601 |
602 | // Prevent the actual click from going though - unless the target node is marked as requiring
603 | // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
604 | if (!this.needsClick(targetElement)) {
605 | event.preventDefault();
606 | this.sendClick(targetElement, event);
607 | }
608 |
609 | return false;
610 | };
611 |
612 |
613 | /**
614 | * On touch cancel, stop tracking the click.
615 | *
616 | * @returns {void}
617 | */
618 | FastClick.prototype.onTouchCancel = function() {
619 | this.trackingClick = false;
620 | this.targetElement = null;
621 | };
622 |
623 |
624 | /**
625 | * Determine mouse events which should be permitted.
626 | *
627 | * @param {Event} event
628 | * @returns {boolean}
629 | */
630 | FastClick.prototype.onMouse = function(event) {
631 |
632 | // If a target element was never set (because a touch event was never fired) allow the event
633 | if (!this.targetElement) {
634 | return true;
635 | }
636 |
637 | if (event.forwardedTouchEvent) {
638 | return true;
639 | }
640 |
641 | // Programmatically generated events targeting a specific element should be permitted
642 | if (!event.cancelable) {
643 | return true;
644 | }
645 |
646 | // Derive and check the target element to see whether the mouse event needs to be permitted;
647 | // unless explicitly enabled, prevent non-touch click events from triggering actions,
648 | // to prevent ghost/doubleclicks.
649 | if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
650 |
651 | // Prevent any user-added listeners declared on FastClick element from being fired.
652 | if (event.stopImmediatePropagation) {
653 | event.stopImmediatePropagation();
654 | } else {
655 |
656 | // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
657 | event.propagationStopped = true;
658 | }
659 |
660 | // Cancel the event
661 | event.stopPropagation();
662 | event.preventDefault();
663 |
664 | return false;
665 | }
666 |
667 | // If the mouse event is permitted, return true for the action to go through.
668 | return true;
669 | };
670 |
671 |
672 | /**
673 | * On actual clicks, determine whether this is a touch-generated click, a click action occurring
674 | * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
675 | * an actual click which should be permitted.
676 | *
677 | * @param {Event} event
678 | * @returns {boolean}
679 | */
680 | FastClick.prototype.onClick = function(event) {
681 | var permitted;
682 |
683 | // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
684 | if (this.trackingClick) {
685 | this.targetElement = null;
686 | this.trackingClick = false;
687 | return true;
688 | }
689 |
690 | // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
691 | if (event.target.type === 'submit' && event.detail === 0) {
692 | return true;
693 | }
694 |
695 | permitted = this.onMouse(event);
696 |
697 | // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
698 | if (!permitted) {
699 | this.targetElement = null;
700 | }
701 |
702 | // If clicks are permitted, return true for the action to go through.
703 | return permitted;
704 | };
705 |
706 |
707 | /**
708 | * Remove all FastClick's event listeners.
709 | *
710 | * @returns {void}
711 | */
712 | FastClick.prototype.destroy = function() {
713 | var layer = this.layer;
714 |
715 | if (deviceIsAndroid) {
716 | layer.removeEventListener('mouseover', this.onMouse, true);
717 | layer.removeEventListener('mousedown', this.onMouse, true);
718 | layer.removeEventListener('mouseup', this.onMouse, true);
719 | }
720 |
721 | layer.removeEventListener('click', this.onClick, true);
722 | layer.removeEventListener('touchstart', this.onTouchStart, false);
723 | layer.removeEventListener('touchmove', this.onTouchMove, false);
724 | layer.removeEventListener('touchend', this.onTouchEnd, false);
725 | layer.removeEventListener('touchcancel', this.onTouchCancel, false);
726 | };
727 |
728 |
729 | /**
730 | * Check whether FastClick is needed.
731 | *
732 | * @param {Element} layer The layer to listen on
733 | */
734 | FastClick.notNeeded = function(layer) {
735 | var metaViewport;
736 | var chromeVersion;
737 | var blackberryVersion;
738 | var firefoxVersion;
739 |
740 | // Devices that don't support touch don't need FastClick
741 | if (typeof window.ontouchstart === 'undefined') {
742 | return true;
743 | }
744 |
745 | // Chrome version - zero for other browsers
746 | chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
747 |
748 | if (chromeVersion) {
749 |
750 | if (deviceIsAndroid) {
751 | metaViewport = document.querySelector('meta[name=viewport]');
752 |
753 | if (metaViewport) {
754 | // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
755 | if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
756 | return true;
757 | }
758 | // Chrome 32 and above with width=device-width or less don't need FastClick
759 | if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
760 | return true;
761 | }
762 | }
763 |
764 | // Chrome desktop doesn't need FastClick (issue #15)
765 | } else {
766 | return true;
767 | }
768 | }
769 |
770 | if (deviceIsBlackBerry10) {
771 | blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
772 |
773 | // BlackBerry 10.3+ does not require Fastclick library.
774 | // https://github.com/ftlabs/fastclick/issues/251
775 | if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
776 | metaViewport = document.querySelector('meta[name=viewport]');
777 |
778 | if (metaViewport) {
779 | // user-scalable=no eliminates click delay.
780 | if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
781 | return true;
782 | }
783 | // width=device-width (or less than device-width) eliminates click delay.
784 | if (document.documentElement.scrollWidth <= window.outerWidth) {
785 | return true;
786 | }
787 | }
788 | }
789 | }
790 |
791 | // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
792 | if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
793 | return true;
794 | }
795 |
796 | // Firefox version - zero for other browsers
797 | firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
798 |
799 | if (firefoxVersion >= 27) {
800 | // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896
801 |
802 | metaViewport = document.querySelector('meta[name=viewport]');
803 | if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
804 | return true;
805 | }
806 | }
807 |
808 | // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
809 | // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
810 | if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
811 | return true;
812 | }
813 |
814 | return false;
815 | };
816 |
817 |
818 | /**
819 | * Factory method for creating a FastClick object
820 | *
821 | * @param {Element} layer The layer to listen on
822 | * @param {Object} [options={}] The options to override the defaults
823 | */
824 | FastClick.attach = function(layer, options) {
825 | return new FastClick(layer, options);
826 | };
827 |
828 |
829 | if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
830 |
831 | // AMD. Register as an anonymous module.
832 | define(function() {
833 | return FastClick;
834 | });
835 | } else if (typeof module !== 'undefined' && module.exports) {
836 | module.exports = FastClick.attach;
837 | module.exports.FastClick = FastClick;
838 | } else {
839 | window.FastClick = FastClick;
840 | }
841 | }());
--------------------------------------------------------------------------------