Compare commits

..

No commits in common. "ecda8dde24e23b089da9db09b156d64ee70ee95f" and "4b3c8f94497c6a5d5e5e5e73e128326736cefd1d" have entirely different histories.

6 changed files with 209 additions and 201 deletions

1
.gitignore vendored
View file

@ -8,4 +8,3 @@ docker-compose*.yml
!docker-compose.example.yml !docker-compose.example.yml
config*.toml config*.toml
arimelody-web arimelody-web
arimelody-web.tar.gz

View file

@ -1,12 +0,0 @@
EXEC = arimelody-web
.PHONY: $(EXEC)
$(EXEC):
GOOS=linux GOARCH=amd64 go build -o $(EXEC)
bundle: $(EXEC)
tar czf $(EXEC).tar.gz $(EXEC) admin/components/ admin/views/ admin/static/ views/ public/ schema-migration/
clean:
rm $(EXEC) $(EXEC).tar.gz

9
bundle.sh Executable file
View file

@ -0,0 +1,9 @@
#!/bin/bash
# simple script to pack up arimelody.me for production distribution
if [ ! -f arimelody-web ]; then
echo "[FATAL] ./arimelody-web not found! please run \`go build -o arimelody-web\` first."
exit 1
fi
tar czf arimelody-web.tar.gz arimelody-web admin/components/ admin/views/ admin/static/ views/ public/ schema-migration/

View file

