Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
203 lines (171 loc) · 5.89 KB
/
Copy pathscript.js
File metadata and controls
203 lines (171 loc) · 5.89 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
// module-reference: page logic. Loaded in <head> without `defer`, so the
// Alpine component below is registered before the deferred Alpine script starts.
window.prettyPrintJSON = function (obj, indent = 2) {
// First, stringify the object normally to handle all JSON syntax
let jsonString = JSON.stringify(obj, null, indent)
// Then show escaped newlines in strings as real line breaks. Escaped
// backslashes are matched too and kept, so a literal "\n" (`\\n` in
// JSON) stays as it is.
return jsonString.replace(/\\\\|\\n/g, (escape) =>
escape === '\\n' ? '\n' + ' '.repeat(indent + 2) : escape
)
}
const TAB_KEY = 'module-reference.tab'
// all page state; registered before the deferred Alpine script starts
document.addEventListener('alpine:init', () => {
Alpine.data('reference', () => ({
edrys: undefined,
tabs: [
{ id: 'data', label: 'Data' },
{ id: 'messages', label: 'Messages' },
{ id: 'state', label: 'State' },
],
tab: 'data',
send: { subject: '', body: '', recipient: 'all' },
messages: [],
seq: 0,
max: 200,
promiscuous: true,
unsubscribe: null,
result: null,
init() {
try {
const saved = localStorage.getItem(TAB_KEY)
if (this.tabs.some((t) => t.id === saved)) this.tab = saved
} catch (e) {}
Edrys.onUpdate((e) => {
this.edrys = { ...e }
})
this.listen()
this.$watch('promiscuous', () => this.listen())
this.$watch('tab', (tab) => {
try {
localStorage.setItem(TAB_KEY, tab)
} catch (e) {}
// CodeMirror measures itself wrong while its tab is hidden
if (tab === 'state') this.$nextTick(() => editor?.refresh())
})
},
// re-registered when promiscuous changes, with onMessage's unsubscribe
listen() {
if (this.unsubscribe) this.unsubscribe()
this.unsubscribe = Edrys.onMessage((m) => {
// usernames are long keys; keep the display name the sender had
const sender = Edrys.liveClass?.users?.[m.from]
this.messages.unshift({
...m,
id: ++this.seq,
fromName: sender?.displayName || m.from,
})
if (this.messages.length > this.max) this.messages.pop()
}, this.promiscuous)
},
sendMessage() {
const { subject, body, recipient } = this.send
Edrys.sendMessage(
subject,
body,
recipient === 'all' ? undefined : recipient
)
},
// tab bar: arrow keys move between tabs, as in the ARIA tabs pattern
move(step) {
const i = this.tabs.findIndex((t) => t.id === this.tab)
const n = this.tabs.length
this.tab = this.tabs[(i + step + n) % n].id
this.$nextTick(() => document.getElementById('tab-' + this.tab).focus())
},
count(tab) {
return tab === 'messages' ? this.messages.length || '' : ''
},
users() {
return Object.values(this.edrys.liveClass.users)
},
// the state of the room this peer is in, and of all other rooms
roomState() {
return this.edrys.liveClass.rooms[this.edrys.liveUser?.room] || {}
},
otherRooms() {
return Object.entries(this.edrys.liveClass.rooms).filter(
([name]) => name !== this.edrys.liveUser?.room
)
},
otherUsers() {
return this.users().filter((u) => u.name !== this.edrys.username)
},
roleLabel(role) {
return role ? role[0].toUpperCase() + role.slice(1) : ''
},
// a config value as Edrys hands it over: parsed JSON, a string, or empty
isEmpty(value) {
return value === undefined || value === null || value === ''
},
isBlock(value) {
return !!value && typeof value === 'object'
},
show(value) {
return this.isEmpty(value) ? 'none' : prettyPrintJSON(value)
},
body(value) {
return typeof value === 'string' ? value : prettyPrintJSON(value)
},
preview(value) {
return typeof value === 'string' ? value : JSON.stringify(value)
},
time(date) {
return new Date(date).toLocaleTimeString()
},
}))
})
// The example editor: a local CodeMirror instance, not synced to peers
let editor
window.initEditor = () => {
editor = CodeMirror(document.getElementById('editor'), {
mode: 'javascript',
// colours in style.css (.cm-s-edrys), from the classroom's theme
theme: 'edrys',
lineNumbers: true,
autoCloseBrackets: true,
matchBrackets: true,
tabSize: 2,
value: `// All modules in a room share one state Map,
// so prefix keys with your module's name.
// Add a map and insert two values
let state = Edrys.getState('reference.demo', 'Map')
// This performs one transaction, otherwise
// the onUpdate event would be triggered on every change
Edrys.updateState(() => {
state.set('option', 12)
state.set('option2', 13)
})
// create a sharable awareness state
let awareness = Edrys.getState('reference.demo', 'Awareness')
// read a value, this returns undefined if it
// has not been set before, or the value itself
console.log('Get Value =>', Edrys.getState('reference.counter', 'Value'))
// update or initialize the value directly by passing a new value
Edrys.getState('reference.counter', 'Value', 12)
// clear the value
// Edrys.clearState('reference.counter')
// Edrys.getState() returns the entire Map of the room,
// shown under "Room state" below
// the value of the last line is shown below the editor
Edrys.getState('reference.counter', 'Value')`,
})
}
// Runs the editor content; returns what to show below the editor
function evalCode() {
let result
try {
result = eval(editor.getValue())
} catch (e) {
return { failed: true, text: `${e.name}: ${e.message}` }
}
if (result === undefined) return { failed: false, text: 'Done.' }
try {
return { failed: false, text: prettyPrintJSON(result) }
} catch (e) {
// not serialisable, e.g. a Yjs type with circular references
return { failed: false, text: String(result) }
}
}