forked from rocicorp/replicache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
261 lines (224 loc) · 7.35 KB
/
Copy pathmain.js
File metadata and controls
261 lines (224 loc) · 7.35 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import {handleDragStart, isDragging} from './drag.js';
import Replicache from 'replicache';
import {html, render} from 'lit-html';
import {classMap} from 'lit-html/directives/class-map.js';
import {live} from 'lit-html/directives/live';
import {repeat} from 'lit-html/directives/repeat.js';
import '@material/mwc-checkbox/mwc-checkbox.js';
import '@material/mwc-fab';
import '@material/mwc-icon';
import '@material/mwc-icon-button';
import '@material/mwc-textfield';
import '@material/mwc-top-app-bar/mwc-top-app-bar.js';
import {generateKeyBetween} from 'fractional-indexing';
/* eslint-env browser */
/* global Pusher */
const key = id => `/todo/${id}`;
const dataLayerAuth = '1';
const dataLayerBase = 'https://replicache-sample-todo.now.sh/serve/';
let rep = new Replicache({
name: 'todo',
// URL that serves the Client View. The Diff Server pulls new Client Views
// from this URL. See
// https://github.com/rocicorp/replicache/blob/main/SERVER_SETUP.md for more
// information on setting up your Client View.
clientViewURL: `${dataLayerBase}replicache-client-view`,
// URL of the Diff Server to use. The Replicache client periodically fetches
// the Client View from your service through the Diff Server, which returns
// a delta to the client. You can use our hosted Diff Server (as here) or
// a local Diff Server, which can be useful during development. See
// https://github.com/rocicorp/replicache/blob/main/SERVER_SETUP.md for more
// information on setting up your Client View or a local Diff Server.
diffServerURL: 'https://serve.replicache.dev/pull',
// Auth token for the Diff Server. When running against the
// replicache-sample-todo backend as here, this value should be '1'. To run
// against your own backend, replace this value with the Account ID assigned
// when creating a Replicache account at https://serve.replicache.dev/signup.
diffServerAuth: '1',
// URL of your service's Replicache batch endpoint. Replicache
// will send batches of mutations here for application.
batchURL: `${dataLayerBase}replicache-batch`,
// Auth token for your client view and batch endpoints. You can use this value
// '1' when running against the replicache-sample-todo backend.
dataLayerAuth: '1',
pushDelay: 500,
syncInterval: null,
});
rep.onSync = syncing => {
const icon = document.querySelector('.sync-icon');
icon.textContent = 'sync';
icon.classList.remove('offline');
if (syncing) {
icon.classList.add('syncing');
setTimeout(() => icon.classList.toggle('syncing', false), 500);
}
if (!rep.online) {
icon.classList.add('offline');
icon.textContent = 'sync_problem';
}
};
rep.subscribe(
async tx => {
const res = [];
for await (const v of tx.scan({indexName: 'byOrder2'})) {
res.push(v);
}
return res;
},
{
onData: update,
},
);
async function initIndexes() {
await rep.createIndex({
name: 'byOrder2',
keyPrefix: '/todo/',
jsonPointer: '/order',
});
console.log('indexes created!');
}
const updateTodo = rep.register('updateTodo', async (tx, changes) => {
const todo = await tx.get(key(changes.id));
Object.assign(todo, changes);
await tx.put(key(todo.id), todo);
});
const deleteTodo = rep.register('deleteTodo', async (tx, {id}) => {
await tx.del(key(id));
});
const createTodo = rep.register('createTodo', async (tx, todo) => {
await tx.put(key(todo.id), todo);
});
async function handleCreate() {
const prev = todos[todos.length - 1]?.order || null;
const next = null;
const order = generateKeyBetween(prev, next);
await createTodo({
id: Math.round(Math.random() * 2 ** 30),
listID: 1,
text: 'Untitled',
order,
complete: false,
});
document
.querySelector('.todo-list .todo-item:last-of-type .textwrap span')
.focus();
}
async function handleDelete(id, e) {
// Need to stop propagation rather than just preventDefault() because we don't
// want the handler at the item level to interpret this click as a checkmark toggle.
e.stopPropagation();
await deleteTodo({id});
}
async function handleFocus(e) {
if ('ontouchstart' in window) {
return;
}
const selection = getSelection();
const range = document.createRange();
range.selectNodeContents(e.target);
selection.removeAllRanges();
selection.addRange(range);
}
async function handleBlur(id, e) {
const text = e.target.textContent;
await updateTodo({id, text});
}
async function handleCheck(id, e) {
updateTodo({id, complete: !e.currentTarget.checked});
}
async function handleItemClick(id, e) {
const checkbox = e.currentTarget.parentElement.querySelector('mwc-checkbox');
checkbox.checked = !checkbox.checked;
updateTodo({id, complete: checkbox.checked});
}
async function handleTextClick(e) {
e.stopPropagation();
}
async function handleDragEnd(id, order) {
await updateTodo({id, order});
}
function handleKeydown(e, isLast) {
if (isLast && e.key == 'Tab' && !e.shiftKey) {
handleCreate();
}
}
let todos = [];
function update(newTodos) {
todos = newTodos;
// Using lit-html, but the principle is the same in any UI framework.
// See https://github.com/rocicorp/replicache-sdk-js/tree/master/sample/cal
// for an example using React.
const item = (todo, index) => html`<div
class=${classMap({'todo-item': true, dragging: isDragging(todo.id)})}
>
<mwc-icon
class="handle"
@mousedown=${e =>
handleDragStart(e, todo.id, index, () => todos, update, handleDragEnd)}
>drag_handle</mwc-icon
>
<mwc-checkbox
.checked=${live(todo.complete)}
@input=${e => handleCheck(todo.id, e)}
></mwc-checkbox>
<div class="textwrap" @click=${e => handleItemClick(todo.id, e)}>
<span
@focus=${handleFocus}
@click=${handleTextClick}
@blur=${e => handleBlur(todo.id, e)}
contenteditable
>${todo.text}</span
>
</div>
<mwc-icon-button
@click=${e => handleDelete(todo.id, e)}
@keydown=${e => handleKeydown(e, index == todos.length - 1)}
icon="delete"
></mwc-icon-button>
</div>`;
render(
repeat(newTodos, todo => todo.id, item),
document.querySelector('.todo-list'),
);
}
async function init() {
await initIndexes();
rep.sync();
}
init();
// FOUC
window.addEventListener('load', async () => {
document.body.style.visibility = 'visible';
});
document.querySelector('mwc-fab').addEventListener('click', e => {
e.preventDefault();
handleCreate();
});
// argh, tired of fighting with serviceworker for now.
// navigator.serviceWorker?.register('sw.js');
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
registration.unregister();
}
});
window.addEventListener('online', e => rep.sync());
// Push
Pusher.logToConsole = true;
let pusher = null;
initPusher();
// Reconstruct the web socket connection on every focus event - this is intended
// to combat the app going dead for 15s-30s in the case where a user switches
// away from a mobile browser and then swithes back. We were observing the
// connections getting torn down, but pusher only tries to reconnect every 15s
// or so.
window.addEventListener('focus', initPusher);
function initPusher() {
if (pusher != null) {
pusher.disconnect();
}
pusher = new Pusher('8084fa6056631d43897d', {
cluster: 'us3',
});
const sub = pusher.subscribe(`u-${dataLayerAuth}`);
sub.bind('poke', () => rep.sync());
}