前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# Deployed apps should consider commenting this line out:
# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git
node_modules
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Hammer.js
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -0,0 +1,3 @@
server:
python -m SimpleHTTPServer
+71
View File
@@ -0,0 +1,71 @@
Touch Emulator
========
Emulate multi-touch input on your desktop. Triggers touch events as
[specified by W3C](http://www.w3.org/TR/touch-events). Press the `shift` key to pinch and rotate!
- [Example with Hammer.js](http://rawgit.com/hammerjs/touchemulator/master/tests/manual/hammer.html)
- [Example with Leaflet Maps](http://rawgit.com/hammerjs/touchemulator/master/tests/manual/leaflet.html)
- [View webpage](http://hammerjs.github.io/touch-emulator)
## Install
Download the script from this repo, via Bower:
```bash
bower install hammer-touchemulator
```
or NPM:
```bash
npm install hammer-touchemulator
```
## How to use
Include the javascript file, and call the `Emulator()` function before any other libraries that do something with the
touch input. It will set some fake properties to spoof the touch detection of some libraries, and triggers `touchstart`, `touchmove` and `touchend` events on the mouse target.
````html
<script src="touch-emulator.js"></script>
<script> TouchEmulator(); </script>
````
````js
function log(ev) {
console.log(ev);
}
document.body.addEventListener('touchstart', log, false);
document.body.addEventListener('touchmove', log, false);
document.body.addEventListener('touchend', log, false);
````
Also, the script includes polyfills for `document.createTouch` and `document.createTouchList`.
## How it works
It listens to the `mousedown`, `mousemove` and `mouseup` events, and translates them to touch events. If the mouseevent
has the `shiftKey` property to `true`, it enables multi-touch.
The script also prevents the following mouse events on the page:
`mousedown`, `mouseenter`, `mouseleave`, `mousemove`, `mouseout`, `mouseover` and `mouseup`.
## Web platform tests
The script has been tested with the [w3c web platform tests](/tests/web-platform-tests/touch-events) and passes all tests, except these;
- *assert_true: event is a TouchEvent event expected true got false*
- We trigger an event of the type `Event`
- *assert_equals: touch list is of type TouchList expected "[object TouchList]" but got "[object Array]"*
- *assert_equals: touch is of type Touch expected "[object Touch]" but got "[object Object]"*
## Bookmarklet
````js
javascript:!function(a){var b=a.createElement("script");b.onload=function(){TouchEmulator()},b.src="//cdn.rawgit.com/hammerjs/touchemulator/0.0.2/touch-emulator.js",a.body.appendChild(b)}(document);
````
## Options
#### TouchEmulator.template = Function(touch)
Change the css properties of the rendered touches.
#### TouchEmulator.multiTouchOffset = 75
The distance between the two touch points when entering the *multi-touch zone*.
+25
View File
@@ -0,0 +1,25 @@
{
"name": "TouchEmulator",
"version": "0.0.2",
"homepage": "https://github.com/hammerjs/Emulator",
"authors": [
"Jorik Tangelder <j.tangelder@gmail.com>"
],
"description": "Emulate touch input",
"main": "touch-emulator.js",
"keywords": [
"touch",
"hammerjs",
"input",
"emulator",
"simulator"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
+29
View File
@@ -0,0 +1,29 @@
{
"name": "hammer-touchemulator",
"version": "0.0.2",
"description": "Emulate touch input on your desktop.",
"main": "touch-emulator.js",
"directories": {
"test": "tests"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/hammerjs/touchemulator"
},
"keywords": [
"touch",
"hammerjs",
"input",
"emulator",
"simulator"
],
"author": "Jorik Tangelder <j.tangelder@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/hammerjs/touchemulator/issues"
},
"homepage": "https://github.com/hammerjs/touchemulator"
}
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
</head>
<body>
<div id="hitarea" style="background: silver; height: 400px;">
Check the console. No mouseevents should be fired, only touchevents. Click events are allowed.
</div>
<script>
function log(ev) {
console.log(ev.type, ev);
}
var hitarea = document.getElementById('hitarea');
var events = ['touchstart','touchmove','touchend','touchcancel',
'mousedown','mouseenter','mouseleave','mousemove',
'mouseout','mouseover','mouseup','mousewheel',
'click'];
for(var i=0; i<events.length; i++) {
hitarea.addEventListener(events[i], log, false);
}
</script>
</body>
</html>
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
</head>
<body>
<p>To test it on the Google Maps view, you should open your
<a href="https://developer.chrome.com/devtools/docs/mobile-emulation#emulate-touch-events">
Inspector and emulate a touch-device (by spoofing the user agent).</a>.</p>
<p>This is because the userAgent can't be overwritten and Google uses this to identify if there's any touch
support.</p>
<div id="maps" style="height: 500px; margin-bottom: 20px; -webkit-user-select: none;"></div>
<script src="../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map = new google.maps.Map(document.getElementById('maps'), {
zoom: 14,
center: new google.maps.LatLng(51.98, 5.91)
});
</script>
</body>
</html>
+208
View File
@@ -0,0 +1,208 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://cdn.rawgit.com/hammerjs/hammer.js/master/tests/manual/assets/style.css">
<title>Hammer.js</title>
<style>
html, body {
overflow: hidden;
margin: 0;
}
.animate {
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
#hit {
padding: 10px;
}
#log {
position: absolute;
padding: 10px;
}
</style>
<script src="../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
</head>
<body>
<div id="log"></div>
<div id="hit" style="background: #42d692; width: 150px; height: 150px;"></div>
<script src="http://hammerjs.github.io/dist/hammer.js"></script>
<script>
var reqAnimationFrame = (function () {
return window[Hammer.prefixed(window, 'requestAnimationFrame')] || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var log = document.querySelector("#log");
var el = document.querySelector("#hit");
var START_X = Math.round((window.innerWidth - el.offsetWidth) / 2);
var START_Y = Math.round((window.innerHeight - el.offsetHeight) / 2);
var ticking = false;
var transform;
var timer;
var mc = new Hammer.Manager(el);
mc.add(new Hammer.Pan({ threshold: 0, pointers: 0 }));
mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));
mc.add(new Hammer.Rotate({ threshold: 0 })).recognizeWith(mc.get('pan'));
mc.add(new Hammer.Pinch({ threshold: 0 })).recognizeWith([mc.get('pan'), mc.get('rotate')]);
mc.add(new Hammer.Tap({ event: 'doubletap', taps: 2 }));
mc.add(new Hammer.Tap());
mc.on("panstart panmove", onPan);
mc.on("rotatestart rotatemove", onRotate);
mc.on("pinchstart pinchmove", onPinch);
mc.on("swipe", onSwipe);
mc.on("tap", onTap);
mc.on("doubletap", onDoubleTap);
mc.on("hammer.input", function(ev) {
if(ev.isFinal) {
resetElement();
}
});
function resetElement() {
el.className = 'animate';
transform = {
translate: { x: START_X, y: START_Y },
scale: 1,
angle: 0,
rx: 0,
ry: 0,
rz: 0
};
requestElementUpdate();
if (log.textContent.length > 2000) {
log.textContent = log.textContent.substring(0, 2000) + "...";
}
}
function updateElementTransform() {
var value = [
'translate3d(' + transform.translate.x + 'px, ' + transform.translate.y + 'px, 0)',
'scale(' + transform.scale + ', ' + transform.scale + ')',
'rotate3d('+ transform.rx +','+ transform.ry +','+ transform.rz +','+ transform.angle + 'deg)'
];
value = value.join(" ");
el.textContent = value;
el.style.webkitTransform = value;
el.style.mozTransform = value;
el.style.transform = value;
ticking = false;
}
function requestElementUpdate() {
if(!ticking) {
reqAnimationFrame(updateElementTransform);
ticking = true;
}
}
function logEvent(str) {
//log.insertBefore(document.createTextNode(str +"\n"), log.firstChild);
}
function onPan(ev) {
el.className = '';
transform.translate = {
x: START_X + ev.deltaX,
y: START_Y + ev.deltaY
};
requestElementUpdate();
logEvent(ev.type);
}
var initScale = 1;
function onPinch(ev) {
if(ev.type == 'pinchstart') {
initScale = transform.scale || 1;
}
el.className = '';
transform.scale = initScale * ev.scale;
requestElementUpdate();
logEvent(ev.type);
}
var initAngle = 0;
function onRotate(ev) {
if(ev.type == 'rotatestart') {
initAngle = transform.angle || 0;
}
el.className = '';
transform.rz = 1;
transform.angle = initAngle + ev.rotation;
requestElementUpdate();
logEvent(ev.type);
}
function onSwipe(ev) {
var angle = 50;
transform.ry = (ev.direction & Hammer.DIRECTION_HORIZONTAL) ? 1 : 0;
transform.rx = (ev.direction & Hammer.DIRECTION_VERTICAL) ? 1 : 0;
transform.angle = (ev.direction & (Hammer.DIRECTION_RIGHT | Hammer.DIRECTION_UP)) ? angle : -angle;
clearTimeout(timer);
timer = setTimeout(function () {
resetElement();
}, 300);
requestElementUpdate();
logEvent(ev.type);
}
function onTap(ev) {
transform.rx = 1;
transform.angle = 25;
clearTimeout(timer);
timer = setTimeout(function () {
resetElement();
}, 200);
requestElementUpdate();
logEvent(ev.type);
}
function onDoubleTap(ev) {
transform.rx = 1;
transform.angle = 80;
clearTimeout(timer);
timer = setTimeout(function () {
resetElement();
}, 500);
requestElementUpdate();
logEvent(ev.type);
}
resetElement();
</script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
</head>
<body>
no dragging of images;<br>
<img src="http://people.ucsc.edu/~ddiep1/puppy.jpg">
</body>
</html>
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id="map" style="height: 500px;"></div>
<script>
// create a map in the "map" div, set the view to a given place and zoom
var map = L.map('map', { boxZoom: false}).setView([51.98, 5.91], 13);
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
</script>
</body>
</html>
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
</head>
<body>
<h1>Can we trick Modernizr?</h1>
<script src="../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.min.js"></script>
<script>
alert('Modernizr.touch == '+ Modernizr.touch);
</script>
</body>
</html>
@@ -0,0 +1,107 @@
html {
font-family:DejaVu Sans, Bitstream Vera Sans, Arial, Sans;
}
#log .warning,
#log .warning a {
color: black;
background: yellow;
}
#log .error,
#log .error a {
color: white;
background: red;
}
#log pre {
border: 1px solid black;
padding: 1em;
}
section#summary {
margin-bottom:1em;
}
table#results {
border-collapse:collapse;
table-layout:fixed;
width:100%;
}
table#results th:first-child,
table#results td:first-child {
width:4em;
}
table#results th:last-child,
table#results td:last-child {
width:50%;
}
table#results.assertions th:last-child,
table#results.assertions td:last-child {
width:35%;
}
table#results th {
padding:0;
padding-bottom:0.5em;
border-bottom:medium solid black;
}
table#results td {
padding:1em;
padding-bottom:0.5em;
border-bottom:thin solid black;
}
tr.pass > td:first-child {
color:green;
}
tr.fail > td:first-child {
color:red;
}
tr.timeout > td:first-child {
color:red;
}
tr.notrun > td:first-child {
color:blue;
}
.pass > td:first-child, .fail > td:first-child, .timeout > td:first-child, .notrun > td:first-child {
font-variant:small-caps;
}
table#results span {
display:block;
}
table#results span.expected {
font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;
white-space:pre;
}
table#results span.actual {
font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;
white-space:pre;
}
span.ok {
color:green;
}
tr.error {
color:red;
}
span.timeout {
color:red;
}
span.ok, span.timeout, span.error {
font-variant:small-caps;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,397 @@
/*global add_completion_callback, setup */
/*
* This file is intended for vendors to implement
* code needed to integrate testharness.js tests with their own test systems.
*
* The default implementation extracts metadata from the tests and validates
* it against the cached version that should be present in the test source
* file. If the cache is not found or is out of sync, source code suitable for
* caching the metadata is optionally generated.
*
* The cached metadata is present for extraction by test processing tools that
* are unable to execute javascript.
*
* Metadata is attached to tests via the properties parameter in the test
* constructor. See testharness.js for details.
*
* Typically test system integration will attach callbacks when each test has
* run, using add_result_callback(callback(test)), or when the whole test file
* has completed, using
* add_completion_callback(callback(tests, harness_status)).
*
* For more documentation about the callback functions and the
* parameters they are called with see testharness.js
*/
var metadata_generator = {
currentMetadata: {},
cachedMetadata: false,
metadataProperties: ['help', 'assert', 'author'],
error: function(message) {
var messageElement = document.createElement('p');
messageElement.setAttribute('class', 'error');
this.appendText(messageElement, message);
var summary = document.getElementById('summary');
if (summary) {
summary.parentNode.insertBefore(messageElement, summary);
}
else {
document.body.appendChild(messageElement);
}
},
/**
* Ensure property value has contact information
*/
validateContact: function(test, propertyName) {
var result = true;
var value = test.properties[propertyName];
var values = Array.isArray(value) ? value : [value];
for (var index = 0; index < values.length; index++) {
value = values[index];
var re = /(\S+)(\s*)<(.*)>(.*)/;
if (! re.test(value)) {
re = /(\S+)(\s+)(http[s]?:\/\/)(.*)/;
if (! re.test(value)) {
this.error('Metadata property "' + propertyName +
'" for test: "' + test.name +
'" must have name and contact information ' +
'("name <email>" or "name http(s)://")');
result = false;
}
}
}
return result;
},
/**
* Extract metadata from test object
*/
extractFromTest: function(test) {
var testMetadata = {};
// filter out metadata from other properties in test
for (var metaIndex = 0; metaIndex < this.metadataProperties.length;
metaIndex++) {
var meta = this.metadataProperties[metaIndex];
if (test.properties.hasOwnProperty(meta)) {
if ('author' == meta) {
this.validateContact(test, meta);
}
testMetadata[meta] = test.properties[meta];
}
}
return testMetadata;
},
/**
* Compare cached metadata to extracted metadata
*/
validateCache: function() {
for (var testName in this.currentMetadata) {
if (! this.cachedMetadata.hasOwnProperty(testName)) {
return false;
}
var testMetadata = this.currentMetadata[testName];
var cachedTestMetadata = this.cachedMetadata[testName];
delete this.cachedMetadata[testName];
for (var metaIndex = 0; metaIndex < this.metadataProperties.length;
metaIndex++) {
var meta = this.metadataProperties[metaIndex];
if (cachedTestMetadata.hasOwnProperty(meta) &&
testMetadata.hasOwnProperty(meta)) {
if (Array.isArray(cachedTestMetadata[meta])) {
if (! Array.isArray(testMetadata[meta])) {
return false;
}
if (cachedTestMetadata[meta].length ==
testMetadata[meta].length) {
for (var index = 0;
index < cachedTestMetadata[meta].length;
index++) {
if (cachedTestMetadata[meta][index] !=
testMetadata[meta][index]) {
return false;
}
}
}
else {
return false;
}
}
else {
if (Array.isArray(testMetadata[meta])) {
return false;
}
if (cachedTestMetadata[meta] != testMetadata[meta]) {
return false;
}
}
}
else if (cachedTestMetadata.hasOwnProperty(meta) ||
testMetadata.hasOwnProperty(meta)) {
return false;
}
}
}
for (var testName in this.cachedMetadata) {
return false;
}
return true;
},
appendText: function(elemement, text) {
elemement.appendChild(document.createTextNode(text));
},
jsonifyArray: function(arrayValue, indent) {
var output = '[';
if (1 == arrayValue.length) {
output += JSON.stringify(arrayValue[0]);
}
else {
for (var index = 0; index < arrayValue.length; index++) {
if (0 < index) {
output += ',\n ' + indent;
}
output += JSON.stringify(arrayValue[index]);
}
}
output += ']';
return output;
},
jsonifyObject: function(objectValue, indent) {
var output = '{';
var value;
var count = 0;
for (var property in objectValue) {
++count;
if (Array.isArray(objectValue[property]) ||
('object' == typeof(value))) {
++count;
}
}
if (1 == count) {
for (var property in objectValue) {
output += ' "' + property + '": ' +
JSON.stringify(objectValue[property]) +
' ';
}
}
else {
var first = true;
for (var property in objectValue) {
if (! first) {
output += ',';
}
first = false;
output += '\n ' + indent + '"' + property + '": ';
value = objectValue[property];
if (Array.isArray(value)) {
output += this.jsonifyArray(value, indent +
' '.substr(0, 5 + property.length));
}
else if ('object' == typeof(value)) {
output += this.jsonifyObject(value, indent + ' ');
}
else {
output += JSON.stringify(value);
}
}
if (1 < output.length) {
output += '\n' + indent;
}
}
output += '}';
return output;
},
/**
* Generate javascript source code for captured metadata
* Metadata is in pretty-printed JSON format
*/
generateSource: function() {
var source =
'<script id="metadata_cache">/*\n' +
this.jsonifyObject(this.currentMetadata, '') + '\n' +
'*/</script>\n';
return source;
},
/**
* Add element containing metadata source code
*/
addSourceElement: function(event) {
var sourceWrapper = document.createElement('div');
sourceWrapper.setAttribute('id', 'metadata_source');
var instructions = document.createElement('p');
if (this.cachedMetadata) {
this.appendText(instructions,
'Replace the existing <script id="metadata_cache"> element ' +
'in the test\'s <head> with the following:');
}
else {
this.appendText(instructions,
'Copy the following into the <head> element of the test ' +
'or the test\'s metadata sidecar file:');
}
sourceWrapper.appendChild(instructions);
var sourceElement = document.createElement('pre');
this.appendText(sourceElement, this.generateSource());
sourceWrapper.appendChild(sourceElement);
var messageElement = document.getElementById('metadata_issue');
messageElement.parentNode.insertBefore(sourceWrapper,
messageElement.nextSibling);
messageElement.parentNode.removeChild(messageElement);
(event.preventDefault) ? event.preventDefault() :
event.returnValue = false;
},
/**
* Extract the metadata cache from the cache element if present
*/
getCachedMetadata: function() {
var cacheElement = document.getElementById('metadata_cache');
if (cacheElement) {
var cacheText = cacheElement.firstChild.nodeValue;
var openBrace = cacheText.indexOf('{');
var closeBrace = cacheText.lastIndexOf('}');
if ((-1 < openBrace) && (-1 < closeBrace)) {
cacheText = cacheText.slice(openBrace, closeBrace + 1);
try {
this.cachedMetadata = JSON.parse(cacheText);
}
catch (exc) {
this.cachedMetadata = 'Invalid JSON in Cached metadata. ';
}
}
else {
this.cachedMetadata = 'Metadata not found in cache element. ';
}
}
},
/**
* Main entry point, extract metadata from tests, compare to cached version
* if present.
* If cache not present or differs from extrated metadata, generate an error
*/
process: function(tests) {
for (var index = 0; index < tests.length; index++) {
var test = tests[index];
if (this.currentMetadata.hasOwnProperty(test.name)) {
this.error('Duplicate test name: ' + test.name);
}
else {
this.currentMetadata[test.name] = this.extractFromTest(test);
}
}
this.getCachedMetadata();
var message = null;
var messageClass = 'warning';
var showSource = false;
if (0 === tests.length) {
if (this.cachedMetadata) {
message = 'Cached metadata present but no tests. ';
}
}
else if (1 === tests.length) {
if (this.cachedMetadata) {
message = 'Single test files should not have cached metadata. ';
}
else {
var testMetadata = this.currentMetadata[tests[0].name];
for (var meta in testMetadata) {
if (testMetadata.hasOwnProperty(meta)) {
message = 'Single tests should not have metadata. ' +
'Move metadata to <head>. ';
break;
}
}
}
}
else {
if (this.cachedMetadata) {
messageClass = 'error';
if ('string' == typeof(this.cachedMetadata)) {
message = this.cachedMetadata;
showSource = true;
}
else if (! this.validateCache()) {
message = 'Cached metadata out of sync. ';
showSource = true;
}
}
}
if (message) {
var messageElement = document.createElement('p');
messageElement.setAttribute('id', 'metadata_issue');
messageElement.setAttribute('class', messageClass);
this.appendText(messageElement, message);
if (showSource) {
var link = document.createElement('a');
this.appendText(link, 'Click for source code.');
link.setAttribute('href', '#');
link.setAttribute('onclick',
'metadata_generator.addSourceElement(event)');
messageElement.appendChild(link);
}
var summary = document.getElementById('summary');
if (summary) {
summary.parentNode.insertBefore(messageElement, summary);
}
else {
var log = document.getElementById('log');
if (log) {
log.appendChild(messageElement);
}
}
}
},
setup: function() {
add_completion_callback(
function (tests, harness_status) {
metadata_generator.process(tests, harness_status);
});
}
};
metadata_generator.setup();
/* If the parent window has a testharness_properties object,
* we use this to provide the test settings. This is used by the
* default in-browser runner to configure the timeout and the
* rendering of results
*/
try {
if (window.opener && "testharness_properties" in window.opener) {
/* If we pass the testharness_properties object as-is here without
* JSON stringifying and reparsing it, IE fails & emits the message
* "Could not complete the operation due to error 80700019".
*/
setup(JSON.parse(JSON.stringify(window.opener.testharness_properties)));
}
} catch (e) {
}
// vim: set expandtab shiftwidth=4 tabstop=4:
@@ -0,0 +1,189 @@
<!DOCTYPE HTML>
<html>
<!--
Test cases for Touch Events v1 Recommendation
http://www.w3.org/TR/touch-events/
These tests are based on Mozilla-Nokia-Google's single-touch tests.
The primary purpose of the tests in this document is checking that the createTouch and
createTouchList interfaces of the Touch Events APIs are correctly implemented.
Other interactions are covered in other test files.
This document references Test Assertions (abbrev TA below) written by Cathy Chan
http://www.w3.org/2010/webevents/wiki/TestAssertions
-->
<head>
<title>Touch Events createTouch and createTouchList Interface Tests</title>
<meta name="viewport" content="width=device-width">
<script src="../../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script>
setup({explicit_done: true});
// Check a Touch object's atttributes for existence and correct type
// TA: 1.1.2, 1.1.3
function check_Touch_object (t) {
test(function() {
assert_equals(Object.prototype.toString.call(t), "[object Touch]", "touch is of type Touch");
}, "touch point is a Touch object");
[
["long", "identifier"],
["EventTarget", "target"],
["long", "screenX"],
["long", "screenY"],
["long", "clientX"],
["long", "clientY"],
["long", "pageX"],
["long", "pageY"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in t, name + " attribute in Touch object");
}, "Touch." + name + " attribute exists");
// type check
switch(type) {
case "long":
test(function() {
assert_equals(typeof t[name], "number", name + " attribute of type long");
}, "Touch." + name + " attribute is of type number (long)");
break;
case "EventTarget":
// An event target is some type of Element
test(function() {
assert_true(t[name] instanceof Element, "EventTarget must be an Element.");
}, "Touch." + name + " attribute is of type Element");
break;
default:
break;
}
});
}
// Check a TouchList object's attributes and methods for existence and proper type
// Also make sure all of the members of the list are Touch objects
// TA: 1.2.1, 1.2.2, 1.2.5, 1.2.6
function check_TouchList_object (tl) {
test(function() {
assert_equals(Object.prototype.toString.call(tl), "[object TouchList]", "touch list is of type TouchList");
}, "touch list is a TouchList object");
[
["unsigned long", "length"],
["function", "item"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in tl, name + " attribute in TouchList");
}, "TouchList." + name + " attribute exists");
// type check
switch(type) {
case "unsigned long":
test(function() {
assert_equals(typeof tl[name], "number", name + " attribute of type long");
}, "TouchList." + name + " attribute is of type number (unsigned long)");
break;
case "function":
test(function() {
assert_equals(typeof tl[name], "function", name + " attribute of type function");
}, "TouchList." + name + " attribute is of type function");
break;
default:
break;
}
});
// Each member of tl should be a proper Touch object
for (var i=0; i < tl.length; i++) {
check_Touch_object(tl.item(i));
}
// TouchList.item(x) should return null if x is >= TouchList.length
test(function() {
var t = tl.item(tl.length);
assert_equals(t, null, "TouchList.item(TouchList.length) must return null");
}, "TouchList.item returns null if the index is >= the length of the list");
}
function check_touch_clientXY(touch) {
assert_equals(touch.clientX, touch.pageX - window.pageXOffset, "touch.clientX is touch.pageX - window.pageXOffset.");
assert_equals(touch.clientY, touch.pageY - window.pageYOffset, "touch.clientY is touch.pageY - window.pageYOffset.");
}
function run() {
var target0 = document.getElementById("target0");
var touch1, touch2;
test(function() {
touch1 = document.createTouch(window, target0, 42, 15, 20, 35, 40);
assert_equals(touch1.target, target0, "touch.target is target0");
assert_equals(touch1.identifier, 42, "touch.identifier is requested value");
assert_equals(touch1.pageX, 15, "touch.pageX is requested value");
assert_equals(touch1.pageY, 20, "touch.pageY is requested value");
check_touch_clientXY(touch1);
assert_equals(touch1.screenX, 35, "touch.screenX is requested value");
assert_equals(touch1.screenY, 40, "touch.screenY is requested value");
}, "document.createTouch exists and creates a Touch object with requested properties");
touch2 = document.createTouch(window, target0, 44, 25, 30, 45, 50);
var touchList;
test(function() {
touchList = document.createTouchList();
assert_equals(touchList.length, 0, "touchList.length is 0");
}, "document.createTouchList exists and correctly creates a TouchList from zero Touch objects");
if (touchList)
check_TouchList_object(touchList);
test(function() {
touchList = document.createTouchList(touch1);
assert_equals(touchList.length, 1, "touchList.length is 1");
assert_equals(touchList.item(0), touch1, "touchList.item(0) is input touch1");
}, "document.createTouchList exists and correctly creates a TouchList from a single Touch");
if (touchList)
check_TouchList_object(touchList);
test(function() {
touchList = document.createTouchList(touch1, touch2);
assert_equals(touchList.length, 2, "touchList.length is 2");
assert_equals(touchList.item(0), touch1, "touchList.item(0) is input touch1");
assert_equals(touchList.item(1), touch2, "touchList.item(1) is input touch2");
}, "document.createTouchList exists and correctly creates a TouchList from two Touch objects");
if (touchList)
check_TouchList_object(touchList);
target0.innerHTML = "Test complete."
done();
}
</script>
<style>
div {
margin: 0em;
padding: 2em;
}
#target0 {
background: yellow;
border: 1px solid orange;
}
</style>
</head>
<body onload="run()">
<h1>Touch Events: createTouch and createTouchList tests</h1>
<div id="target0">Please wait for test to complete...</div>
<div id="log"></div>
</body>
</html>
@@ -0,0 +1,53 @@
<!DOCTYPE HTML>
<html>
<!--
Test cases for Touch Events v1 Recommendation
http://www.w3.org/TR/touch-events/
These tests are based on Mozilla-Nokia-Google's single-touch
tests and to some extent Olli Pettay's multi-touch tests.
The primary purpose of the tests in this document is checking that the interactions
of various Touch events are correctly implemented under any touch patterns.
This document references Test Assertions (abbrev TA below) written by Cathy Chan
http://www.w3.org/2010/webevents/wiki/TestAssertions
-->
<head>
<title>Touch Events Multi-Touch Interaction Test</title>
<meta name="viewport" content="width=device-width">
<script src="../../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="multi-touch-interactions.js"></script>
<style>
div {
margin: 0em;
padding: 1.5em;
}
#target0 {
background: yellow;
border: 1px solid orange;
}
#target1 {
background: lightblue;
border: 1px solid blue;
}
</style>
</head>
<body onload="run()">
<h1>Touch Events: Multi-Touch Interaction Test</h1>
<div id="target0">
Touch this box with one finger, then another one...
</div>
<div id="target1">
...then drag to this box, then touch with a third finger, and lift all your fingers.
</div>
<div id="debug"></div>
<div id="log"></div>
</body>
</html>
@@ -0,0 +1,371 @@
setup({explicit_done: true});
var debug = document.getElementById("debug");
function debug_print (x) {
/* uncomment below statement to show debug messages */
// document.getElementById("debug").innerHTML += x;
}
var starting_elements = {};
function check_list_subset_of_targetlist(list, list_name, targetlist, targetlist_name) {
var exist_in_targetlist;
for(i=0; i<list.length; i++) {
exist_in_targetlist=false;
for(j=0; j<targetlist.length; j++)
if(list.item(i).identifier==targetlist.item(j).identifier)
exist_in_targetlist=true;
assert_true(exist_in_targetlist, list_name + ".item("+i+") exists in " + targetlist_name);
}
}
function check_list_subset_of_two_targetlists(list, list_name, targetlist1, targetlist1_name, targetlist2, targetlist2_name) {
var exist_in_targetlists;
for(i=0; i<list.length; i++) {
exist_in_targetlists=false;
for(j=0; j<targetlist1.length; j++)
if(list.item(i).identifier==targetlist1.item(j).identifier)
exist_in_targetlists=true;
if(!exist_in_targetlists)
for(j=0; j<targetlist2.length; j++)
if(list.item(i).identifier==targetlist2.item(j).identifier)
exist_in_targetlists=true;
assert_true(exist_in_targetlists, list_name + ".item("+i+") exists in " + targetlist1_name + " or " + targetlist2_name);
}
}
function is_at_least_one_item_in_targetlist(list, targetlist) {
for(i=0; i<list.length; i++)
for(j=0; j<targetlist.length; j++)
if(list.item(i).identifier==targetlist.item(j).identifier)
return true;
return false;
}
function check_no_item_in_targetlist(list, list_name, targetlist, targetlist_name) {
for(i=0; i<list.length; i++)
for(j=0; j<targetlist.length; j++) {
assert_false(list.item(i).identifier==targetlist.item(j).identifier, list_name + ".item("+i+") exists in " + targetlist_name);
return;
}
}
function check_targets(list, target) {
for(i=0; i<list.length; i++)
assert_true(list.item(i).target==target, "item(" + i + ").target is element receiving event");
}
function check_starting_elements(list) {
for (i=0; i<list.length; i++) {
assert_equals(list.item(i).target, starting_elements[list.item(i).identifier], "item(" + i + ").target matches starting element");
}
}
function run() {
var target0 = document.getElementById("target0");
var target1 = document.getElementById("target1");
var test_touchstart = async_test("touchstart event received");
var test_touchmove = async_test("touchmove event received");
var test_touchend = async_test("touchend event received");
var test_mousedown = async_test("Interaction with mouse events");
var touchstart_received = 0;
var touchmove_received = 0;
var touchend_received = 0;
var touchstart_identifier;
// last received touch lists for comparison
var last_touches;
var last_targetTouches={};
var last_changedTouches={};
on_event(window, "touchstart", function onTouchStart(ev) {
// process event only if it's targeted at target0 or target1
if(ev.target != target0 && ev.target != target1 )
return;
ev.preventDefault();
if(!touchstart_received) {
// Check event ordering TA: 1.6.1
test_touchstart.step(function() {
assert_true(touchmove_received==0, "touchstart precedes touchmove");
assert_true(touchend_received==0, "touchstart precedes touchend");
});
test_touchstart.done();
test_mousedown.done(); // If we got here, then the mouse event test is not needed.
}
touchstart_received++;
// TA: 1.3.2.2, 1.3.2.4
test(function() {
assert_true(ev.changedTouches.length >= 1, "changedTouches.length is at least 1");
assert_true(ev.changedTouches.length <= ev.touches.length, "changedTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.changedTouches, "changedTouches", ev.touches, "touches");
}, "touchstart #" + touchstart_received + ": changedTouches is a subset of touches");
// TA: 1.3.3.2, 1.3.3.3
test(function() {
assert_true(ev.targetTouches.length >= 1, "targetTouches.length is at least 1");
assert_true(ev.targetTouches.length <= ev.touches.length, "targetTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.touches, "touches");
}, "touchstart #" + touchstart_received + ": targetTouches is a subset of touches");
// TA: 1.3.3.9
test(function() {
check_targets(ev.targetTouches, ev.target);
}, "touchstart #" + touchstart_received + ": targets of targetTouches are correct");
// TA: 1.3.4.2
test(function() {
assert_true(ev.touches.length >= 1, "touches.length is at least 1");
}, "touchstart #" + touchstart_received + ": touches.length is valid");
if(touchstart_received == 1) {
// TA: 1.3.3.5, 1.3.3.7
test(function() {
assert_true(ev.targetTouches.length <= ev.changedTouches.length, "targetTouches.length is smaller than changedTouches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.changedTouches, "changedTouches");
}, "touchstart #" + touchstart_received + ": targetTouches is a subset of changedTouches");
// TA: 1.3.4.3
test(function() {
assert_true(ev.touches.length==ev.changedTouches.length, "touches and changedTouches have the same length");
}, "touchstart #" + touchstart_received + ": touches and changedTouches have the same length");
} else {
// TA: 1.3.3.6
test(function() {
var diff_in_targetTouches = ev.targetTouches.length - (last_targetTouches[ev.target.id] ? last_targetTouches[ev.target.id].length : 0);
assert_true(diff_in_targetTouches > 0, "targetTouches.length is larger than last received targetTouches.length");
assert_true(diff_in_targetTouches <= ev.changedTouches.length, "change in targetTouches.length is smaller than changedTouches.length");
}, "touchstart #" + touchstart_received + ": change in targetTouches.length is valid");
// TA: 1.3.3.8
test(function() {
assert_true(is_at_least_one_item_in_targetlist(ev.targetTouches, ev.changedTouches), "at least one item of targetTouches is in changedTouches");
}, "touchstart #" + touchstart_received + ": at least one targetTouches item in changedTouches");
// TA: 1.3.4.4
test(function() {
var diff_in_touches = ev.touches.length - last_touches.length;
assert_true(diff_in_touches > 0, "touches.length is larger than last received touches.length");
assert_true(diff_in_touches == ev.changedTouches.length, "change in touches.length equals changedTouches.length");
}, "touchstart #" + touchstart_received + ": change in touches.length is valid");
// TA: 1.3.4.5
test(function() {
check_list_subset_of_two_targetlists(ev.touches, "touches", ev.changedTouches, "changedTouches", last_touches, "last touches");
}, "touchstart #" + touchstart_received + ": touches is subset of {changedTouches, last received touches}");
}
// save starting element of each new touch point
for (i=0; i<ev.changedTouches.length; i++) {
starting_elements[ev.changedTouches.item(i).identifier] = ev.changedTouches.item(i).target;
}
last_touches = ev.touches;
last_targetTouches[ev.target.id] = ev.targetTouches;
last_changedTouches = {}; // changedTouches are only saved for touchend events
});
on_event(window, "touchmove", function onTouchMove(ev) {
// process event only if it's targeted at target0 or target1
if(ev.target != target0 && ev.target != target1 )
return;
ev.preventDefault();
// TA: 1.6.1
test_touchmove.step(function() {
assert_true(touchstart_received>0, "touchmove follows touchstart");
// assert_false(touchend_received, "touchmove precedes touchend"); // this applies to scenario tests
});
test_touchmove.done();
touchmove_received++;
// do the detailed checking only for a few times
if(touchmove_received<6) {
// TA: 1.4.2.2, 1.4.2.4
test(function() {
assert_true(ev.changedTouches.length >= 1, "changedTouches.length is at least 1");
assert_true(ev.changedTouches.length <= ev.touches.length, "changedTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.changedTouches, "changedTouches", ev.touches, "touches");
}, "touchmove #" + touchmove_received + ": changedTouches is a subset of touches");
// TA: 1.4.3.2, 1.4.3.4
test(function() {
assert_true(ev.targetTouches.length >= 1, "targetTouches.length is at least 1");
assert_true(ev.targetTouches.length <= ev.touches.length, "targetTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.touches, "touches");
}, "touchmove #" + touchmove_received + ": targetTouches is a subset of touches");
// TA: 1.4.3.6
test(function() {
assert_true(is_at_least_one_item_in_targetlist(ev.targetTouches, ev.changedTouches), "at least one item of targetTouches is in changedTouches");
}, "touchmove #" + touchmove_received + ": at least one targetTouches item in changedTouches");
// TA: 1.4.3.8
test(function() {
check_targets(ev.targetTouches, ev.target);
}, "touchmove #" + touchmove_received + ": targets of targetTouches are correct");
// TA: 1.4.4.2
test(function() {
assert_true(ev.touches.length==last_touches.length, "length of touches is same as length of last received touches");
check_list_subset_of_targetlist(ev.touches, "touches", last_touches, "last received touches");
}, "touchmove #" + touchmove_received + ": touches must be same as last received touches");
// TA: 1.6.3
check_starting_elements(ev.changedTouches);
}
last_touches = ev.touches;
last_targetTouches[ev.target.id] = ev.targetTouches;
last_changedTouches = {}; // changedTouches are only saved for touchend events
});
on_event(window, "touchend", function onTouchEnd(ev) {
// process event only if it's targeted at target0 or target1
if(ev.target != target0 && ev.target != target1 )
return;
test_touchend.step(function() {
assert_true(touchstart_received>0, "touchend follows touchstart");
});
test_touchend.done();
touchend_received++;
debug_print("touchend #" + touchend_received + ":<br>");
debug_print("changedTouches.length=" + ev.changedTouches.length + "<br>");
debug_print("targetTouches.length=" + ev.targetTouches.length + "<br>");
debug_print("touches.length=" + ev.touches.length + "<br>");
for(i=0; i<ev.changedTouches.length; i++)
debug_print("changedTouches.item(" + i + ").target=" + ev.changedTouches.item(i).target.id + "<br>");
// TA: 1.5.2.2
test(function() {
assert_true(ev.changedTouches.length >= 1, "changedTouches.length is at least 1");
}, "touchend #" + touchend_received + ": length of changedTouches is valid");
// TA: 1.5.2.3
test(function() {
check_list_subset_of_targetlist(ev.changedTouches, "changedTouches", last_touches, "last received touches");
}, "touchend #" + touchend_received + ": changedTouches is a subset of last received touches");
// TA: 1.5.2.4, 1.5.2.5
test(function() {
check_no_item_in_targetlist(ev.changedTouches, "changedTouches", ev.touches, "touches");
check_no_item_in_targetlist(ev.changedTouches, "changedTouches", ev.targetTouches, "targetTouches");
}, "touchend #" + touchend_received + ": no item in changedTouches are in touches or targetTouches");
// TA: 1.5.2.6
test(function() {
var found=false;
for (i=0; i<ev.changedTouches.length; i++)
if (ev.changedTouches.item(i).target == ev.target)
found=true;
assert_true(found, "at least one item in changedTouches has matching target");
}, "touchend #" + touchend_received + ": at least one item in changedTouches targeted at this element");
// TA: 1.5.3.2, 1.5.3.3
test(function() {
assert_true(ev.targetTouches.length >= 0, "targetTouches.length is non-negative");
assert_true(ev.targetTouches.length <= ev.touches.length, "targetTouches.length is smaller than touches.length");
check_list_subset_of_targetlist(ev.targetTouches, "targetTouches", ev.touches, "touches");
}, "touchend #" + touchend_received + ": targetTouches is a subset of touches");
// TA: 1.5.3.5 (new)
test(function() {
check_targets(ev.targetTouches, ev.target);
}, "touchend #" + touchend_received + ": targets of targetTouches are correct");
// In some cases, when multiple touch points are released simultaneously
// the UA would dispatch the "same" touchend event (same changedTouches, same touches, but possibly different targetTouches)
// to each of the elements that are starting elments of the released touch points.
// in these situations, the subsequent events are exempt from TA 1.5.3.4 and 1.5.4.2
var same_event_as_last = false;
if (last_changedTouches && last_changedTouches.length==ev.changedTouches.length) {
same_event_as_last = true; // assume true until proven otherwise
for (i=0; i<last_changedTouches.length; i++) {
var match = false;
for (j=0; j<ev.changedTouches.length; j++)
if (last_changedTouches.item(i) == ev.changedTouches.item(j)) {
match = true;
break;
}
if (!match)
same_event_as_last = false;
}
}
if (!same_event_as_last) {
// TA: 1.5.3.4
// Getting semi-random failures on this and 1.5.4.2.
// See 1.5.4.2. Not sure if it's the same issue...
test(function() {
assert_true(last_targetTouches[ev.target.id].length > 0, "last received targetTouches.length is not zero");
var diff_in_targetTouches = last_targetTouches[ev.target.id].length - ev.targetTouches.length;
debug_print("diff_in_targetTouches=" + diff_in_targetTouches + "<br>");
assert_true(diff_in_targetTouches > 0, "targetTouches.length is smaller than last received targetTouches.length");
assert_true(diff_in_targetTouches <= ev.changedTouches.length, "change in targetTouches.length is smaller than changedTouches.length");
}, "touchend #" + touchend_received + ": change in targetTouches.length is valid");
// TA: 1.5.4.2
// Getting semi-random failures on this and 1.5.3.4.
// It looks like if fingers are lifted simultaneously, the "same" touchend event can be dispatched to two target elements
// but adapted to the element (same touches, changedTouches but different targetTouches).
// When one event is processed after another, ev.touches would end up being identical to last_touches, leading to failure.
// Question is why done() does not stop the processing of the latter event.
test(function() {
assert_true(last_touches.length > 0, "last received touches.length is not zero");
var diff_in_touches = last_touches.length - ev.touches.length;
debug_print("diff_in_touches=" + diff_in_touches + "<br>");
assert_true(diff_in_touches > 0, "touches.length is smaller than last received touches.length");
assert_equals(diff_in_touches, ev.changedTouches.length, "change in touches.length equals changedTouches.length");
}, "touchend #" + touchend_received + ": change in touches.length is valid");
}
// TA: 1.6.4
debug_print("touchend #" + touchend_received + ": TA 1.6.4<br>");
test(function() {
check_starting_elements(ev.changedTouches);
}, "touchend #" + touchend_received + ": event dispatched to correct element<br>");
debug_print("touchend #" + touchend_received + ": saving touch lists<br>");
last_touches = ev.touches;
last_targetTouches[ev.target.id] = ev.targetTouches;
last_changedTouches = ev.changedTouches;
debug_print("touchend #" + touchend_received + ": done<br>");
if(ev.touches.length==0)
done();
});
on_event(target0, "mousedown", function onMouseDown(ev) {
test_mousedown.step(function() {
assert_true(touchstart_received,
"The touchstart event must be dispatched before any mouse " +
"events. (If this fails, it might mean that the user agent does " +
"not implement W3C touch events at all.)"
);
});
test_mousedown.done();
if (!touchstart_received) {
// Abort the tests. If touch events are not supported, then most of
// the other event handlers will never be called, and the test will
// time out with misleading results.
done();
}
});
}
@@ -0,0 +1,277 @@
<!DOCTYPE HTML>
<html>
<!--
Test cases for Touch Events v1 Recommendation
http://www.w3.org/TR/touch-events/
These tests are based on Mozilla-Nokia-Google's single-touch
tests and to some extent Olli Pettay's multi-touch tests.
The primary purpose of the tests in this document is checking that the
various interfaces of the Touch Events APIs are correctly implemented.
Other interactions are covered in other test files.
This document references Test Assertions (abbrev TA below) written by Cathy Chan
http://www.w3.org/2010/webevents/wiki/TestAssertions
-->
<head>
<title>Touch Events Multi-Touch Interface Tests</title>
<meta name="viewport" content="width=device-width">
<script src="../../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<script src="../resources/testharness.js"></script>
<script>
setup({explicit_done: true});
// Check a Touch object's atttributes for existence and correct type
// TA: 1.1.2, 1.1.3
function check_Touch_object (t) {
test(function() {
assert_equals(Object.prototype.toString.call(t), "[object Touch]", "touch is of type Touch");
}, "touch point is a Touch object");
[
["long", "identifier"],
["EventTarget", "target"],
["long", "screenX"],
["long", "screenY"],
["long", "clientX"],
["long", "clientY"],
["long", "pageX"],
["long", "pageY"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in t, name + " attribute in Touch object");
}, "Touch." + name + " attribute exists");
// type check
switch(type) {
case "long":
test(function() {
assert_equals(typeof t[name], "number", name + " attribute of type long");
}, "Touch." + name + " attribute is of type number (long)");
break;
case "EventTarget":
// An event target is some type of Element
test(function() {
assert_true(t[name] instanceof Element, "EventTarget must be an Element.");
}, "Touch." + name + " attribute is of type Element");
break;
default:
break;
}
});
}
// Check a TouchList object's attributes and methods for existence and proper type
// Also make sure all of the members of the list are Touch objects
// TA: 1.2.1, 1.2.2, 1.2.5, 1.2.6
function check_TouchList_object (tl) {
test(function() {
assert_equals(Object.prototype.toString.call(tl), "[object TouchList]", "touch list is of type TouchList");
}, "touch list is a TouchList object");
[
["unsigned long", "length"],
["function", "item"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in tl, name + " attribute in TouchList");
}, "TouchList." + name + " attribute exists");
// type check
switch(type) {
case "unsigned long":
test(function() {
assert_equals(typeof tl[name], "number", name + " attribute of type long");
}, "TouchList." + name + " attribute is of type number (unsigned long)");
break;
case "function":
test(function() {
assert_equals(typeof tl[name], "function", name + " attribute of type function");
}, "TouchList." + name + " attribute is of type function");
break;
default:
break;
}
});
// Each member of tl should be a proper Touch object
for (var i=0; i < tl.length; i++) {
check_Touch_object(tl.item(i));
}
}
// Check a TouchEvent event's attributes for existence and proper type
// Also check that each of the event's TouchList objects are valid
// TA: 1.{3,4,5}.1.1, 1.{3,4,5}.1.2
function check_TouchEvent(ev) {
test(function() {
assert_true(ev instanceof TouchEvent, "event is a TouchEvent event");
}, ev.type + " event is a TouchEvent event");
[
["TouchList", "touches"],
["TouchList", "targetTouches"],
["TouchList", "changedTouches"],
["boolean", "altKey"],
["boolean", "metaKey"],
["boolean", "ctrlKey"],
["boolean", "shiftKey"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in ev, name + " attribute in " + ev.type + " event");
}, ev.type + "." + name + " attribute exists");
// type check
switch(type) {
case "boolean":
test(function() {
assert_equals(typeof ev[name], "boolean", name + " attribute of type boolean");
}, ev.type + "." + name + " attribute is of type boolean");
break;
case "TouchList":
test(function() {
assert_equals(Object.prototype.toString.call(ev[name]), "[object TouchList]", name + " attribute of type TouchList");
}, ev.type + "." + name + " attribute is of type TouchList");
// Now check the validity of the TouchList
check_TouchList_object(ev[name]);
break;
default:
break;
}
});
}
function is_touch_over_element(touch, element) {
var bounds = element.getBoundingClientRect();
return touch.pageX >= bounds.left && touch.pageX <= bounds.right &&
touch.pageY >= bounds.top && touch.pageY <= bounds.bottom;
}
function check_touch_clientXY(touch) {
assert_equals(touch.clientX, touch.pageX - window.pageXOffset, "touch.clientX is touch.pageX - window.pageXOffset.");
assert_equals(touch.clientY, touch.pageY - window.pageYOffset, "touch.clientY is touch.pageY - window.pageYOffset.");
}
function run() {
var target0 = document.getElementById("target0");
var target1 = document.getElementById("target1");
var test_touchstart = async_test("touchstart event received");
var test_touchmove = async_test("touchmove event received");
var test_touchend = async_test("touchend event received");
var test_mousedown = async_test("Interaction with mouse events");
var touchstart_received = 0;
var touchmove_received = false;
var touchend_received = false;
var invalid_touchmove_received = false;
on_event(target0, "touchstart", function onTouchStart(ev) {
ev.preventDefault();
if(!touchstart_received) {
// Check event ordering TA: 1.6.2
test_touchstart.step(function() {
assert_false(touchmove_received, "touchstart precedes touchmove");
assert_false(touchend_received, "touchstart precedes touchend");
});
test_touchstart.done();
test_mousedown.done(); // If we got here, then the mouse event test is not needed.
}
if(++touchstart_received <= 2)
check_TouchEvent(ev);
});
on_event(target0, "touchmove", function onTouchMove(ev) {
ev.preventDefault();
if (touchmove_received)
return;
touchmove_received = true;
test_touchmove.step(function() {
assert_true(touchstart_received>0, "touchmove follows touchstart");
assert_false(touchend_received, "touchmove precedes touchend");
});
test_touchmove.done();
check_TouchEvent(ev);
});
on_event(target1, "touchmove", function onTouchMove(ev) {
invalid_touchmove_received = true;
});
on_event(window, "touchend", function onTouchEnd(ev) {
touchend_received = true;
test_touchend.step(function() {
assert_true(touchstart_received>0, "touchend follows touchstart");
assert_true(touchmove_received, "touchend follows touchmove");
assert_false(invalid_touchmove_received, "touchmove dispatched to correct target");
});
test_touchend.done();
check_TouchEvent(ev);
done();
});
on_event(target0, "mousedown", function onMouseDown(ev) {
test_mousedown.step(function() {
assert_true(touchstart_received,
"The touchstart event must be dispatched before any mouse " +
"events. (If this fails, it might mean that the user agent does " +
"not implement W3C touch events at all.)"
);
});
test_mousedown.done();
if (!touchstart_received) {
// Abort the tests. If touch events are not supported, then most of
// the other event handlers will never be called, and the test will
// time out with misleading results.
done();
}
});
}
</script>
<style>
div {
margin: 0em;
padding: 2em;
}
#target0 {
background: yellow;
border: 1px solid orange;
}
#target1 {
background: lightblue;
border: 1px solid blue;
}
</style>
</head>
<body onload="run()">
<h1>Touch Events: multi-touch interface tests</h1>
<div id="target0">
Touch this box with one finger, then another one...
</div>
<div id="target1">
...then drag to this box and lift your fingers.
</div>
<div id="log"></div>
</body>
</html>
@@ -0,0 +1,382 @@
<!DOCTYPE HTML>
<html>
<!--
Test cases for Touch Events v1 Recommendation
http://www.w3.org/TR/touch-events/
These tests are based on Matt Bruebeck's single-touch tests.
There are NO multi-touch tests in this document.
This document references Test Assertions (abbrev TA below) written by Cathy Chan
http://www.w3.org/2010/webevents/wiki/TestAssertions
-->
<head>
<title>Touch Events Single Touch Tests</title>
<meta name="viewport" content="width=device-width">
<script src="../../../touch-emulator.js"></script>
<script> TouchEmulator(); </script>
<script src="../resources/testharness.js"></script>
<script>
setup({explicit_done: true});
// Check a Touch object's atttributes for existence and correct type
// TA: 1.1.2, 1.1.3
function check_Touch_object (t) {
test(function() {
assert_equals(Object.prototype.toString.call(t), "[object Touch]", name + " attribute of type TouchList");
}, "touch point is a Touch object");
[
["long", "identifier"],
["EventTarget", "target"],
["long", "screenX"],
["long", "screenY"],
["long", "clientX"],
["long", "clientY"],
["long", "pageX"],
["long", "pageY"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in t, name + " attribute in Touch object");
}, "Touch." + name + " attribute exists");
// type check
switch(type) {
case "long":
test(function() {
assert_equals(typeof t[name], "number", name + " attribute of type long");
}, "Touch." + name + " attribute is of type number (long)");
break;
case "EventTarget":
// An event target is some type of Element
test(function() {
assert_true(t[name] instanceof Element, "EventTarget must be an Element.");
}, "Touch." + name + " attribute is of type Element");
break;
default:
break;
}
});
}
// Check a TouchList object's attributes and methods for existence and proper type
// Also make sure all of the members of the list are Touch objects
// TA: 1.2.1, 1.2.2, 1.2.5
function check_TouchList_object (tl) {
test(function() {
assert_equals(Object.prototype.toString.call(tl), "[object TouchList]", name + " attribute of type TouchList");
}, "touch list is a TouchList object");
[
["unsigned long", "length"],
["function", "item"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in tl, name + " attribute in TouchList");
}, "TouchList." + name + " attribute exists");
// type check
switch(type) {
case "unsigned long":
test(function() {
assert_equals(typeof tl[name], "number", name + " attribute of type long");
}, "TouchList." + name + " attribute is of type number (unsigned long)");
break;
case "function":
test(function() {
assert_equals(typeof tl[name], "function", name + " attribute of type function");
}, "TouchList." + name + " attribute is of type function");
break;
default:
break;
}
});
// Each member of tl should be a proper Touch object
for (var i=0; i < tl.length; i++) {
check_Touch_object(tl.item(i));
}
}
// Check a TouchEvent event's attributes for existence and proper type
// Also check that each of the event's TouchList objects are valid
// TA: 1.{3,4,5}.1.1, 1.{3,4,5}.1.2
function check_TouchEvent(ev) {
test(function() {
assert_true(ev instanceof TouchEvent, "event is a TouchEvent event");
}, ev.type + " event is a TouchEvent event");
[
["TouchList", "touches"],
["TouchList", "targetTouches"],
["TouchList", "changedTouches"],
["boolean", "altKey"],
["boolean", "metaKey"],
["boolean", "ctrlKey"],
["boolean", "shiftKey"],
].forEach(function(attr) {
var type = attr[0];
var name = attr[1];
// existence check
test(function() {
assert_true(name in ev, name + " attribute in " + ev.type + " event");
}, ev.type + "." + name + " attribute exists");
// type check
switch(type) {
case "boolean":
test(function() {
assert_equals(typeof ev[name], "boolean", name + " attribute of type boolean");
}, ev.type + "." + name + " attribute is of type boolean");
break;
case "TouchList":
test(function() {
assert_equals(Object.prototype.toString.call(ev[name]), "[object TouchList]", name + " attribute of type TouchList");
}, ev.type + "." + name + " attribute is of type TouchList");
// Now check the validity of the TouchList
check_TouchList_object(ev[name]);
break;
default:
break;
}
});
}
function is_touch_over_element(touch, element) {
var bounds = element.getBoundingClientRect();
return touch.pageX >= bounds.left && touch.pageX <= bounds.right &&
touch.pageY >= bounds.top && touch.pageY <= bounds.bottom;
}
function check_touch_clientXY(touch) {
assert_equals(touch.clientX, touch.pageX - window.pageXOffset, "touch.clientX is touch.pageX - window.pageXOffset.");
assert_equals(touch.clientY, touch.pageY - window.pageYOffset, "touch.clientY is touch.pageY - window.pageYOffset.");
}
function check_screenXY_clientXY_pageXY(touch) {
assert_greater_than_equal(touch.screenX, 0, "touch.screenX is no less than 0");
assert_greater_than_equal(touch.screenY, 0, "touch.screenY is no less than 0");
assert_greater_than_equal(touch.clientX, 0, "touch.clientX is no less than 0");
assert_greater_than_equal(touch.clientY, 0, "touch.clientY is no less than 0");
assert_greater_than_equal(touch.pageX, 0, "touch.pageX is no less than 0");
assert_greater_than_equal(touch.pageY, 0, "touch.pageY is no less than 0");
}
function run() {
var target0 = document.getElementById("target0");
var target1 = document.getElementById("target1");
var test_touchstart = async_test("touchstart event received");
var test_touchmove = async_test("touchmove event received");
var test_touchend = async_test("touchend event received");
var test_mousedown = async_test("Interaction with mouse events");
var touchstart_received = false;
var touchmove_received = false;
var touchend_received = false;
var invalid_touchmove_received = false;
var touchstart_identifier;
on_event(target0, "touchstart", function onTouchStart(ev) {
ev.preventDefault();
// Check event ordering TA: 1.6.2
test_touchstart.step(function() {
assert_false(touchstart_received, "duplicate touchstart event");
assert_false(touchmove_received, "touchstart precedes touchmove");
assert_false(touchend_received, "touchstart precedes touchend");
});
test_touchstart.done();
if (touchstart_received)
return;
touchstart_received = true;
test_mousedown.done(); // If we got here, then the mouse event test is not needed.
check_TouchEvent(ev);
// TA: 1.3.2.1, 1.3.3.1, 1.3.4.1
test(function() {
assert_equals(ev.touches.length, 1, "One touch point.");
assert_equals(ev.changedTouches.length, 1, "One changed touch point.");
assert_equals(ev.targetTouches.length, 1, "One target touch point.");
}, "touchstart: all TouchList lengths are correct");
var t = ev.touches[0];
var ct = ev.changedTouches[0];
var tt = ev.targetTouches[0];
touchstart_identifier = t.identifier;
// TA: 1.3.3.3, 1.3.2.3, 1.3.3.4 (indirect (transitive))
test(function() {
assert_equals(ct.identifier, touchstart_identifier, "changedTouches identifier matches.");
assert_equals(tt.identifier, touchstart_identifier, "targetTouches identifier matches.");
}, "touchstart: all TouchList identifiers are consistent");
// TA: 1.3.3.9
test(function() {
assert_equals(tt.target, ev.target, "event target same as targetTouches target.");
}, "touchstart: event target same as targetTouches target");
test(function() {
assert_true(is_touch_over_element(t, target0), "touch.pageX/pageY is over target0.");
}, "touchstart: touch pageX/pageY inside of target element");
test(function() {
check_touch_clientXY(t);
}, "touchstart: touch clientX/clientY is consistent with pageX/pageY");
// Note we don't bother testing screenX/screenY values - there's no reliable way to
// verify they are consistent with clientX/clientY (due to unknown amount of window
// chrome), and also various forms of scaling mean they are in different units.
test(function() {
check_screenXY_clientXY_pageXY(t);
}, "touchstart: touch screenX/screenY pageX/pageY and clientX/clientY values are no less than 0");
});
on_event(target0, "touchmove", function onTouchMove(ev) {
ev.preventDefault();
if (touchmove_received)
return;
touchmove_received = true;
test_touchmove.step(function() {
assert_true(touchstart_received, "touchmove follows touchstart");
assert_false(touchend_received, "touchmove precedes touchend");
});
test_touchmove.done();
check_TouchEvent(ev);
// TA: 1.4.2.1, 1.4.3.1
test(function() {
assert_equals(ev.touches.length, 1, "One touch point.");
assert_equals(ev.changedTouches.length, 1, "One changed touch point.");
assert_equals(ev.targetTouches.length, 1, "One target touch point.");
}, "touchmove: all TouchList lengths are correct");
// 1.4.2.3, 1.4.3.3, 1.4.3.5, 1.4.4.3
test(function() {
assert_equals(ev.touches[0].identifier, touchstart_identifier, "Touch identifier matches.");
assert_equals(ev.changedTouches[0].identifier, touchstart_identifier, "Changed touch identifier matches.");
assert_equals(ev.targetTouches[0].identifier, touchstart_identifier, "Target touch identifier matches.");
}, "touchmove: all TouchList identifiers matches touchstart identifier");
// TA: 1.4.3.8
var tt = ev.targetTouches[0];
test(function() {
assert_equals(tt.target, ev.target, "event target same as targetTouches target.");
}, "touchmove: event target same as targetTouches target");
test(function() {
assert_true(is_touch_over_element(tt, target0) || is_touch_over_element(tt, target1),
"touch.pageX/pageY is over one of the targets.");
}, "touchmove: touch pageX/pageY inside of one of the target elements");
test(function() {
check_touch_clientXY(tt);
}, "touchmove: touch clientX/clientY is consistent with pageX/pageY");
test(function() {
check_screenXY_clientXY_pageXY(tt);
}, "touchmove: touch screenX/screenY pageX/pageY and clientX/clientY values are no less than 0");
});
on_event(target1, "touchmove", function onTouchMove(ev) {
invalid_touchmove_received = true;
});
on_event(window, "touchend", function onTouchEnd(ev) {
touchend_received = true;
test_touchend.step(function() {
assert_equals(ev.target, target0, "touchend is dispatched to the original target");
assert_true(touchstart_received, "touchend follows touchstart");
assert_true(touchmove_received, "touchend follows touchmove");
assert_false(invalid_touchmove_received, "touchmove dispatched to correct target");
});
test_touchend.done();
check_TouchEvent(ev);
// TA: 1.5.1.2, 1.5.3.1, 1.5.4.1
test(function() {
assert_equals(ev.touches.length, 0, "Zero touch points.");
assert_equals(ev.changedTouches.length, 1, "One changed touch point.");
assert_equals(ev.targetTouches.length, 0, "Zero target touch points.");
}, "touchend: all TouchList lengths are correct");
var t = ev.changedTouches[0];
// TA: 1.5.2.6, 1.5.2.3
test(function() {
assert_equals(t.identifier, touchstart_identifier, "changedTouches identifier matches.");
}, "touchend: touches identifier matches changedTouches identifier");
test(function() {
assert_true(is_touch_over_element(t, target1),
"touch.pageX/pageY is over target1.");
}, "touchend: touch pageX/pageY inside expected element");
test(function() {
check_touch_clientXY(t);
}, "touchend: touch clientX/clientY is consistent with pageX/pageY");
test(function() {
check_screenXY_clientXY_pageXY(t);
}, "touchend: touch screenX/screenY pageX/pageY and clientX/clientY values are no less than 0");
done();
});
on_event(target0, "mousedown", function onMouseDown(ev) {
test_mousedown.step(function() {
assert_true(touchstart_received,
"The touchstart event must be dispatched before any mouse " +
"events. (If this fails, it might mean that the user agent does " +
"not implement W3C touch events at all.)"
);
});
test_mousedown.done();
if (!touchstart_received) {
// Abort the tests. If touch events are not supported, then most of
// the other event handlers will never be called, and the test will
// time out with misleading results.
done();
}
});
}
</script>
<style>
div {
margin: 0em;
padding: 2em;
}
#target0 {
background: yellow;
border: 1px solid orange;
}
#target1 {
background: lightblue;
border: 1px solid blue;
}
</style>
</head>
<body onload="run()">
<h1>Touch Events: single-touch tests</h1>
<div id="target0">
Touch this box with one finger (or other pointing device)...
</div>
<div id="target1">
...then drag to this box and lift your finger.
</div>
<div id="log"></div>
</body>
</html>
+361
View File
@@ -0,0 +1,361 @@
(function(window, document, exportName, undefined) {
"use strict";
var isMultiTouch = false;
var multiTouchStartPos;
var eventTarget;
var touchElements = {};
// polyfills
if(!document.createTouch) {
document.createTouch = function(view, target, identifier, pageX, pageY, screenX, screenY, clientX, clientY) {
// auto set
if(clientX == undefined || clientY == undefined) {
clientX = pageX - window.pageXOffset;
clientY = pageY - window.pageYOffset;
}
return new Touch(target, identifier, {
pageX: pageX,
pageY: pageY,
screenX: screenX,
screenY: screenY,
clientX: clientX,
clientY: clientY
});
};
}
if(!document.createTouchList) {
document.createTouchList = function() {
var touchList = new TouchList();
for (var i = 0; i < arguments.length; i++) {
touchList[i] = arguments[i];
}
touchList.length = arguments.length;
return touchList;
};
}
/**
* create an touch point
* @constructor
* @param target
* @param identifier
* @param pos
* @param deltaX
* @param deltaY
* @returns {Object} touchPoint
*/
function Touch(target, identifier, pos, deltaX, deltaY) {
deltaX = deltaX || 0;
deltaY = deltaY || 0;
this.identifier = identifier;
this.target = target;
this.clientX = pos.clientX + deltaX;
this.clientY = pos.clientY + deltaY;
this.screenX = pos.screenX + deltaX;
this.screenY = pos.screenY + deltaY;
this.pageX = pos.pageX + deltaX;
this.pageY = pos.pageY + deltaY;
}
/**
* create empty touchlist with the methods
* @constructor
* @returns touchList
*/
function TouchList() {
var touchList = [];
touchList.item = function(index) {
return this[index] || null;
};
// specified by Mozilla
touchList.identifiedTouch = function(id) {
return this[id + 1] || null;
};
return touchList;
}
/**
* Simple trick to fake touch event support
* this is enough for most libraries like Modernizr and Hammer
*/
function fakeTouchSupport() {
var objs = [window, document.documentElement];
var props = ['ontouchstart', 'ontouchmove', 'ontouchcancel', 'ontouchend'];
for(var o=0; o<objs.length; o++) {
for(var p=0; p<props.length; p++) {
if(objs[o] && objs[o][props[p]] == undefined) {
objs[o][props[p]] = null;
}
}
}
}
/**
* we don't have to emulate on a touch device
* @returns {boolean}
*/
function hasTouchSupport() {
return ("ontouchstart" in window) || // touch events
(window.Modernizr && window.Modernizr.touch) || // modernizr
(navigator.msMaxTouchPoints || navigator.maxTouchPoints) > 2; // pointer events
}
/**
* disable mouseevents on the page
* @param ev
*/
function preventMouseEvents(ev) {
ev.preventDefault();
ev.stopPropagation();
}
/**
* only trigger touches when the left mousebutton has been pressed
* @param touchType
* @returns {Function}
*/
function onMouse(touchType) {
return function(ev) {
// prevent mouse events
preventMouseEvents(ev);
if (ev.which !== 1) {
return;
}
// The EventTarget on which the touch point started when it was first placed on the surface,
// even if the touch point has since moved outside the interactive area of that element.
// also, when the target doesnt exist anymore, we update it
if (ev.type == 'mousedown' || !eventTarget || (eventTarget && !eventTarget.dispatchEvent)) {
eventTarget = ev.target;
}
// shiftKey has been lost, so trigger a touchend
if (isMultiTouch && !ev.shiftKey) {
triggerTouch('touchend', ev);
isMultiTouch = false;
}
triggerTouch(touchType, ev);
// we're entering the multi-touch mode!
if (!isMultiTouch && ev.shiftKey) {
isMultiTouch = true;
multiTouchStartPos = {
pageX: ev.pageX,
pageY: ev.pageY,
clientX: ev.clientX,
clientY: ev.clientY,
screenX: ev.screenX,
screenY: ev.screenY
};
triggerTouch('touchstart', ev);
}
// reset
if (ev.type == 'mouseup') {
multiTouchStartPos = null;
isMultiTouch = false;
eventTarget = null;
}
}
}
/**
* trigger a touch event
* @param eventName
* @param mouseEv
*/
function triggerTouch(eventName, mouseEv) {
var touchEvent = document.createEvent('Event');
touchEvent.initEvent(eventName, true, true);
touchEvent.altKey = mouseEv.altKey;
touchEvent.ctrlKey = mouseEv.ctrlKey;
touchEvent.metaKey = mouseEv.metaKey;
touchEvent.shiftKey = mouseEv.shiftKey;
touchEvent.touches = getActiveTouches(mouseEv, eventName);
touchEvent.targetTouches = getActiveTouches(mouseEv, eventName);
touchEvent.changedTouches = getChangedTouches(mouseEv, eventName);
eventTarget.dispatchEvent(touchEvent);
}
/**
* create a touchList based on the mouse event
* @param mouseEv
* @returns {TouchList}
*/
function createTouchList(mouseEv) {
var touchList = new TouchList();
if (isMultiTouch) {
var f = TouchEmulator.multiTouchOffset;
var deltaX = multiTouchStartPos.pageX - mouseEv.pageX;
var deltaY = multiTouchStartPos.pageY - mouseEv.pageY;
touchList.push(new Touch(eventTarget, 1, multiTouchStartPos, (deltaX*-1) - f, (deltaY*-1) + f));
touchList.push(new Touch(eventTarget, 2, multiTouchStartPos, deltaX+f, deltaY-f));
} else {
touchList.push(new Touch(eventTarget, 1, mouseEv, 0, 0));
}
return touchList;
}
/**
* receive all active touches
* @param mouseEv
* @returns {TouchList}
*/
function getActiveTouches(mouseEv, eventName) {
// empty list
if (mouseEv.type == 'mouseup') {
return new TouchList();
}
var touchList = createTouchList(mouseEv);
if(isMultiTouch && mouseEv.type != 'mouseup' && eventName == 'touchend') {
touchList.splice(1, 1);
}
return touchList;
}
/**
* receive a filtered set of touches with only the changed pointers
* @param mouseEv
* @param eventName
* @returns {TouchList}
*/
function getChangedTouches(mouseEv, eventName) {
var touchList = createTouchList(mouseEv);
// we only want to return the added/removed item on multitouch
// which is the second pointer, so remove the first pointer from the touchList
//
// but when the mouseEv.type is mouseup, we want to send all touches because then
// no new input will be possible
if(isMultiTouch && mouseEv.type != 'mouseup' &&
(eventName == 'touchstart' || eventName == 'touchend')) {
touchList.splice(0, 1);
}
return touchList;
}
/**
* show the touchpoints on the screen
*/
function showTouches(ev) {
var touch, i, el, styles;
// first all visible touches
for(i = 0; i < ev.touches.length; i++) {
touch = ev.touches[i];
el = touchElements[touch.identifier];
if(!el) {
el = touchElements[touch.identifier] = document.createElement("div");
document.body.appendChild(el);
}
styles = TouchEmulator.template(touch);
for(var prop in styles) {
el.style[prop] = styles[prop];
}
}
// remove all ended touches
if(ev.type == 'touchend' || ev.type == 'touchcancel') {
for(i = 0; i < ev.changedTouches.length; i++) {
touch = ev.changedTouches[i];
el = touchElements[touch.identifier];
if(el) {
el.parentNode.removeChild(el);
delete touchElements[touch.identifier];
}
}
}
}
/**
* TouchEmulator initializer
*/
function TouchEmulator() {
if (hasTouchSupport()) {
return;
}
fakeTouchSupport();
window.addEventListener("mousedown", onMouse('touchstart'), true);
window.addEventListener("mousemove", onMouse('touchmove'), true);
window.addEventListener("mouseup", onMouse('touchend'), true);
window.addEventListener("mouseenter", preventMouseEvents, true);
window.addEventListener("mouseleave", preventMouseEvents, true);
window.addEventListener("mouseout", preventMouseEvents, true);
window.addEventListener("mouseover", preventMouseEvents, true);
// it uses itself!
window.addEventListener("touchstart", showTouches, false);
window.addEventListener("touchmove", showTouches, false);
window.addEventListener("touchend", showTouches, false);
window.addEventListener("touchcancel", showTouches, false);
}
// start distance when entering the multitouch mode
TouchEmulator.multiTouchOffset = 75;
/**
* css template for the touch rendering
* @param touch
* @returns object
*/
TouchEmulator.template = function(touch) {
var size = 30;
var transform = 'translate('+ (touch.clientX-(size/2)) +'px, '+ (touch.clientY-(size/2)) +'px)';
return {
position: 'fixed',
left: 0,
top: 0,
background: '#fff',
border: 'solid 1px #999',
opacity: .6,
borderRadius: '100%',
height: size + 'px',
width: size + 'px',
padding: 0,
margin: 0,
display: 'block',
overflow: 'hidden',
pointerEvents: 'none',
webkitUserSelect: 'none',
mozUserSelect: 'none',
userSelect: 'none',
webkitTransform: transform,
mozTransform: transform,
transform: transform
}
};
// export
if (typeof define == "function" && define.amd) {
define(function() {
return TouchEmulator;
});
} else if (typeof module != "undefined" && module.exports) {
module.exports = TouchEmulator;
} else {
window[exportName] = TouchEmulator;
}
})(window, document, "TouchEmulator");