@ -17,9 +17,8 @@ type CursorClient struct {
ID int32 ID int32
Conn *websocket.Conn Conn *websocket.Conn
Route string Route string
X float32 X int16
Y float32 Y int16
Click bool
Disconnected bool Disconnected bool
} }
@ -92,7 +91,7 @@ func handleClient(client *CursorClient) {
if otherClient.ID == client.ID { continue } if otherClient.ID == client.ID { continue }
if otherClient.Route != client.Route { continue } if otherClient.Route != client.Route { continue }
client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID))) client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID)))
client.Send([]byte(fmt.Sprintf("pos:%d:%f:%f", otherClient.ID, otherClient.X, otherClient.Y))) client.Send([]byte(fmt.Sprintf("pos:%d:%d:%d", otherClient.ID, otherClient.X, otherClient.Y)))
} }
mutex.Unlock() mutex.Unlock()
broadcast <- CursorMessage{ broadcast <- CursorMessage{
@ -119,26 +118,15 @@ func handleClient(client *CursorClient) {
client.Route, client.Route,
[]*CursorClient{ client }, []*CursorClient{ client },
} }
case "click":
if len(args) < 2 { return }
click := 0
if args[1][0] == '1' {
click = 1
}
broadcast <- CursorMessage{
[]byte(fmt.Sprintf("click:%d:%d", client.ID, click)),
client.Route,
[]*CursorClient{ client },
}
case "pos": case "pos":
if len(args) < 3 { return } if len(args) < 3 { return }
x, err := strconv.ParseFloat(args[1], 32) x, err := strconv.ParseInt(args[1], 10, 32)
y, err := strconv.ParseFloat(args[2], 32) y, err := strconv.ParseInt(args[2], 10, 32)
if err != nil { return } if err != nil { return }
client.X = float32(x) client.X = int16(x)
client.Y = float32(y) client.Y = int16(y)
broadcast <- CursorMessage{ broadcast <- CursorMessage{
[]byte(fmt.Sprintf("pos:%d:%f:%f", client.ID, client.X, client.Y)), []byte(fmt.Sprintf("pos:%d:%d:%d", client.ID, client.X, client.Y)),
client.Route, client.Route,
[]*CursorClient{ client }, []*CursorClient{ client },
} }

View file

@ -1,14 +1,13 @@
import config from './config.js'; import config from './config.js';
const CURSOR_TICK_RATE = 1000/30;
const CURSOR_LERP_RATE = 1/100; const CURSOR_LERP_RATE = 1/100;
const CURSOR_FUNCHAR_RATE = 20; const CURSOR_FUNCHAR_RATE = 20;
const CURSOR_CHAR_MAX_LIFE = 5000; const CURSOR_CHAR_MAX_LIFE = 5000;
const CURSOR_MAX_CHARS = 64; const CURSOR_MAX_CHARS = 64;
/** @type HTMLCanvasElement */ /** @type HTMLElement */
let canvas; let cursorContainer;
/** @type CanvasRenderingContext2D */
let ctx;
/** @type Cursor */ /** @type Cursor */
let myCursor; let myCursor;
/** @type Map<number, Cursor> */ /** @type Map<number, Cursor> */
@ -20,12 +19,11 @@ let ws;
let running = false; let running = false;
let lastUpdate = 0; let lastUpdate = 0;
let cursorBoxHeight = 0;
let cursorBoxRadius = 0;
let cursorIDFontSize = 0;
let cursorCharFontSize = 0;
class Cursor { class Cursor {
/** @type HTMLElement */
#element;
/** @type HTMLElement */
#charElement;
#funCharCooldown = CURSOR_FUNCHAR_RATE; #funCharCooldown = CURSOR_FUNCHAR_RATE;
/** /**
@ -34,20 +32,46 @@ class Cursor {
* @param {number} y * @param {number} y
*/ */
constructor(id, x, y) { constructor(id, x, y) {
this.id = id;
// real coordinates (canonical) // real coordinates (canonical)
this.x = x; this.x = x;
this.y = y; this.y = y;
// render coordinates (interpolated) // render coordinates (interpolated)
this.rx = x; this.rx = x;
this.ry = y; this.ry = y;
this.msg = ''; this.msg = '';
/** @type Array<FunChar> */
this.funChars = new Array(); this.funChars = new Array();
this.colour = randomColour();
this.click = false; const element = document.createElement('i');
element.classList.add('cursor');
const colour = randomColour();
element.style.borderColor = colour;
element.style.color = colour;
cursorContainer.appendChild(element);
this.#element = element;
const char = document.createElement('i');
char.className = 'char';
cursorContainer.appendChild(char);
this.#charElement = char;
this.setID(id);
}
destroy() {
this.#element.remove();
this.#charElement.remove();
this.funChars.forEach(char => {
char.destroy();
});
}
/**
* @param {number} x
* @param {number} y
*/
move(x, y) {
this.x = x;
this.y = y;
} }
/** /**
@ -56,80 +80,64 @@ class Cursor {
update(deltaTime) { update(deltaTime) {
this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime; this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime;
this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime; this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime;
this.#element.style.left = this.rx + 'px';
this.#element.style.top = this.ry + 'px';
this.#charElement.style.left = this.rx + 'px';
this.#charElement.style.top = (this.ry - 24) + 'px';
if (this.#funCharCooldown > 0) if (this.#funCharCooldown > 0)
this.#funCharCooldown -= deltaTime; this.#funCharCooldown -= deltaTime;
const x = this.rx * innerWidth - scrollX; if (this.msg.length > 0) {
const y = this.ry * innerHeight - scrollY; if (config.cursorFunMode === true) {
const onBackground = ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--on-background');
if (config.cursorFunMode === true) {
if (this.msg.length > 0) {
if (this.#funCharCooldown <= 0) { if (this.#funCharCooldown <= 0) {
this.#funCharCooldown = CURSOR_FUNCHAR_RATE; this.#funCharCooldown = CURSOR_FUNCHAR_RATE;
if (this.funChars.length >= CURSOR_MAX_CHARS) { if (this.funChars.length >= CURSOR_MAX_CHARS) {
this.funChars.shift(); const char = this.funChars.shift();
char.destroy();
} }
const yOffset = -10 / innerHeight; const yOffset = -20;
const accelMultiplier = 0.002; const accelMultiplier = 0.002;
this.funChars.push(new FunChar( this.funChars.push(new FunChar(
this.x, this.y + yOffset, this.x + window.scrollX, this.y + window.scrollY + yOffset,
(this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier, (this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier,
this.msg)); this.msg));
} }
} else {
this.#charElement.innerText = this.msg;
} }
} else {
this.funChars.forEach(char => { this.#charElement.innerText = '';
if (char.life > CURSOR_CHAR_MAX_LIFE ||
char.y - scrollY > innerHeight ||
char.x < 0 ||
char.x * innerWidth - scrollX > innerWidth
) {
this.funChars = this.funChars.filter(c => c !== this);
return;
}
char.update(deltaTime);
});
} else if (this.msg.length > 0) {
ctx.font = 'normal bold ' + cursorCharFontSize + 'px monospace';
ctx.fillStyle = onBackground;
ctx.fillText(
this.msg,
(x + 6) * devicePixelRatio,
(y + -8) * devicePixelRatio);
} }
const lightTheme = matchMedia && matchMedia('(prefers-color-scheme: light)').matches; this.funChars.forEach(char => {
if (char.life > CURSOR_CHAR_MAX_LIFE ||
char.y > document.body.clientHeight ||
char.x < 0 ||
char.x > document.body.clientWidth
) {
this.funChars = this.funChars.filter(c => c !== this);
char.destroy();
return;
}
char.update(deltaTime);
});
}
if (lightTheme) setID(id) {
ctx.filter = 'saturate(5) brightness(0.8)'; this.id = id;
this.#element.id = 'cursor' + id;
this.#element.innerText = '0x' + id.toString(16).slice(0, 8).padStart(8, '0');
}
const idText = '0x' + this.id.toString(16).padStart(8, '0'); /**
const colour = this.click ? onBackground : this.colour; * @param {boolean} active
*/
ctx.beginPath(); click(active) {
ctx.roundRect( if (active)
(x) * devicePixelRatio, this.#element.classList.add('click');
(y) * devicePixelRatio, else
(12 + 7.2 * idText.length) * devicePixelRatio, this.#element.classList.remove('click');
cursorBoxHeight,
cursorBoxRadius);
ctx.closePath();
ctx.fillStyle = lightTheme ? '#fff8' : '#0008';
ctx.fill();
ctx.strokeStyle = colour;
ctx.lineWidth = devicePixelRatio;
ctx.stroke();
ctx.font = cursorIDFontSize + 'px monospace';
ctx.fillStyle = colour;
ctx.fillText(
idText,
(x + 6) * devicePixelRatio,
(y + 14) * devicePixelRatio);
ctx.filter = '';
} }
} }
@ -144,12 +152,20 @@ class FunChar {
constructor(x, y, xa, ya, text) { constructor(x, y, xa, ya, text) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.xa = xa + Math.random() * .0005 - .00025; this.xa = xa + Math.random() * .2 - .1;
this.ya = ya + Math.random() * -.00025; this.ya = ya + Math.random() * -.25;
this.r = this.xa * 1000; this.r = this.xa * 100;
this.ra = this.r * 0.01; this.ra = this.r * 0.01;
this.text = text;
this.life = 0; this.life = 0;
const char = document.createElement('i');
char.className = 'funchar';
char.innerText = text;
char.style.left = x + 'px';
char.style.top = y + 'px';
char.style.transform = `rotate(${this.r}deg)`;
this.element = char;
cursorContainer.appendChild(this.element);
} }
/** /**
@ -161,27 +177,15 @@ class FunChar {
this.x += this.xa * deltaTime; this.x += this.xa * deltaTime;
this.y += this.ya * deltaTime; this.y += this.ya * deltaTime;
this.r += this.ra * deltaTime; this.r += this.ra * deltaTime;
this.ya = Math.min(this.ya + 0.000001 * deltaTime, 10); this.ya = Math.min(this.ya + 0.0005 * deltaTime, 10);
const x = this.x * innerWidth - scrollX; this.element.style.left = (this.x - window.scrollX) + 'px';
const y = this.y * innerHeight - scrollY; this.element.style.top = (this.y - window.scrollY) + 'px';
this.element.style.transform = `rotate(${this.r}deg)`;
}
const translateOffset = { destroy() {
x: (x + 7.2) * devicePixelRatio, this.element.remove();
y: (y - 7.2) * devicePixelRatio,
};
ctx.translate(translateOffset.x, translateOffset.y);
ctx.rotate(this.r);
ctx.translate(-translateOffset.x, -translateOffset.y);
ctx.font = 'normal bold ' + cursorCharFontSize + 'px monospace';
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--on-background');
ctx.fillText(
this.text,
x * devicePixelRatio,
y * devicePixelRatio);
ctx.resetTransform();
} }
} }
@ -201,37 +205,18 @@ function randomColour() {
/** /**
* @param {MouseEvent} event * @param {MouseEvent} event
*/ */
let mouseMoveLock = false;
const mouseMoveCooldown = 1000/30;
function handleMouseMove(event) { function handleMouseMove(event) {
if (!myCursor) return; if (!myCursor) return;
if (ws && ws.readyState == WebSocket.OPEN)
const x = event.pageX / innerWidth; ws.send(`pos:${event.x}:${event.y}`);
const y = event.pageY / innerHeight; myCursor.move(event.x, event.y);
const f = 10000; // four digit floating-point precision
if (!mouseMoveLock) {
mouseMoveLock = true;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`pos:${Math.round(x * f) / f}:${Math.round(y * f) / f}`);
setTimeout(() => {
mouseMoveLock = false;
}, mouseMoveCooldown);
}
myCursor.x = x;
myCursor.y = y;
} }
function handleMouseDown() { function handleMouseDown() {
myCursor.click = true; myCursor.click(true);
if (ws && ws.readyState == WebSocket.OPEN)
ws.send('click:1');
} }
function handleMouseUp() { function handleMouseUp() {
myCursor.click = false; myCursor.click(false);
if (ws && ws.readyState == WebSocket.OPEN)
ws.send('click:0');
} }
/** /**
@ -253,69 +238,56 @@ function handleKeyUp() {
} }
/** /**
* @param {number} timestamp * @param {number} time
*/ */
function update(timestamp) { function updateCursors(time) {
if (!running) return; if (!running) return;
const deltaTime = timestamp - lastUpdate; const deltaTime = time - lastUpdate;
lastUpdate = timestamp;
ctx.clearRect(0, 0, canvas.width, canvas.height);
cursors.forEach(cursor => { cursors.forEach(cursor => {
cursor.update(deltaTime); cursor.update(deltaTime);
}); });
requestAnimationFrame(update); lastUpdate = time;
} requestAnimationFrame(updateCursors);
function handleWindowResize() {
canvas.width = innerWidth * devicePixelRatio;
canvas.height = innerHeight * devicePixelRatio;
cursorBoxHeight = 20 * devicePixelRatio;
cursorBoxRadius = 4 * devicePixelRatio;
cursorIDFontSize = 12 * devicePixelRatio;
cursorCharFontSize = 20 * devicePixelRatio;
} }
function cursorSetup() { function cursorSetup() {
if (running) throw new Error('Only one instance of Cursor can run at a time.'); if (running) throw new Error('Only one instance of Cursor can run at a time.');
running = true; running = true;
canvas = document.createElement('canvas'); cursorContainer = document.createElement('div');
canvas.id = 'cursors'; cursorContainer.id = 'cursors';
handleWindowResize(); document.body.appendChild(cursorContainer);
document.body.appendChild(canvas);
ctx = canvas.getContext('2d'); myCursor = new Cursor("You!", window.innerWidth / 2, window.innerHeight / 2);
myCursor = new Cursor('You!', innerWidth / 2, innerHeight / 2);
cursors.set(0, myCursor); cursors.set(0, myCursor);
addEventListener('resize', handleWindowResize);
document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mousedown', handleMouseDown); document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp); document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('keypress', handleKeyPress); document.addEventListener('keypress', handleKeyPress);
document.addEventListener('keyup', handleKeyUp); document.addEventListener('keyup', handleKeyUp);
requestAnimationFrame(update); requestAnimationFrame(updateCursors);
ws = new WebSocket('/cursor-ws'); ws = new WebSocket("/cursor-ws");
ws.addEventListener('open', () => {
console.log('Cursor connected to server successfully.');
ws.send(`loc:${location.pathname}`); ws.addEventListener("open", () => {
console.log("Cursor connected to server successfully.");
ws.send(`loc:${window.location.pathname}`);
}); });
ws.addEventListener('error', error => { ws.addEventListener("error", error => {
console.error('Cursor WebSocket error:', error); console.error("Cursor WebSocket error:", error);
}); });
ws.addEventListener('close', () => { ws.addEventListener("close", () => {
console.log('Cursor connection closed.'); console.log("Cursor connection closed.");
}); });
ws.addEventListener('message', event => {
const args = String(event.data).split(':'); ws.addEventListener("message", event => {
const args = String(event.data).split(":");
if (args.length == 0) return; if (args.length == 0) return;
let id = 0; let id = 0;
@ -328,7 +300,7 @@ function cursorSetup() {
switch (args[0]) { switch (args[0]) {
case 'id': { case 'id': {
myCursor.id = Number(args[1]); myCursor.setID(Number(args[1]));
break; break;
} }
case 'join': { case 'join': {
@ -338,6 +310,7 @@ function cursorSetup() {
} }
case 'leave': { case 'leave': {
if (!cursor || cursor === myCursor) break; if (!cursor || cursor === myCursor) break;
cursors.get(id).destroy();
cursors.delete(id); cursors.delete(id);
break; break;
} }
@ -351,37 +324,33 @@ function cursorSetup() {
cursor.msg = ''; cursor.msg = '';
break; break;
} }
case 'click': {
if (!cursor || cursor === myCursor) break;
cursor.click = args[2] == '1';
break;
}
case 'pos': { case 'pos': {
if (!cursor || cursor === myCursor) break; if (!cursor || cursor === myCursor) break;
cursor.x = Number(args[2]); cursor.move(Number(args[2]), Number(args[3]));
cursor.y = Number(args[3]);
break; break;
} }
default: { default: {
console.warn('Cursor: Unknown command received from server:', args[0]); console.warn("Cursor: Unknown command received from server:", args[0]);
break; break;
} }
} }
}); });
console.log(`Cursor tracking @ ${location.pathname}`); console.log(`Cursor tracking @ ${window.location.pathname}`);
} }
function cursorDestroy() { function cursorDestroy() {
if (!running) return; if (!running) return;
removeEventListener('resize', handleWindowResize);
document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mousedown', handleMouseDown); document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mouseup', handleMouseUp); document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('keypress', handleKeyPress); document.removeEventListener('keypress', handleKeyPress);
document.removeEventListener('keyup', handleKeyUp); document.removeEventListener('keyup', handleKeyUp);
cursors.forEach(cursor => {
cursor.destroy();
});
cursors.clear(); cursors.clear();
myCursor = null; myCursor = null;

View file

@ -1,9 +1,64 @@
canvas#cursors { #cursors i.cursor {
position: fixed;
padding: 4px;
display: block;
z-index: 1000;
background: #0008;
border: 2px solid #808080;
border-radius: 2px;
font-style: normal;
font-size: 10px;
font-weight: bold;
white-space: nowrap;
}
#cursors i.cursor.click {
color: var(--on-background) !important;
border-color: var(--on-background) !important;
}
#cursors i.char {
position: absolute;
margin: 0;
font-style: normal;
font-size: 20px;
font-weight: bold;
color: var(--on-background);
}
#cursors i.funchar {
position: absolute;
margin: 0;
display: block;
z-index: 1000;
font-style: normal;
font-size: 20px;
font-weight: bold;
color: var(--on-background);
}
#cursors {
width: 100vw;
height: 100vh;
position: fixed; position: fixed;
top: 0; top: 0;
left: 0; left: 0;
width: 100vw;
height: 100vh; z-index: 1000;
overflow: clip;
user-select: none;
pointer-events: none; pointer-events: none;
z-index: 100; }
@media (prefers-color-scheme: light) {
#cursors i.cursor {
filter: saturate(5) brightness(0.8);
background: #fff8;
}
} }