forked from mathiasbynens/virtual-scroller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorting.html
76 lines (63 loc) · 2.09 KB
/
sorting.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<html>
<head>
<title>Sorting contacts</title>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
<style>
body {
font-family: Roboto, Helvetica, sans-serif;
max-width: 600px;
margin: 0 auto;
display: flex;
flex-direction: column;
}
label {
margin: 10px 0;
}
virtual-scroller {
flex: 1;
border-top: 2px solid #eee;
border-bottom: 2px solid #eee;
}
</style>
</head>
<body>
<label>
<input type="checkbox" onchange="toggleElementKey(this.checked)"> Use
<code>contact.guid</code> as
<code>elementKey</code>
</label>
<virtual-scroller>
<template>
<contact-element sortable></contact-element>
</template>
</virtual-scroller>
<script type="module">
import { ItemSource } from '../virtual-scroller-element.js';
import './contacts/contact-element.js';
const virtualScroller = document.querySelector('virtual-scroller');
const onMoveup = (event) => moveContact(event.target.contact, -1);
const onMovedown = (event) => moveContact(event.target.contact, 1);
virtualScroller.updateElement = (element, contact) => {
element.addEventListener('moveup', onMoveup);
element.addEventListener('movedown', onMovedown);
element.contact = contact;
};
let myContacts = null;
fetch('contacts/contacts.json').then((resp) => resp.json()).then((contacts) => {
myContacts = contacts;
toggleElementKey();
});
function moveContact(contact, offset) {
const i = myContacts.indexOf(contact);
const newI = Math.max(0, Math.min(myContacts.length, i + offset));
myContacts.splice(i, 1); // remove it
myContacts.splice(newI, 0, contact); // add it to new position
virtualScroller.itemsChanged(); // notify virtual-scroller
}
window.toggleElementKey = function toggleElementKey(useGuid) {
const key = useGuid ? (contact) => contact.guid : (_, index) => index;
virtualScroller.itemSource = ItemSource.fromArray(myContacts, key);
};
</script>
</body>
</html>