-
Moritz Langenstein authoredMoritz Langenstein authored
app.js 3.15 KiB
const Y = require("yjs")
require("y-memory")(Y)
require("y-map")(Y)
require("y-array")(Y)
require("./y-webrtc")(Y)
const uuidv4 = require("uuid/v4")
const { line, curveBasis } = require("d3")
Y({
db: {
name: "memory",
},
connector: {
name: "webrtc",
host: "localhost",
port: 3000,
path: "/api",
},
share: {
drawing: "Map",
},
}).then((y) => {
const userIDElem = document.getElementById("user-id")
const peerIDElem = document.getElementById("peer-id")
const peerButton = document.getElementById("peer-connect")
const connectedP = document.getElementById("connected-peers")
userIDElem.value = y.db.userId
y.connector.onUserEvent(function(event) {
switch (event.action) {
case "userID":
userIDElem.value = event.id
break
case "userJoined":
var peerElem = document.createElement("li")
peerElem.innerHTML = event.user
connectedP.appendChild(peerElem)
break
case "userLeft":
for (var peer of connectedP.children) {
if (peer.innerHTML == event.user) {
connectedP.removeChild(peer)
}
}
break
}
})
peerButton.onclick = function() {
const peerID = peerIDElem.value
if (peerID == "") {
return
}
y.connector.connectToPeer(peerID)
peerIDElem.value = ""
}
const whiteboard = document.getElementById("whiteboard")
var painting = false
var paths = new Map()
var pathID
function createOrUpdatePath(uid, points) {
const lineFn = line()
.x((d) => d[0])
.y((d) => d[1])
.curve(curveBasis)
var path = paths.get(uid)
if (path === undefined) {
path = document.createElementNS("http://www.w3.org/2000/svg", "path")
path.setAttribute("stroke", "blue")
path.setAttribute("stroke-width", 3)
path.setAttribute("fill", "none")
path.setAttribute("pointer-events", "none")
whiteboard.appendChild(path)
paths.set(uid, path)
}
points = points.toArray().filter((point) => point !== undefined)
if (points.length <= 0) {
path.removeAttribute("d")
return path
}
path.setAttribute("d", lineFn(points))
return path
}
whiteboard.onmousedown = function(e) {
painting = true
const mouse = {
x: e.offsetX,
y: e.offsetY,
}
pathID = uuidv4()
const sharedPath = y.share.drawing.set(pathID, Y.Array)
sharedPath.push([[mouse.x, mouse.y]])
}
whiteboard.onmouseup = function() {
painting = false
}
whiteboard.onmousemove = function(e) {
const mouse = {
x: e.offsetX,
y: e.offsetY,
}
if (painting) {
const sharedPath = y.share.drawing.get(pathID)
sharedPath.push([[mouse.x, mouse.y]])
}
}
y.share.drawing.observe(function(lineEvent) {
const lineID = lineEvent.name
switch (lineEvent.type) {
case "add":
createOrUpdatePath(lineID, lineEvent.value)
lineEvent.value.observe(function(pointEvent) {
switch (pointEvent.type) {
case "insert":
createOrUpdatePath(lineID, pointEvent.object)
break
}
})
break
}
})
})