Compare commits
No commits in common. "3f3164bc153a70df2bd6352fb514a62646f7cc1c" and "0fc6c9f86d6b1b74ead9179d4cd0fd4961b68711" have entirely different histories.
3f3164bc15
...
0fc6c9f86d
13 changed files with 35 additions and 758 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -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
|
|
||||||
|
|
12
Makefile
12
Makefile
|
@ -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
9
bundle.sh
Executable 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/
|
189
cursor/cursor.go
189
cursor/cursor.go
|
@ -1,189 +0,0 @@
|
||||||
package cursor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"arimelody-web/model"
|
|
||||||
"fmt"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CursorClient struct {
|
|
||||||
ID int32
|
|
||||||
Conn *websocket.Conn
|
|
||||||
Route string
|
|
||||||
X int16
|
|
||||||
Y int16
|
|
||||||
Disconnected bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type CursorMessage struct {
|
|
||||||
Data []byte
|
|
||||||
Route string
|
|
||||||
Exclude []*CursorClient
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *CursorClient) Send(data []byte) {
|
|
||||||
err := client.Conn.WriteMessage(websocket.TextMessage, data)
|
|
||||||
if err != nil {
|
|
||||||
client.Disconnect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (client *CursorClient) Disconnect() {
|
|
||||||
client.Disconnected = true
|
|
||||||
broadcast <- CursorMessage{
|
|
||||||
[]byte(fmt.Sprintf("leave:%d", client.ID)),
|
|
||||||
client.Route,
|
|
||||||
[]*CursorClient{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var clients = make(map[int32]*CursorClient)
|
|
||||||
var broadcast = make(chan CursorMessage)
|
|
||||||
var mutex = &sync.Mutex{}
|
|
||||||
|
|
||||||
func StartCursor(app *model.AppState) {
|
|
||||||
var includes = func (clients []*CursorClient, client *CursorClient) bool {
|
|
||||||
for _, c := range clients {
|
|
||||||
if c.ID == client.ID { return true }
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
log("Cursor message handler ready!")
|
|
||||||
|
|
||||||
for {
|
|
||||||
message := <-broadcast
|
|
||||||
mutex.Lock()
|
|
||||||
for _, client := range clients {
|
|
||||||
if client.Route != message.Route { continue }
|
|
||||||
if includes(message.Exclude, client) { continue }
|
|
||||||
client.Send(message.Data)
|
|
||||||
}
|
|
||||||
mutex.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleClient(client *CursorClient) {
|
|
||||||
msgType, message, err := client.Conn.ReadMessage()
|
|
||||||
if err != nil {
|
|
||||||
client.Disconnect()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if msgType != websocket.TextMessage { return }
|
|
||||||
|
|
||||||
args := strings.Split(string(message), ":")
|
|
||||||
if len(args) == 0 { return }
|
|
||||||
switch args[0] {
|
|
||||||
case "loc":
|
|
||||||
if len(args) < 2 { return }
|
|
||||||
|
|
||||||
client.Route = args[1]
|
|
||||||
|
|
||||||
mutex.Lock()
|
|
||||||
for _, otherClient := range clients {
|
|
||||||
if otherClient.ID == client.ID { continue }
|
|
||||||
if otherClient.Route != client.Route { continue }
|
|
||||||
client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID)))
|
|
||||||
client.Send([]byte(fmt.Sprintf("pos:%d:%d:%d", otherClient.ID, otherClient.X, otherClient.Y)))
|
|
||||||
}
|
|
||||||
mutex.Unlock()
|
|
||||||
broadcast <- CursorMessage{
|
|
||||||
[]byte(fmt.Sprintf("join:%d", client.ID)),
|
|
||||||
client.Route,
|
|
||||||
[]*CursorClient{ client },
|
|
||||||
}
|
|
||||||
case "char":
|
|
||||||
if len(args) < 2 { return }
|
|
||||||
// haha, turns out using ':' as a separator means you can't type ':'s
|
|
||||||
// i should really be writing byte packets, not this nonsense
|
|
||||||
msg := byte(':')
|
|
||||||
if len(args[1]) > 0 {
|
|
||||||
msg = args[1][0]
|
|
||||||
}
|
|
||||||
broadcast <- CursorMessage{
|
|
||||||
[]byte(fmt.Sprintf("char:%d:%c", client.ID, msg)),
|
|
||||||
client.Route,
|
|
||||||
[]*CursorClient{ client },
|
|
||||||
}
|
|
||||||
case "nochar":
|
|
||||||
broadcast <- CursorMessage{
|
|
||||||
[]byte(fmt.Sprintf("nochar:%d", client.ID)),
|
|
||||||
client.Route,
|
|
||||||
[]*CursorClient{ client },
|
|
||||||
}
|
|
||||||
case "pos":
|
|
||||||
if len(args) < 3 { return }
|
|
||||||
x, err := strconv.ParseInt(args[1], 10, 32)
|
|
||||||
y, err := strconv.ParseInt(args[2], 10, 32)
|
|
||||||
if err != nil { return }
|
|
||||||
client.X = int16(x)
|
|
||||||
client.Y = int16(y)
|
|
||||||
broadcast <- CursorMessage{
|
|
||||||
[]byte(fmt.Sprintf("pos:%d:%d:%d", client.ID, client.X, client.Y)),
|
|
||||||
client.Route,
|
|
||||||
[]*CursorClient{ client },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Handler(app *model.AppState) http.HandlerFunc {
|
|
||||||
var upgrader = websocket.Upgrader{
|
|
||||||
CheckOrigin: func (r *http.Request) bool {
|
|
||||||
origin := r.Header.Get("Origin")
|
|
||||||
return origin == app.Config.BaseUrl
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
conn, err := upgrader.Upgrade(w, r, nil)
|
|
||||||
if err != nil {
|
|
||||||
log("Failed to upgrade to WebSocket connection: %v\n", err)
|
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
client := CursorClient{
|
|
||||||
ID: rand.Int31(),
|
|
||||||
Conn: conn,
|
|
||||||
X: 0.0,
|
|
||||||
Y: 0.0,
|
|
||||||
Disconnected: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
err = client.Conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("id:%d", client.ID)))
|
|
||||||
if err != nil {
|
|
||||||
client.Conn.Close()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
mutex.Lock()
|
|
||||||
clients[client.ID] = &client
|
|
||||||
mutex.Unlock()
|
|
||||||
|
|
||||||
// log("Client connected: %s (%s)", fmt.Sprintf("0x%08x", client.ID), client.Conn.RemoteAddr().String())
|
|
||||||
|
|
||||||
for {
|
|
||||||
if client.Disconnected {
|
|
||||||
mutex.Lock()
|
|
||||||
delete(clients, client.ID)
|
|
||||||
client.Conn.Close()
|
|
||||||
mutex.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
handleClient(&client)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func log(format string, args ...any) {
|
|
||||||
logString := fmt.Sprintf(format, args...)
|
|
||||||
fmt.Printf("[%s] [CURSOR] %s\n", time.Now().Format(time.UnixDate), logString)
|
|
||||||
}
|
|
1
go.mod
1
go.mod
|
@ -10,7 +10,6 @@ require (
|
||||||
require golang.org/x/crypto v0.27.0 // indirect
|
require golang.org/x/crypto v0.27.0 // indirect
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/gorilla/websocket v1.5.3 // indirect
|
|
||||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
|
||||||
)
|
)
|
||||||
|
|
2
go.sum
2
go.sum
|
@ -2,8 +2,6 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
|
||||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
|
|
|
@ -30,7 +30,6 @@ const (
|
||||||
TYPE_ARTWORK string = "artwork"
|
TYPE_ARTWORK string = "artwork"
|
||||||
TYPE_FILES string = "files"
|
TYPE_FILES string = "files"
|
||||||
TYPE_MISC string = "misc"
|
TYPE_MISC string = "misc"
|
||||||
TYPE_CURSOR string = "cursor"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type LogLevel int
|
type LogLevel int
|
||||||
|
|
16
main.go
16
main.go
|
@ -1,13 +1,11 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
stdLog "log"
|
stdLog "log"
|
||||||
"math"
|
"math"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
@ -19,10 +17,9 @@ import (
|
||||||
"arimelody-web/api"
|
"arimelody-web/api"
|
||||||
"arimelody-web/colour"
|
"arimelody-web/colour"
|
||||||
"arimelody-web/controller"
|
"arimelody-web/controller"
|
||||||
"arimelody-web/cursor"
|
|
||||||
"arimelody-web/log"
|
|
||||||
"arimelody-web/model"
|
"arimelody-web/model"
|
||||||
"arimelody-web/templates"
|
"arimelody-web/templates"
|
||||||
|
"arimelody-web/log"
|
||||||
"arimelody-web/view"
|
"arimelody-web/view"
|
||||||
|
|
||||||
"github.com/jmoiron/sqlx"
|
"github.com/jmoiron/sqlx"
|
||||||
|
@ -431,8 +428,6 @@ func main() {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
go cursor.StartCursor(&app)
|
|
||||||
|
|
||||||
// start the web server!
|
// start the web server!
|
||||||
mux := createServeMux(&app)
|
mux := createServeMux(&app)
|
||||||
fmt.Printf("Now serving at http://%s:%d\n", app.Config.Host, app.Config.Port)
|
fmt.Printf("Now serving at http://%s:%d\n", app.Config.Host, app.Config.Port)
|
||||||
|
@ -449,7 +444,6 @@ func createServeMux(app *model.AppState) *http.ServeMux {
|
||||||
mux.Handle("/api/", http.StripPrefix("/api", api.Handler(app)))
|
mux.Handle("/api/", http.StripPrefix("/api", api.Handler(app)))
|
||||||
mux.Handle("/music/", http.StripPrefix("/music", view.MusicHandler(app)))
|
mux.Handle("/music/", http.StripPrefix("/music", view.MusicHandler(app)))
|
||||||
mux.Handle("/uploads/", http.StripPrefix("/uploads", staticHandler(filepath.Join(app.Config.DataDirectory, "uploads"))))
|
mux.Handle("/uploads/", http.StripPrefix("/uploads", staticHandler(filepath.Join(app.Config.DataDirectory, "uploads"))))
|
||||||
mux.Handle("/cursor-ws", cursor.Handler(app))
|
|
||||||
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == http.MethodHead {
|
if r.Method == http.MethodHead {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
|
@ -542,14 +536,6 @@ type LoggingResponseWriter struct {
|
||||||
Status int
|
Status int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
|
||||||
hijack, ok := lrw.ResponseWriter.(http.Hijacker)
|
|
||||||
if !ok {
|
|
||||||
return nil, nil, errors.New("Server does not support hijacking\n")
|
|
||||||
}
|
|
||||||
return hijack.Hijack()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lrw *LoggingResponseWriter) WriteHeader(status int) {
|
func (lrw *LoggingResponseWriter) WriteHeader(status int) {
|
||||||
lrw.Status = status
|
lrw.Status = status
|
||||||
lrw.ResponseWriter.WriteHeader(status)
|
lrw.ResponseWriter.WriteHeader(status)
|
||||||
|
|
|
@ -1,107 +1,33 @@
|
||||||
const ARIMELODY_CONFIG_NAME = "arimelody.me-config";
|
const DEFAULT_CONFIG = {
|
||||||
|
crt: false
|
||||||
class Config {
|
};
|
||||||
_crt = false;
|
|
||||||
_cursor = false;
|
|
||||||
_cursorFunMode = false;
|
|
||||||
|
|
||||||
/** @type Map<string, Array<Function>> */
|
|
||||||
#listeners = new Map();
|
|
||||||
|
|
||||||
constructor(values) {
|
|
||||||
function thisOrElse(values, name, defaultValue) {
|
|
||||||
if (values === null) return defaultValue;
|
|
||||||
if (values[name] === undefined) return defaultValue;
|
|
||||||
return values[name];
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#listeners.set('crt', new Array());
|
|
||||||
this.crt = thisOrElse(values, 'crt', false);
|
|
||||||
this.#listeners.set('cursor', new Array());
|
|
||||||
this.cursor = thisOrElse(values, 'cursor', false);
|
|
||||||
this.#listeners.set('cursorFunMode', new Array());
|
|
||||||
this.cursorFunMode = thisOrElse(values, 'cursorFunMode', false);
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Appends a listener function to be called when the config value of `name`
|
|
||||||
* is changed.
|
|
||||||
*/
|
|
||||||
addListener(name, callback) {
|
|
||||||
const callbacks = this.#listeners.get(name);
|
|
||||||
if (!callbacks) return;
|
|
||||||
callbacks.push(callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes the listener function `callback` from the list of callbacks when
|
|
||||||
* the config value of `name` is changed.
|
|
||||||
*/
|
|
||||||
removeListener(name, callback) {
|
|
||||||
const callbacks = this.#listeners.get(name);
|
|
||||||
if (!callbacks) return;
|
|
||||||
callbacks.set(name, callbacks.filter(c => c !== callback));
|
|
||||||
}
|
|
||||||
|
|
||||||
save() {
|
|
||||||
localStorage.setItem(ARIMELODY_CONFIG_NAME, JSON.stringify({
|
|
||||||
crt: this.crt,
|
|
||||||
cursor: this.cursor,
|
|
||||||
cursorFunMode: this.cursorFunMode
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
get crt() { return this._crt }
|
|
||||||
set crt(/** @type boolean */ enabled) {
|
|
||||||
this._crt = enabled;
|
|
||||||
|
|
||||||
if (enabled) {
|
|
||||||
document.body.classList.add("crt");
|
|
||||||
} else {
|
|
||||||
document.body.classList.remove("crt");
|
|
||||||
}
|
|
||||||
document.getElementById('toggle-crt').className = enabled ? "" : "disabled";
|
|
||||||
|
|
||||||
this.#listeners.get('crt').forEach(callback => {
|
|
||||||
callback(this._crt);
|
|
||||||
})
|
|
||||||
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
get cursor() { return this._cursor }
|
|
||||||
set cursor(/** @type boolean */ value) {
|
|
||||||
this._cursor = value;
|
|
||||||
this.#listeners.get('cursor').forEach(callback => {
|
|
||||||
callback(this._cursor);
|
|
||||||
})
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
|
|
||||||
get cursorFunMode() { return this._cursorFunMode }
|
|
||||||
set cursorFunMode(/** @type boolean */ value) {
|
|
||||||
this._cursorFunMode = value;
|
|
||||||
this.#listeners.get('cursorFunMode').forEach(callback => {
|
|
||||||
callback(this._cursorFunMode);
|
|
||||||
})
|
|
||||||
this.save();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = (() => {
|
const config = (() => {
|
||||||
let values = null;
|
let saved = localStorage.getItem("config");
|
||||||
|
if (saved) {
|
||||||
|
const config = JSON.parse(saved);
|
||||||
|
setCRT(config.crt || DEFAULT_CONFIG.crt);
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
const saved = localStorage.getItem(ARIMELODY_CONFIG_NAME);
|
localStorage.setItem("config", JSON.stringify(DEFAULT_CONFIG));
|
||||||
if (saved)
|
return DEFAULT_CONFIG;
|
||||||
values = JSON.parse(saved);
|
|
||||||
|
|
||||||
return new Config(values);
|
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
function saveConfig() {
|
||||||
|
localStorage.setItem("config", JSON.stringify(config));
|
||||||
|
}
|
||||||
|
|
||||||
document.getElementById("toggle-crt").addEventListener("click", () => {
|
document.getElementById("toggle-crt").addEventListener("click", () => {
|
||||||
config.crt = !config.crt;
|
config.crt = !config.crt;
|
||||||
|
setCRT(config.crt);
|
||||||
|
saveConfig();
|
||||||
});
|
});
|
||||||
|
|
||||||
window.config = config;
|
function setCRT(/** @type boolean */ enabled) {
|
||||||
export default config;
|
if (enabled) {
|
||||||
|
document.body.classList.add("crt");
|
||||||
|
} else {
|
||||||
|
document.body.classList.remove("crt");
|
||||||
|
}
|
||||||
|
document.getElementById('toggle-crt').className = enabled ? "" : "disabled";
|
||||||
|
}
|
||||||
|
|
|
@ -1,372 +0,0 @@
|
||||||
import config from './config.js';
|
|
||||||
|
|
||||||
const CURSOR_TICK_RATE = 1000/30;
|
|
||||||
const CURSOR_LERP_RATE = 1/100;
|
|
||||||
const CURSOR_FUNCHAR_RATE = 20;
|
|
||||||
const CURSOR_CHAR_MAX_LIFE = 5000;
|
|
||||||
const CURSOR_MAX_CHARS = 64;
|
|
||||||
|
|
||||||
/** @type HTMLElement */
|
|
||||||
let cursorContainer;
|
|
||||||
/** @type Cursor */
|
|
||||||
let myCursor;
|
|
||||||
/** @type Map<number, Cursor> */
|
|
||||||
let cursors = new Map();
|
|
||||||
|
|
||||||
/** @type WebSocket */
|
|
||||||
let ws;
|
|
||||||
|
|
||||||
let running = false;
|
|
||||||
let lastUpdate = 0;
|
|
||||||
|
|
||||||
class Cursor {
|
|
||||||
/** @type HTMLElement */
|
|
||||||
#element;
|
|
||||||
/** @type HTMLElement */
|
|
||||||
#charElement;
|
|
||||||
#funCharCooldown = CURSOR_FUNCHAR_RATE;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} id
|
|
||||||
* @param {number} x
|
|
||||||
* @param {number} y
|
|
||||||
*/
|
|
||||||
constructor(id, x, y) {
|
|
||||||
// real coordinates (canonical)
|
|
||||||
this.x = x;
|
|
||||||
this.y = y;
|
|
||||||
// render coordinates (interpolated)
|
|
||||||
this.rx = x;
|
|
||||||
this.ry = y;
|
|
||||||
this.msg = '';
|
|
||||||
this.funChars = new Array();
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {number} deltaTime
|
|
||||||
*/
|
|
||||||
update(deltaTime) {
|
|
||||||
this.rx += (this.x - this.rx) * 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)
|
|
||||||
this.#funCharCooldown -= deltaTime;
|
|
||||||
|
|
||||||
if (this.msg.length > 0) {
|
|
||||||
if (config.cursorFunMode === true) {
|
|
||||||
if (this.#funCharCooldown <= 0) {
|
|
||||||
this.#funCharCooldown = CURSOR_FUNCHAR_RATE;
|
|
||||||
if (this.funChars.length >= CURSOR_MAX_CHARS) {
|
|
||||||
const char = this.funChars.shift();
|
|
||||||
char.destroy();
|
|
||||||
}
|
|
||||||
const yOffset = -20;
|
|
||||||
const accelMultiplier = 0.002;
|
|
||||||
this.funChars.push(new FunChar(
|
|
||||||
this.x + window.scrollX, this.y + window.scrollY + yOffset,
|
|
||||||
(this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier,
|
|
||||||
this.msg));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.#charElement.innerText = this.msg;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.#charElement.innerText = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
setID(id) {
|
|
||||||
this.id = id;
|
|
||||||
this.#element.id = 'cursor' + id;
|
|
||||||
this.#element.innerText = '0x' + id.toString(16).slice(0, 8).padStart(8, '0');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {boolean} active
|
|
||||||
*/
|
|
||||||
click(active) {
|
|
||||||
if (active)
|
|
||||||
this.#element.classList.add('click');
|
|
||||||
else
|
|
||||||
this.#element.classList.remove('click');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class FunChar {
|
|
||||||
/**
|
|
||||||
* @param {number} x
|
|
||||||
* @param {number} y
|
|
||||||
* @param {number} xa
|
|
||||||
* @param {number} ya
|
|
||||||
* @param {string} text
|
|
||||||
*/
|
|
||||||
constructor(x, y, xa, ya, text) {
|
|
||||||
this.x = x;
|
|
||||||
this.y = y;
|
|
||||||
this.xa = xa + Math.random() * .2 - .1;
|
|
||||||
this.ya = ya + Math.random() * -.25;
|
|
||||||
this.r = this.xa * 100;
|
|
||||||
this.ra = this.r * 0.01;
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {number} deltaTime
|
|
||||||
*/
|
|
||||||
update(deltaTime) {
|
|
||||||
this.life += deltaTime;
|
|
||||||
|
|
||||||
this.x += this.xa * deltaTime;
|
|
||||||
this.y += this.ya * deltaTime;
|
|
||||||
this.r += this.ra * deltaTime;
|
|
||||||
this.ya = Math.min(this.ya + 0.0005 * deltaTime, 10);
|
|
||||||
|
|
||||||
this.element.style.left = (this.x - window.scrollX) + 'px';
|
|
||||||
this.element.style.top = (this.y - window.scrollY) + 'px';
|
|
||||||
this.element.style.transform = `rotate(${this.r}deg)`;
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy() {
|
|
||||||
this.element.remove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @returns string
|
|
||||||
*/
|
|
||||||
function randomColour() {
|
|
||||||
const min = 128;
|
|
||||||
const range = 100;
|
|
||||||
const red = Math.round((min + Math.random() * range)).toString(16);
|
|
||||||
const green = Math.round((min + Math.random() * range)).toString(16);
|
|
||||||
const blue = Math.round((min + Math.random() * range)).toString(16);
|
|
||||||
|
|
||||||
return '#' + red + green + blue;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {MouseEvent} event
|
|
||||||
*/
|
|
||||||
function handleMouseMove(event) {
|
|
||||||
if (!myCursor) return;
|
|
||||||
if (ws && ws.readyState == WebSocket.OPEN)
|
|
||||||
ws.send(`pos:${event.x}:${event.y}`);
|
|
||||||
myCursor.move(event.x, event.y);
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleMouseDown() {
|
|
||||||
myCursor.click(true);
|
|
||||||
}
|
|
||||||
function handleMouseUp() {
|
|
||||||
myCursor.click(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {KeyboardEvent} event
|
|
||||||
*/
|
|
||||||
function handleKeyPress(event) {
|
|
||||||
if (event.key.length > 1) return;
|
|
||||||
if (event.metaKey || event.ctrlKey) return;
|
|
||||||
if (myCursor.msg === event.key) return;
|
|
||||||
if (ws && ws.readyState == WebSocket.OPEN)
|
|
||||||
ws.send(`char:${event.key}`);
|
|
||||||
myCursor.msg = event.key;
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleKeyUp() {
|
|
||||||
if (ws && ws.readyState == WebSocket.OPEN)
|
|
||||||
ws.send(`nochar`);
|
|
||||||
myCursor.msg = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {number} time
|
|
||||||
*/
|
|
||||||
function updateCursors(time) {
|
|
||||||
if (!running) return;
|
|
||||||
|
|
||||||
const deltaTime = time - lastUpdate;
|
|
||||||
|
|
||||||
cursors.forEach(cursor => {
|
|
||||||
cursor.update(deltaTime);
|
|
||||||
});
|
|
||||||
|
|
||||||
lastUpdate = time;
|
|
||||||
requestAnimationFrame(updateCursors);
|
|
||||||
}
|
|
||||||
|
|
||||||
function cursorSetup() {
|
|
||||||
if (running) throw new Error('Only one instance of Cursor can run at a time.');
|
|
||||||
running = true;
|
|
||||||
|
|
||||||
cursorContainer = document.createElement('div');
|
|
||||||
cursorContainer.id = 'cursors';
|
|
||||||
document.body.appendChild(cursorContainer);
|
|
||||||
|
|
||||||
myCursor = new Cursor("You!", window.innerWidth / 2, window.innerHeight / 2);
|
|
||||||
cursors.set(0, myCursor);
|
|
||||||
|
|
||||||
document.addEventListener('mousemove', handleMouseMove);
|
|
||||||
document.addEventListener('mousedown', handleMouseDown);
|
|
||||||
document.addEventListener('mouseup', handleMouseUp);
|
|
||||||
document.addEventListener('keypress', handleKeyPress);
|
|
||||||
document.addEventListener('keyup', handleKeyUp);
|
|
||||||
|
|
||||||
requestAnimationFrame(updateCursors);
|
|
||||||
|
|
||||||
ws = new WebSocket("/cursor-ws");
|
|
||||||
|
|
||||||
ws.addEventListener("open", () => {
|
|
||||||
console.log("Cursor connected to server successfully.");
|
|
||||||
|
|
||||||
ws.send(`loc:${window.location.pathname}`);
|
|
||||||
});
|
|
||||||
ws.addEventListener("error", error => {
|
|
||||||
console.error("Cursor WebSocket error:", error);
|
|
||||||
});
|
|
||||||
ws.addEventListener("close", () => {
|
|
||||||
console.log("Cursor connection closed.");
|
|
||||||
});
|
|
||||||
|
|
||||||
ws.addEventListener("message", event => {
|
|
||||||
const args = String(event.data).split(":");
|
|
||||||
if (args.length == 0) return;
|
|
||||||
|
|
||||||
let id = 0;
|
|
||||||
/** @type Cursor */
|
|
||||||
let cursor;
|
|
||||||
if (args.length > 1) {
|
|
||||||
id = Number(args[1]);
|
|
||||||
cursor = cursors.get(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (args[0]) {
|
|
||||||
case 'id': {
|
|
||||||
myCursor.setID(Number(args[1]));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'join': {
|
|
||||||
if (id === myCursor.id) break;
|
|
||||||
cursors.set(id, new Cursor(id, 0, 0));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'leave': {
|
|
||||||
if (!cursor || cursor === myCursor) break;
|
|
||||||
cursors.get(id).destroy();
|
|
||||||
cursors.delete(id);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'char': {
|
|
||||||
if (!cursor || cursor === myCursor) break;
|
|
||||||
cursor.msg = args[2];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'nochar': {
|
|
||||||
if (!cursor || cursor === myCursor) break;
|
|
||||||
cursor.msg = '';
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'pos': {
|
|
||||||
if (!cursor || cursor === myCursor) break;
|
|
||||||
cursor.move(Number(args[2]), Number(args[3]));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default: {
|
|
||||||
console.warn("Cursor: Unknown command received from server:", args[0]);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`Cursor tracking @ ${window.location.pathname}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function cursorDestroy() {
|
|
||||||
if (!running) return;
|
|
||||||
|
|
||||||
document.removeEventListener('mousemove', handleMouseMove);
|
|
||||||
document.removeEventListener('mousedown', handleMouseDown);
|
|
||||||
document.removeEventListener('mouseup', handleMouseUp);
|
|
||||||
document.removeEventListener('keypress', handleKeyPress);
|
|
||||||
document.removeEventListener('keyup', handleKeyUp);
|
|
||||||
|
|
||||||
cursors.forEach(cursor => {
|
|
||||||
cursor.destroy();
|
|
||||||
});
|
|
||||||
cursors.clear();
|
|
||||||
myCursor = null;
|
|
||||||
|
|
||||||
cursorContainer.remove();
|
|
||||||
|
|
||||||
console.log(`Cursor no longer tracking.`);
|
|
||||||
running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.cursor === true) {
|
|
||||||
cursorSetup();
|
|
||||||
}
|
|
||||||
|
|
||||||
config.addListener('cursor', enabled => {
|
|
||||||
if (enabled === true)
|
|
||||||
cursorSetup();
|
|
||||||
else
|
|
||||||
cursorDestroy();
|
|
||||||
});
|
|
|
@ -1,6 +1,5 @@
|
||||||
import "./header.js";
|
import "./header.js";
|
||||||
import "./config.js";
|
import "./config.js";
|
||||||
import "./cursor.js";
|
|
||||||
|
|
||||||
function type_out(e) {
|
function type_out(e) {
|
||||||
const text = e.innerText;
|
const text = e.innerText;
|
||||||
|
|
|
@ -1,64 +0,0 @@
|
||||||
#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;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
|
|
||||||
z-index: 1000;
|
|
||||||
overflow: clip;
|
|
||||||
|
|
||||||
user-select: none;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: light) {
|
|
||||||
#cursors i.cursor {
|
|
||||||
filter: saturate(5) brightness(0.8);
|
|
||||||
background: #fff8;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -2,7 +2,6 @@
|
||||||
@import url("/style/header.css");
|
@import url("/style/header.css");
|
||||||
@import url("/style/footer.css");
|
@import url("/style/footer.css");
|
||||||
@import url("/style/prideflag.css");
|
@import url("/style/prideflag.css");
|
||||||
@import url("/style/cursor.css");
|
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "Monaspace Argon";
|
font-family: "Monaspace Argon";
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue