Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Enhance environment configuration and add Mapbox support (#616)

Bill Yangcb57738a47b6
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 40d861ce2..3649cd676 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -40,7 +40,8 @@
"WebSearch",
"WebFetch(domain:umami.is)",
"WebFetch(domain:posthog.com)",
- "WebFetch(domain:rybbit.io)"
+ "WebFetch(domain:rybbit.io)",
+ "WebFetch(domain:docs.mapbox.com)"
]
},
"enableAllProjectMcpServers": false
diff --git a/client/Dockerfile b/client/Dockerfile
index 9ee00c04b..bd5907b89 100644
--- a/client/Dockerfile
+++ b/client/Dockerfile
@@ -28,9 +28,11 @@ ENV NEXT_TELEMETRY_DISABLED=1
ARG NEXT_PUBLIC_BACKEND_URL
ARG NEXT_PUBLIC_DISABLE_SIGNUP
ARG NEXT_PUBLIC_CLOUD
+ARG NEXT_PUBLIC_MAPBOX_TOKEN
ENV NEXT_PUBLIC_BACKEND_URL=${NEXT_PUBLIC_BACKEND_URL}
ENV NEXT_PUBLIC_DISABLE_SIGNUP=${NEXT_PUBLIC_DISABLE_SIGNUP}
ENV NEXT_PUBLIC_CLOUD=${NEXT_PUBLIC_CLOUD}
+ENV NEXT_PUBLIC_MAPBOX_TOKEN=${NEXT_PUBLIC_MAPBOX_TOKEN}
WORKDIR /app/client
RUN npm run build
diff --git a/client/package-lock.json b/client/package-lock.json
index 44477a372..4b3d2eb30 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -58,6 +58,7 @@
"lodash": "4.17.21",
"lucide-react": "0.510.0",
"luxon": "3.6.1",
+ "mapbox-gl": "^3.15.0",
"next": "15.3.2",
"next-themes": "0.4.6",
"react": "19.1.0",
@@ -74,6 +75,7 @@
"tailwind-merge": "2.6.0",
"tailwindcss-animate": "1.0.7",
"three": "0.176.0",
+ "unique-names-generator": "^4.7.1",
"zod": "3.24.4",
"zustand": "5.0.4"
},
@@ -83,6 +85,7 @@
"@types/leaflet": "1.9.17",
"@types/lodash": "4.17.16",
"@types/luxon": "3.6.2",
+ "@types/mapbox-gl": "^3.4.1",
"@types/node": "^20.14.8",
"@types/react": "19",
"knip": "^5.60.2",
@@ -1525,6 +1528,58 @@
"integrity": "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==",
"license": "MIT"
},
+ "node_modules/@mapbox/jsonlint-lines-primitives": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz",
+ "integrity": "sha512-rY0o9A5ECsTQRVhv7tL/OyDpGAoUB4tTvLiW1DSzQGq4bvTPhNw1VpSNjDJc5GFZ2XuyOtSWSVN05qOtcD71qQ==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/@mapbox/mapbox-gl-supported": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/mapbox-gl-supported/-/mapbox-gl-supported-3.0.0.tgz",
+ "integrity": "sha512-2XghOwu16ZwPJLOFVuIOaLbN0iKMn867evzXFyf0P22dqugezfJwLmdanAgU25ITvz1TvOfVP4jsDImlDJzcWg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@mapbox/point-geometry": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz",
+ "integrity": "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==",
+ "license": "ISC"
+ },
+ "node_modules/@mapbox/tiny-sdf": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.0.7.tgz",
+ "integrity": "sha512-25gQLQMcpivjOSA40g3gO6qgiFPDpWRoMfd+G/GoppPIeP6JDaMMkMrEJnMZhKyyS6iKwVt5YKu02vCUyJM3Ug==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/@mapbox/unitbezier": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz",
+ "integrity": "sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/@mapbox/vector-tile": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-2.0.4.tgz",
+ "integrity": "sha512-AkOLcbgGTdXScosBWwmmD7cDlvOjkg/DetGva26pIRiZPdeJYjYKarIlb4uxVzi6bwHO6EWH82eZ5Nuv4T5DUg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@mapbox/point-geometry": "~1.1.0",
+ "@types/geojson": "^7946.0.16",
+ "pbf": "^4.0.1"
+ }
+ },
+ "node_modules/@mapbox/whoots-js": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz",
+ "integrity": "sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.11.tgz",
@@ -6497,6 +6552,15 @@
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
+ "node_modules/@types/geojson-vt": {
+ "version": "3.2.5",
+ "resolved": "https://registry.npmjs.org/@types/geojson-vt/-/geojson-vt-3.2.5.tgz",
+ "integrity": "sha512-qDO7wqtprzlpe8FfQ//ClPV9xiuoh2nkIgiouIptON9w5jvD/fA4szvP9GBlDVdJ5dldAl0kX/sy3URbWwLx0g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
"node_modules/@types/leaflet": {
"version": "1.9.17",
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.17.tgz",
@@ -6521,6 +6585,22 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/mapbox__point-geometry": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/@types/mapbox__point-geometry/-/mapbox__point-geometry-0.1.4.tgz",
+ "integrity": "sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/mapbox-gl": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmjs.org/@types/mapbox-gl/-/mapbox-gl-3.4.1.tgz",
+ "integrity": "sha512-NsGKKtgW93B+UaLPti6B7NwlxYlES5DpV5Gzj9F75rK5ALKsqSk15CiEHbOnTr09RGbr6ZYiCdI+59NNNcAImg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
"node_modules/@types/node": {
"version": "20.14.8",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.8.tgz",
@@ -6536,6 +6616,12 @@
"integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==",
"license": "MIT"
},
+ "node_modules/@types/pbf": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/pbf/-/pbf-3.0.5.tgz",
+ "integrity": "sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA==",
+ "license": "MIT"
+ },
"node_modules/@types/react": {
"version": "19.1.4",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.4.tgz",
@@ -6570,6 +6656,15 @@
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
"license": "MIT"
},
+ "node_modules/@types/supercluster": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/@types/supercluster/-/supercluster-7.1.3.tgz",
+ "integrity": "sha512-Z0pOY34GDFl3Q6hUFYf3HkTwKEE02e7QgtJppBt+beEAxnyOpJua+voGFvxINBHa06GwLFFym7gRPY2SiKIfIA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
"node_modules/@types/three": {
"version": "0.176.0",
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.176.0.tgz",
@@ -6957,6 +7052,12 @@
],
"license": "CC-BY-4.0"
},
+ "node_modules/cheap-ruler": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/cheap-ruler/-/cheap-ruler-4.0.0.tgz",
+ "integrity": "sha512-0BJa8f4t141BYKQyn9NSQt1PguFQXMXwZiA5shfoaBYHAb2fFk2RAX+tiWMoQU+Agtzt3mdt0JtuyshAXqZ+Vw==",
+ "license": "ISC"
+ },
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -7144,6 +7245,12 @@
"node": ">= 8"
}
},
+ "node_modules/csscolorparser": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/csscolorparser/-/csscolorparser-1.0.3.tgz",
+ "integrity": "sha512-umPSgYwZkdFoUrH5hIq5kf0wPSXiro51nPw0j2K/c83KflkPSTBGMz6NJvMB+07VlL0y7VPo6QJcDjcgKTTm3w==",
+ "license": "MIT"
+ },
"node_modules/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
@@ -8124,6 +8231,12 @@
"node": ">= 0.10"
}
},
+ "node_modules/geojson-vt": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/geojson-vt/-/geojson-vt-4.0.2.tgz",
+ "integrity": "sha512-AV9ROqlNqoZEIJGfm1ncNjEXfkz2hdFlZf0qkVfmkwdKa8vj7H16YUOT81rJw1rdFhyEDlN2Tds91p/glzbl5A==",
+ "license": "ISC"
+ },
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -8180,6 +8293,12 @@
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
+ "node_modules/gl-matrix": {
+ "version": "3.4.4",
+ "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz",
+ "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==",
+ "license": "MIT"
+ },
"node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
@@ -8230,6 +8349,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/grid-index": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/grid-index/-/grid-index-1.1.0.tgz",
+ "integrity": "sha512-HZRwumpOGUrHyxO5bqKZL0B0GlUpwtCAzZ42sgxUPniu33R1LSFH5yrIcBCHjkctCAh3mtWKcKd9J4vDDdeVHA==",
+ "license": "ISC"
+ },
"node_modules/h3-js": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/h3-js/-/h3-js-4.2.1.tgz",
@@ -8550,6 +8675,12 @@
"node": ">=12"
}
},
+ "node_modules/kdbush": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.0.2.tgz",
+ "integrity": "sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA==",
+ "license": "ISC"
+ },
"node_modules/kleur": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
@@ -8711,6 +8842,68 @@
"node": ">=12"
}
},
+ "node_modules/mapbox-gl": {
+ "version": "3.15.0",
+ "resolved": "https://registry.npmjs.org/mapbox-gl/-/mapbox-gl-3.15.0.tgz",
+ "integrity": "sha512-I42ffZpiXwt0PG3PO6gMYQnoz+AInkirLe/+zoHjcfBTFoFkKYtu5gFwT1WGeSvNrVTqG2Bwp9zUjPw0PFGY+w==",
+ "license": "SEE LICENSE IN LICENSE.txt",
+ "workspaces": [
+ "src/style-spec",
+ "test/build/typings"
+ ],
+ "dependencies": {
+ "@mapbox/jsonlint-lines-primitives": "^2.0.2",
+ "@mapbox/mapbox-gl-supported": "^3.0.0",
+ "@mapbox/point-geometry": "^1.1.0",
+ "@mapbox/tiny-sdf": "^2.0.6",
+ "@mapbox/unitbezier": "^0.0.1",
+ "@mapbox/vector-tile": "^2.0.4",
+ "@mapbox/whoots-js": "^3.1.0",
+ "@types/geojson": "^7946.0.16",
+ "@types/geojson-vt": "^3.2.5",
+ "@types/mapbox__point-geometry": "^0.1.4",
+ "@types/pbf": "^3.0.5",
+ "@types/supercluster": "^7.1.3",
+ "cheap-ruler": "^4.0.0",
+ "csscolorparser": "~1.0.3",
+ "earcut": "^3.0.1",
+ "geojson-vt": "^4.0.2",
+ "gl-matrix": "^3.4.4",
+ "grid-index": "^1.1.0",
+ "kdbush": "^4.0.2",
+ "martinez-polygon-clipping": "^0.7.4",
+ "murmurhash-js": "^1.0.0",
+ "pbf": "^4.0.1",
+ "potpack": "^2.0.0",
+ "quickselect": "^3.0.0",
+ "serialize-to-js": "^3.1.2",
+ "supercluster": "^8.0.1",
+ "tinyqueue": "^3.0.0"
+ }
+ },
+ "node_modules/martinez-polygon-clipping": {
+ "version": "0.7.4",
+ "resolved": "https://registry.npmjs.org/martinez-polygon-clipping/-/martinez-polygon-clipping-0.7.4.tgz",
+ "integrity": "sha512-jBEwrKtA0jTagUZj2bnmb4Yg2s4KnJGRePStgI7bAVjtcipKiF39R4LZ2V/UT61jMYWrTcBhPazexeqd6JAVtw==",
+ "license": "MIT",
+ "dependencies": {
+ "robust-predicates": "^2.0.4",
+ "splaytree": "^0.1.4",
+ "tinyqueue": "^1.2.0"
+ }
+ },
+ "node_modules/martinez-polygon-clipping/node_modules/robust-predicates": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-2.0.4.tgz",
+ "integrity": "sha512-l4NwboJM74Ilm4VKfbAtFeGq7aEjWL+5kVFcmgFA2MrdnQWx9iE/tUGvxY5HyMI7o/WpSIUFLbC5fbeaHgSCYg==",
+ "license": "Unlicense"
+ },
+ "node_modules/martinez-polygon-clipping/node_modules/tinyqueue": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/tinyqueue/-/tinyqueue-1.2.3.tgz",
+ "integrity": "sha512-Qz9RgWuO9l8lT+Y9xvbzhPT2efIUIFd69N7eF7tJ9lnQl0iLj1M7peK7IoUGZL9DJHw9XftqLreccfxcQgYLxA==",
+ "license": "ISC"
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -8829,6 +9022,12 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
+ "node_modules/murmurhash-js": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/murmurhash-js/-/murmurhash-js-1.0.0.tgz",
+ "integrity": "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==",
+ "license": "MIT"
+ },
"node_modules/mz": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
@@ -9111,6 +9310,18 @@
"node": ">=8"
}
},
+ "node_modules/pbf": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/pbf/-/pbf-4.0.1.tgz",
+ "integrity": "sha512-SuLdBvS42z33m8ejRbInMapQe8n0D3vN/Xd5fmWM3tufNgRQFBpaW2YVJxQZV4iPNqb0vEFvssMEo5w9c6BTIA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "resolve-protobuf-schema": "^2.1.0"
+ },
+ "bin": {
+ "pbf": "bin/pbf"
+ }
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -9325,6 +9536,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/potpack": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/potpack/-/potpack-2.1.0.tgz",
+ "integrity": "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==",
+ "license": "ISC"
+ },
"node_modules/preact": {
"version": "10.26.6",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.26.6.tgz",
@@ -9362,6 +9579,12 @@
"react-is": "^16.13.1"
}
},
+ "node_modules/protocol-buffers-schema": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.0.tgz",
+ "integrity": "sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw==",
+ "license": "MIT"
+ },
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
@@ -9406,6 +9629,12 @@
],
"license": "MIT"
},
+ "node_modules/quickselect": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",
+ "integrity": "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==",
+ "license": "ISC"
+ },
"node_modules/radix-ui": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.4.2.tgz",
@@ -10472,6 +10701,15 @@
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
}
},
+ "node_modules/resolve-protobuf-schema": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
+ "integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "protocol-buffers-schema": "^3.3.1"
+ }
+ },
"node_modules/reusify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
@@ -10576,6 +10814,15 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
+ "node_modules/serialize-to-js": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/serialize-to-js/-/serialize-to-js-3.1.2.tgz",
+ "integrity": "sha512-owllqNuDDEimQat7EPG0tH7JjO090xKNzUtYz6X+Sk2BXDnOCilDdNLwjWeFywG9xkJul1ULvtUQa9O4pUaY0w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
"node_modules/set-cookie-parser": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
@@ -10727,6 +10974,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/splaytree": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/splaytree/-/splaytree-0.1.4.tgz",
+ "integrity": "sha512-D50hKrjZgBzqD3FT2Ek53f2dcDLAQT8SSGrzj3vidNH5ISRgceeGVJ2dQIthKOuayqFXfFjXheHNo4bbt9LhRQ==",
+ "license": "MIT"
+ },
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
@@ -10914,6 +11167,15 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/supercluster": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/supercluster/-/supercluster-8.0.1.tgz",
+ "integrity": "sha512-IiOea5kJ9iqzD2t7QJq/cREyLHTtSmUT6gQsweojg9WH2sYJqZK9SswTu6jrscO6D1G5v5vYZ9ru/eq85lXeZQ==",
+ "license": "ISC",
+ "dependencies": {
+ "kdbush": "^4.0.2"
+ }
+ },
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
@@ -11198,6 +11460,12 @@
"integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==",
"license": "MIT"
},
+ "node_modules/tinyqueue": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/tinyqueue/-/tinyqueue-3.0.0.tgz",
+ "integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==",
+ "license": "ISC"
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -11267,6 +11535,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/unique-names-generator": {
+ "version": "4.7.1",
+ "resolved": "https://registry.npmjs.org/unique-names-generator/-/unique-names-generator-4.7.1.tgz",
+ "integrity": "sha512-lMx9dX+KRmG8sq6gulYYpKWZc9RlGsgBR6aoO8Qsm3qvkSJ+3rAymr+TnV8EDMrIrwuFJ4kruzMWM/OpYzPoow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/unplugin": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.1.0.tgz",
diff --git a/client/package.json b/client/package.json
index 66fa153e9..4fa45ba42 100644
--- a/client/package.json
+++ b/client/package.json
@@ -62,6 +62,7 @@
"lodash": "4.17.21",
"lucide-react": "0.510.0",
"luxon": "3.6.1",
+ "mapbox-gl": "^3.15.0",
"next": "15.3.2",
"next-themes": "0.4.6",
"react": "19.1.0",
@@ -78,6 +79,7 @@
"tailwind-merge": "2.6.0",
"tailwindcss-animate": "1.0.7",
"three": "0.176.0",
+ "unique-names-generator": "^4.7.1",
"zod": "3.24.4",
"zustand": "5.0.4"
},
@@ -87,6 +89,7 @@
"@types/leaflet": "1.9.17",
"@types/lodash": "4.17.16",
"@types/luxon": "3.6.2",
+ "@types/mapbox-gl": "^3.4.1",
"@types/node": "^20.14.8",
"@types/react": "19",
"knip": "^5.60.2",
diff --git a/client/src/api/analytics/useGetLiveSessionLocations.ts b/client/src/api/analytics/useGetLiveSessionLocations.ts
deleted file mode 100644
index b87e93be4..000000000
--- a/client/src/api/analytics/useGetLiveSessionLocations.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { authedFetch } from "../utils";
-
-export type LiveSessionLocation = {
- lat: number;
- lon: number;
- count: number;
- city: string;
-};
-
-export function useGetLiveSessionLocations(minutes = 5) {
- const { site } = useStore();
- return useQuery<LiveSessionLocation[]>({
- queryKey: ["live-session-locations", site, minutes],
- queryFn: () =>
- authedFetch(`/live-session-locations/${site}`, {
- time: minutes,
- }).then((res: any) => res.data),
- });
-}
diff --git a/client/src/api/analytics/useGetSessionLocations.ts b/client/src/api/analytics/useGetSessionLocations.ts
new file mode 100644
index 000000000..60d9879e1
--- /dev/null
+++ b/client/src/api/analytics/useGetSessionLocations.ts
@@ -0,0 +1,32 @@
+import { useQuery } from "@tanstack/react-query";
+import { useStore } from "../../lib/store";
+import { authedFetch, getQueryParams } from "../utils";
+
+export type LiveSessionLocation = {
+ lat: number;
+ lon: number;
+ count: number;
+ city: string;
+};
+
+export function useGetSessionLocations() {
+ const { time, site, filters } = useStore();
+ return useQuery<LiveSessionLocation[]>({
+ queryKey: ["session-locations", site, time, filters],
+ queryFn: () => {
+ const queryParams = {
+ ...getQueryParams(time),
+ filters: filters.filter(
+ f =>
+ f.parameter !== "lat" &&
+ f.parameter !== "lon" &&
+ f.parameter !== "city" &&
+ f.parameter !== "country" &&
+ f.parameter !== "region"
+ ),
+ };
+
+ return authedFetch(`/session-locations/${site}`, queryParams).then((res: any) => res.data);
+ },
+ });
+}
diff --git a/client/src/app/[site]/components/Header/Header.tsx b/client/src/app/[site]/components/Header/Header.tsx
index b62262330..1fffcc8f0 100644
--- a/client/src/app/[site]/components/Header/Header.tsx
+++ b/client/src/app/[site]/components/Header/Header.tsx
@@ -1,5 +1,6 @@
"use client";
+import { usePathname } from "next/navigation";
import { FreePlanBanner } from "../../../../components/FreePlanBanner";
import { userStore } from "../../../../lib/userStore";
import { DemoSignupBanner } from "./DemoSignupBanner";
@@ -8,10 +9,11 @@ import { UsageBanners } from "./UsageBanners";
export function Header() {
const { user } = userStore();
+ const pathname = usePathname();
return (
<div className="flex flex-col">
- {user && (
+ {user && !pathname.includes("/globe") && (
<div className="flex flex-col px-2 md:px-4">
<DemoSignupBanner />
<FreePlanBanner />
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
index 0ae722a7c..66d6bacee 100644
--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx
+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
@@ -6,6 +6,7 @@ import {
File,
Funnel,
Gauge,
+ Globe,
LayoutDashboard,
Map,
MousePointerClick,
@@ -70,6 +71,12 @@ function SidebarContent() {
href={getTabPath("map")}
icon={<Map className="w-4 h-4" />}
/>
+ <SidebarComponents.Item
+ label="Globe"
+ active={isActiveTab("globe")}
+ href={getTabPath("globe")}
+ icon={<Globe className="w-4 h-4" />}
+ />
{IS_CLOUD && (
<SidebarComponents.Item
label="Pages"
diff --git a/client/src/app/[site]/components/shared/Filters/utils.ts b/client/src/app/[site]/components/shared/Filters/utils.ts
index aa6dc24c6..8dd1ce19e 100644
--- a/client/src/app/[site]/components/shared/Filters/utils.ts
+++ b/client/src/app/[site]/components/shared/Filters/utils.ts
@@ -51,6 +51,10 @@ export function getParameterNameLabel(parameter: FilterParameter) {
return "OS Version";
case "user_id":
return "User ID";
+ case "lat":
+ return "Lat";
+ case "lon":
+ return "Lon";
default:
return parameter;
}
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
new file mode 100644
index 000000000..7a50cbd2c
--- /dev/null
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -0,0 +1,196 @@
+import { ArrowRight, ChevronDown, ChevronUp, ExternalLink, FileText, MousePointerClick } from "lucide-react";
+import { DateTime } from "luxon";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { animals, colors, uniqueNamesGenerator } from "unique-names-generator";
+import { useCurrentSite } from "../../../../api/admin/sites";
+import { GetSessionsResponse, useGetSessionsInfinite } from "../../../../api/analytics/userSessions";
+import { Channel } from "../../../../components/Channel";
+import {
+ BrowserTooltipIcon,
+ CountryFlagTooltipIcon,
+ DeviceTypeTooltipIcon,
+ OperatingSystemTooltipIcon,
+} from "../../../../components/TooltipIcons/TooltipIcons";
+import { Badge } from "../../../../components/ui/badge";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
+import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";
+import { cn, formatter } from "../../../../lib/utils";
+import { Button } from "../../../../components/ui/button";
+
+// Function to truncate path for display
+function truncatePath(path: string, maxLength: number = 32) {
+ if (!path) return "-";
+ if (path.length <= maxLength) return path;
+
+ // Keep the beginning of the path with ellipsis
+ return `${path.substring(0, maxLength)}...`;
+}
+
+function SessionCardSkeleton() {
+ return (
+ <div className="rounded-lg bg-neutral-850 border border-neutral-800 overflow-hidden p-2 space-y-2 animate-pulse">
+ <div className="flex justify-between border-b border-neutral-700 pb-2">
+ <div className="flex items-center gap-2">
+ <div className="h-4 w-24 bg-neutral-700 rounded" />
+ <div className="h-4 w-4 bg-neutral-700 rounded" />
+ </div>
+ <div className="flex items-center gap-1.5">
+ <div className="h-3 w-20 bg-neutral-700 rounded" />
+ <div className="h-3 w-1 bg-neutral-700 rounded" />
+ <div className="h-3 w-10 bg-neutral-700 rounded hidden md:block" />
+ </div>
+ </div>
+ <div className="flex space-x-2 items-center">
+ <div className="h-6 w-6 bg-neutral-700 rounded" />
+ <div className="h-6 w-6 bg-neutral-700 rounded" />
+ <div className="h-6 w-6 bg-neutral-700 rounded" />
+ <div className="h-6 w-6 bg-neutral-700 rounded" />
+ <div className="h-6 w-16 bg-neutral-700 rounded" />
+ <div className="h-6 w-16 bg-neutral-700 rounded" />
+ <div className="h-6 w-20 bg-neutral-700 rounded" />
+ </div>
+ <div className="items-center flex-1 min-w-0 hidden md:flex gap-2">
+ <div className="h-3 w-32 bg-neutral-700 rounded" />
+ <div className="h-3 w-3 bg-neutral-700 rounded" />
+ <div className="h-3 w-32 bg-neutral-700 rounded" />
+ </div>
+ </div>
+ );
+}
+
+function SessionCard({ session }: { session: GetSessionsResponse[number] }) {
+ // Calculate session duration in minutes
+ const start = DateTime.fromSQL(session.session_start);
+ const end = DateTime.fromSQL(session.session_end);
+ const totalSeconds = Math.floor(end.diff(start).milliseconds / 1000);
+ const duration = formatShortDuration(totalSeconds);
+ const siteId = useCurrentSite();
+
+ const name = uniqueNamesGenerator({
+ dictionaries: [colors, animals],
+ separator: " ",
+ style: "capital",
+ seed: session.user_id,
+ });
+
+ return (
+ <div className="rounded-lg bg-neutral-850 border border-neutral-800 overflow-hidden p-2 space-y-2">
+ <div className="flex justify-between border-b border-neutral-700 pb-2">
+ <div className="text-sm text-neutral-100 flex items-center gap-2">
+ {name}{" "}
+ <Link href={`/${siteId.site?.id}/user/${session.user_id}`}>
+ <ExternalLink className="w-4 h-4 text-gray-400" />
+ </Link>
+ </div>
+ <div className="flex space-x-2 items-center pr-2">
+ <div className="flex items-center gap-1.5 text-xs text-gray-300">
+ <span className="text-gray-400">
+ {DateTime.fromSQL(session.session_start, {
+ zone: "utc",
+ })
+ .setLocale(userLocale)
+ .toLocal()
+ .toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
+ </span>
+ <span className="text-gray-400">•</span>
+ <span className="hidden md:block">{duration}</span>
+ </div>
+ </div>
+ </div>
+ <div className="flex space-x-2 items-center">
+ {session.country && (
+ <CountryFlagTooltipIcon country={session.country} city={session.city} region={session.region} />
+ )}
+ <BrowserTooltipIcon browser={session.browser || "Unknown"} browser_version={session.browser_version} />
+ <OperatingSystemTooltipIcon
+ operating_system={session.operating_system || ""}
+ operating_system_version={session.operating_system_version}
+ />
+ <DeviceTypeTooltipIcon
+ device_type={session.device_type || ""}
+ screen_width={session.screen_width}
+ screen_height={session.screen_height}
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge className="flex items-center gap-1 bg-neutral-800 text-gray-300">
+ <FileText className="w-4 h-4 text-blue-500" />
+ <span>{formatter(session.pageviews)}</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>Pageviews</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge className="flex items-center gap-1 bg-neutral-800 text-gray-300">
+ <MousePointerClick className="w-4 h-4 text-amber-500" />
+ <span>{formatter(session.events)}</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>Events</TooltipContent>
+ </Tooltip>
+ <Channel channel={session.channel} referrer={session.referrer} />
+ </div>
+ <div className="items-center flex-1 min-w-0 hidden md:flex">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-xs text-gray-400 truncate max-w-[200px] inline-block">
+ {truncatePath(session.entry_page)}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{session.entry_page || "-"}</p>
+ </TooltipContent>
+ </Tooltip>
+
+ <ArrowRight className="mx-2 w-3 h-3 flex-shrink-0 text-gray-400" />
+
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-xs text-gray-400 truncate max-w-[200px] inline-block">
+ {truncatePath(session.exit_page)}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{session.exit_page || "-"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ );
+}
+
+export function GlobeSessions() {
+ const { data, isLoading, error, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite();
+
+ const [expanded, setExpanded] = useState(false);
+
+ // Combine all pages of data
+ const flattenedData = useMemo(() => {
+ if (!data) return [];
+ return data.pages.flatMap(page => page.data || []);
+ }, [data]);
+
+ return (
+ <div className="space-y-2 bg-neutral-900 p-2 rounded-lg w-[371px]">
+ <div className="text-sm text-neutral-300 font-medium flex items-center justify-between">
+ SESSIONS
+ <Button variant="ghost" size="smIcon" onClick={() => setExpanded(!expanded)}>
+ {expanded ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />}
+ </Button>
+ </div>
+ <div className={cn("space-y-2 overflow-y-auto", expanded ? "max-h-[calc(100vh-210px)]" : "max-h-[210px]")}>
+ {isLoading ? (
+ <>
+ <SessionCardSkeleton />
+ <SessionCardSkeleton />
+ <SessionCardSkeleton />
+ </>
+ ) : (
+ flattenedData.map(session => <SessionCard key={session.session_id} session={session} />)
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/globe/components/ModeSelector.tsx b/client/src/app/[site]/globe/components/ModeSelector.tsx
new file mode 100644
index 000000000..0e3679302
--- /dev/null
+++ b/client/src/app/[site]/globe/components/ModeSelector.tsx
@@ -0,0 +1,39 @@
+import { Globe2, HouseIcon, Radio } from "lucide-react";
+
+import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { useGlobeStore } from "../globeStore";
+
+export type MapView = "countries" | "subdivisions" | "coordinates";
+
+export default function MapViewSelector() {
+ const { mapView, setMapView } = useGlobeStore();
+
+ const mapViewToTab: Record<MapView, string> = {
+ coordinates: "tab-1",
+ countries: "tab-2",
+ subdivisions: "tab-3",
+ };
+
+ return (
+ <Tabs value={mapViewToTab[mapView]}>
+ <ScrollArea>
+ <TabsList className="mb-3">
+ <TabsTrigger value="tab-1" className="group" onClick={() => setMapView("coordinates")}>
+ <Radio className="-ms-0.5 me-1.5 opacity-60" size={16} aria-hidden="true" />
+ Coordinates
+ </TabsTrigger>
+ <TabsTrigger value="tab-2" onClick={() => setMapView("countries")}>
+ <Globe2 className="-ms-0.5 me-1.5 opacity-60" size={16} aria-hidden="true" />
+ Countries
+ </TabsTrigger>
+ <TabsTrigger value="tab-3" className="group" onClick={() => setMapView("subdivisions")}>
+ <HouseIcon className="-ms-0.5 me-1.5 opacity-60" size={16} aria-hidden="true" />
+ Subdivisions
+ </TabsTrigger>
+ </TabsList>
+ <ScrollBar orientation="horizontal" />
+ </ScrollArea>
+ </Tabs>
+ );
+}
diff --git a/client/src/app/[site]/globe/globeStore.ts b/client/src/app/[site]/globe/globeStore.ts
new file mode 100644
index 000000000..67bfc934c
--- /dev/null
+++ b/client/src/app/[site]/globe/globeStore.ts
@@ -0,0 +1,32 @@
+import { create } from "zustand";
+import { MapView } from "./components/ModeSelector";
+
+interface TooltipContent {
+ name: string;
+ code: string;
+ count: number;
+ percentage: number;
+}
+
+interface TooltipPosition {
+ x: number;
+ y: number;
+}
+
+interface GlobeStore {
+ tooltipContent: TooltipContent | null;
+ tooltipPosition: TooltipPosition;
+ mapView: MapView;
+ setTooltipContent: (content: TooltipContent | null) => void;
+ setTooltipPosition: (position: TooltipPosition) => void;
+ setMapView: (view: MapView) => void;
+}
+
+export const useGlobeStore = create<GlobeStore>(set => ({
+ tooltipContent: null,
+ tooltipPosition: { x: 0, y: 0 },
+ mapView: "coordinates",
+ setTooltipContent: content => set({ tooltipContent: content }),
+ setTooltipPosition: position => set({ tooltipPosition: position }),
+ setMapView: view => set({ mapView: view }),
+}));
diff --git a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
new file mode 100644
index 000000000..1a5727f83
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
@@ -0,0 +1,175 @@
+import { useEffect } from "react";
+import mapboxgl from "mapbox-gl";
+import { scaleSequentialSqrt } from "d3-scale";
+import { interpolateYlOrRd } from "d3-scale-chromatic";
+import { LiveSessionLocation } from "../../../../api/analytics/useGetSessionLocations";
+import { addFilter } from "../../../../lib/store";
+import { FilterParameter } from "@rybbit/shared/dist/filters";
+import { round } from "lodash";
+
+const getSizeMultiplier = (total: number) => {
+ if (total <= 50) return 3; // Large dots
+ if (total <= 200) return 2; // Medium dots
+ if (total <= 500) return 1.5; // Small-medium dots
+ return 1; // Small dots
+};
+
+export function useCoordinatesLayer({
+ map,
+ liveSessionLocations,
+ mapLoaded,
+ minutes,
+ setTooltipContent,
+ mapView,
+}: {
+ map: React.RefObject<mapboxgl.Map | null>;
+ liveSessionLocations: LiveSessionLocation[] | undefined;
+ mapLoaded: boolean;
+ minutes: number;
+ setTooltipContent: (content: any) => void;
+ mapView: string;
+}) {
+ useEffect(() => {
+ if (!map.current || !liveSessionLocations || !mapLoaded) return;
+
+ const addCoordinatesLayer = () => {
+ if (!map.current) return;
+
+ const highest = liveSessionLocations.reduce((acc, curr) => Math.max(acc, curr.count), 0) || 1;
+ const normalized = 5 / Number(minutes);
+ const weightColor = scaleSequentialSqrt(interpolateYlOrRd).domain([0, highest * normalized * 15]);
+ const singleColor = weightColor(0); // Use the start color for all hexbins
+
+ // Calculate size scale based on total number of locations
+ const totalLocations = liveSessionLocations.length;
+
+ const sizeMultiplier = getSizeMultiplier(totalLocations);
+
+ // Create GeoJSON points from live session locations
+ const geojsonData: GeoJSON.FeatureCollection<GeoJSON.Point> = {
+ type: "FeatureCollection",
+ features: liveSessionLocations.map(location => ({
+ type: "Feature",
+ geometry: {
+ type: "Point",
+ coordinates: [location.lon, location.lat],
+ },
+ properties: {
+ count: location.count,
+ city: location.city,
+ },
+ })),
+ };
+
+ // Add or update source
+ if (map.current.getSource("realtime-coordinates")) {
+ (map.current.getSource("realtime-coordinates") as mapboxgl.GeoJSONSource).setData(geojsonData);
+ } else {
+ map.current.addSource("realtime-coordinates", {
+ type: "geojson",
+ data: geojsonData,
+ });
+
+ // Add hexbin layer (using circle layer for simplicity, can be enhanced with custom hexbin implementation)
+ map.current.addLayer({
+ id: "realtime-coordinates-layer",
+ type: "circle",
+ source: "realtime-coordinates",
+ paint: {
+ "circle-radius": [
+ "interpolate",
+ ["exponential", 2],
+ ["zoom"],
+ 0,
+ ["interpolate", ["linear"], ["get", "count"], 1, 1 * sizeMultiplier, highest, 3 * sizeMultiplier],
+ 5,
+ ["interpolate", ["linear"], ["get", "count"], 1, 3 * sizeMultiplier, highest, 7 * sizeMultiplier],
+ 10,
+ ["interpolate", ["linear"], ["get", "count"], 1, 7 * sizeMultiplier, highest, 15 * sizeMultiplier],
+ 15,
+ ["interpolate", ["linear"], ["get", "count"], 1, 15 * sizeMultiplier, highest, 30 * sizeMultiplier],
+ ],
+ // "circle-radius": [
+ // "interpolate",
+ // ["exponential", 2],
+ // ["zoom"],
+ // 0,
+ // ["interpolate", ["linear"], ["get", "count"], 1, 1 * sizeMultiplier, highest, 3 * sizeMultiplier],
+ // 5,
+ // ["interpolate", ["linear"], ["get", "count"], 1, 2 * sizeMultiplier, highest, 5 * sizeMultiplier],
+ // 10,
+ // ["interpolate", ["linear"], ["get", "count"], 1, 4 * sizeMultiplier, highest, 10 * sizeMultiplier],
+ // 15,
+ // ["interpolate", ["linear"], ["get", "count"], 1, 8 * sizeMultiplier, highest, 20 * sizeMultiplier],
+ // ],
+ "circle-color": singleColor,
+ "circle-opacity": 0.7,
+ "circle-stroke-width": 1,
+ "circle-stroke-color": "#fff",
+ "circle-stroke-opacity": 0.3,
+ },
+ layout: {
+ visibility: mapView === "coordinates" ? "visible" : "none",
+ },
+ });
+
+ // Add mouse events for tooltip and popover
+ map.current.on("mouseenter", "realtime-coordinates-layer", () => {
+ if (!map.current) return;
+ map.current.getCanvas().style.cursor = "pointer";
+ });
+
+ map.current.on("mousemove", "realtime-coordinates-layer", e => {
+ if (!map.current || !e.features || e.features.length === 0) return;
+
+ const feature = e.features[0];
+ const city = feature.properties?.city || "Unknown";
+ const count = feature.properties?.count || 0;
+
+ setTooltipContent({
+ name: city,
+ code: "",
+ count,
+ percentage: 0,
+ });
+ });
+
+ map.current.on("mouseleave", "realtime-coordinates-layer", () => {
+ if (!map.current) return;
+ map.current.getCanvas().style.cursor = "";
+ setTooltipContent(null);
+ });
+
+ map.current.on("click", "realtime-coordinates-layer", e => {
+ if (!map.current || !e.features || e.features.length === 0) return;
+
+ const feature = e.features[0];
+ const city = feature.properties?.city || "Unknown";
+ const count = feature.properties?.count || 0;
+
+ // Get the feature's coordinates
+ const coordinates = (feature.geometry as any).coordinates.slice().map((c: number) => round(c, 4));
+
+ addFilter({
+ parameter: "lat" as FilterParameter,
+ value: [coordinates[1]],
+ type: "equals",
+ });
+
+ addFilter({
+ parameter: "lon" as FilterParameter,
+ value: [coordinates[0]],
+ type: "equals",
+ });
+ });
+ }
+
+ // Update colors when data changes
+ if (map.current.getLayer("realtime-coordinates-layer")) {
+ map.current.setPaintProperty("realtime-coordinates-layer", "circle-color", singleColor);
+ }
+ };
+
+ addCoordinatesLayer();
+ }, [liveSessionLocations, mapLoaded, map, minutes, setTooltipContent]);
+}
diff --git a/client/src/app/[site]/globe/hooks/useCountriesLayer.ts b/client/src/app/[site]/globe/hooks/useCountriesLayer.ts
new file mode 100644
index 000000000..daf253102
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useCountriesLayer.ts
@@ -0,0 +1,122 @@
+import { useEffect } from "react";
+import mapboxgl from "mapbox-gl";
+import { FilterParameter } from "@rybbit/shared";
+import { addFilter } from "../../../../lib/store";
+
+interface UseCountriesLayerProps {
+ map: React.RefObject<mapboxgl.Map | null>;
+ countriesGeoData: any;
+ processedCountryData: any;
+ colorScale: (value: number) => string;
+ countryData: any;
+ setTooltipContent: (content: any) => void;
+ mapLoaded: boolean;
+ mapView: string;
+}
+
+export function useCountriesLayer({
+ map,
+ countriesGeoData,
+ processedCountryData,
+ colorScale,
+ countryData,
+ setTooltipContent,
+ mapLoaded,
+ mapView,
+}: UseCountriesLayerProps) {
+ useEffect(() => {
+ if (!map.current || !countriesGeoData || !processedCountryData || !mapLoaded) return;
+
+ const addCountriesLayer = () => {
+ if (!map.current) return;
+
+ const geoDataCopy = JSON.parse(JSON.stringify(countriesGeoData));
+ geoDataCopy.features.forEach((feature: any) => {
+ const code = feature.properties?.ISO_A2;
+ const foundData = processedCountryData.find((d: any) => d.value === code);
+ const count = foundData?.count || 0;
+ const color = count > 0 ? colorScale(count) : "rgba(140, 140, 140, 0.5)";
+ feature.properties.fillColor = color;
+ feature.properties.count = count;
+ });
+
+ if (map.current.getSource("countries")) {
+ (map.current.getSource("countries") as mapboxgl.GeoJSONSource).setData(geoDataCopy);
+ } else {
+ map.current.addSource("countries", {
+ type: "geojson",
+ data: geoDataCopy,
+ });
+
+ map.current.addLayer({
+ id: "countries-fill",
+ type: "fill",
+ source: "countries",
+ paint: {
+ "fill-color": ["get", "fillColor"],
+ "fill-opacity": 0.6,
+ },
+ layout: {
+ visibility: mapView === "countries" ? "visible" : "none",
+ },
+ });
+
+ map.current.addLayer({
+ id: "countries-outline",
+ type: "line",
+ source: "countries",
+ paint: {
+ "line-color": "#ffffff",
+ "line-width": 0.5,
+ "line-opacity": 0.3,
+ },
+ layout: {
+ visibility: mapView === "countries" ? "visible" : "none",
+ },
+ });
+
+ map.current.on("mousemove", "countries-fill", (e) => {
+ if (!map.current || !e.features || e.features.length === 0) return;
+ map.current.getCanvas().style.cursor = "pointer";
+
+ const feature = e.features[0];
+ const code = feature.properties?.ISO_A2;
+ const name = feature.properties?.ADMIN;
+ const count = feature.properties?.count || 0;
+
+ const currentData = countryData?.data;
+ const foundData = currentData?.find((d: any) => d.value === code);
+ const percentage = foundData?.percentage || 0;
+
+ setTooltipContent({
+ name,
+ code,
+ count,
+ percentage,
+ });
+ });
+
+ map.current.on("mouseleave", "countries-fill", () => {
+ if (!map.current) return;
+ map.current.getCanvas().style.cursor = "";
+ setTooltipContent(null);
+ });
+
+ map.current.on("click", "countries-fill", (e) => {
+ if (!e.features || e.features.length === 0) return;
+
+ const feature = e.features[0];
+ const code = feature.properties?.ISO_A2;
+
+ addFilter({
+ parameter: "country" as FilterParameter,
+ value: [code],
+ type: "equals",
+ });
+ });
+ }
+ };
+
+ addCountriesLayer();
+ }, [countriesGeoData, processedCountryData, colorScale, map, countryData, setTooltipContent, mapLoaded]);
+}
diff --git a/client/src/app/[site]/globe/hooks/useLayerVisibility.ts b/client/src/app/[site]/globe/hooks/useLayerVisibility.ts
new file mode 100644
index 000000000..aab3982ea
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useLayerVisibility.ts
@@ -0,0 +1,49 @@
+import { useEffect } from "react";
+import mapboxgl from "mapbox-gl";
+import { MapView } from "../components/ModeSelector";
+
+export function useLayerVisibility(
+ map: React.RefObject<mapboxgl.Map | null>,
+ mapView: MapView,
+ mapLoaded: boolean
+) {
+ useEffect(() => {
+ if (!map.current || !mapLoaded) return;
+
+ if (map.current.getLayer("countries-fill")) {
+ map.current.setLayoutProperty(
+ "countries-fill",
+ "visibility",
+ mapView === "countries" ? "visible" : "none"
+ );
+ }
+ if (map.current.getLayer("countries-outline")) {
+ map.current.setLayoutProperty(
+ "countries-outline",
+ "visibility",
+ mapView === "countries" ? "visible" : "none"
+ );
+ }
+ if (map.current.getLayer("subdivisions-fill")) {
+ map.current.setLayoutProperty(
+ "subdivisions-fill",
+ "visibility",
+ mapView === "subdivisions" ? "visible" : "none"
+ );
+ }
+ if (map.current.getLayer("subdivisions-outline")) {
+ map.current.setLayoutProperty(
+ "subdivisions-outline",
+ "visibility",
+ mapView === "subdivisions" ? "visible" : "none"
+ );
+ }
+ if (map.current.getLayer("realtime-coordinates-layer")) {
+ map.current.setLayoutProperty(
+ "realtime-coordinates-layer",
+ "visibility",
+ mapView === "coordinates" ? "visible" : "none"
+ );
+ }
+ }, [mapView, mapLoaded, map]);
+}
diff --git a/client/src/app/[site]/globe/hooks/useMapbox.ts b/client/src/app/[site]/globe/hooks/useMapbox.ts
new file mode 100644
index 000000000..c7525adb8
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useMapbox.ts
@@ -0,0 +1,53 @@
+import { useEffect, useRef, useState } from "react";
+import mapboxgl from "mapbox-gl";
+
+export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>) {
+ const map = useRef<mapboxgl.Map | null>(null);
+ const [mapLoaded, setMapLoaded] = useState(false);
+
+ useEffect(() => {
+ if (!containerRef.current) return;
+
+ mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN || "";
+
+ map.current = new mapboxgl.Map({
+ container: containerRef.current,
+ // style: "mapbox://styles/mapbox/standard",
+ style: "mapbox://styles/mapbox/dark-v11",
+ projection: { name: "globe" },
+ zoom: 1.5,
+ center: [0, 20],
+ pitch: 0,
+ bearing: 0,
+ antialias: true,
+ attributionControl: false,
+ });
+
+ map.current.on("style.load", () => {
+ if (!map.current) return;
+
+ // Customize land color
+ // map.current.setPaintProperty("land", "background-color", "#1a365d"); // dark blue
+
+ // Customize water/ocean color
+ map.current.setPaintProperty("water", "fill-color", "#0a1929"); // darker blue
+
+ map.current.setFog({
+ color: "rgb(61, 76, 89)",
+ "high-color": "rgb(36, 92, 223)",
+ "horizon-blend": 0.0,
+ "space-color": "rgb(12, 12, 16)",
+ "star-intensity": 0.6,
+ });
+
+ setMapLoaded(true);
+ });
+
+ return () => {
+ map.current?.remove();
+ map.current = null;
+ };
+ }, [containerRef]);
+
+ return { map, mapLoaded };
+}
diff --git a/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts b/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
new file mode 100644
index 000000000..f110d596b
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
@@ -0,0 +1,122 @@
+import { useEffect } from "react";
+import mapboxgl from "mapbox-gl";
+import { FilterParameter } from "@rybbit/shared";
+import { addFilter } from "../../../../lib/store";
+
+interface UseSubdivisionsLayerProps {
+ map: React.RefObject<mapboxgl.Map | null>;
+ subdivisionsGeoData: any;
+ processedSubdivisionData: any;
+ colorScale: (value: number) => string;
+ subdivisionData: any;
+ setTooltipContent: (content: any) => void;
+ mapLoaded: boolean;
+ mapView: string;
+}
+
+export function useSubdivisionsLayer({
+ map,
+ subdivisionsGeoData,
+ processedSubdivisionData,
+ colorScale,
+ subdivisionData,
+ setTooltipContent,
+ mapLoaded,
+ mapView,
+}: UseSubdivisionsLayerProps) {
+ useEffect(() => {
+ if (!map.current || !subdivisionsGeoData || !processedSubdivisionData || !mapLoaded) return;
+
+ const addSubdivisionsLayer = () => {
+ if (!map.current) return;
+
+ const geoDataCopy = JSON.parse(JSON.stringify(subdivisionsGeoData));
+ geoDataCopy.features.forEach((feature: any) => {
+ const code = feature.properties?.iso_3166_2;
+ const foundData = processedSubdivisionData.find((d: any) => d.value === code);
+ const count = foundData?.count || 0;
+ const color = count > 0 ? colorScale(count) : "rgba(140, 140, 140, 0.5)";
+ feature.properties.fillColor = color;
+ feature.properties.count = count;
+ });
+
+ if (map.current.getSource("subdivisions")) {
+ (map.current.getSource("subdivisions") as mapboxgl.GeoJSONSource).setData(geoDataCopy);
+ } else {
+ map.current.addSource("subdivisions", {
+ type: "geojson",
+ data: geoDataCopy,
+ });
+
+ map.current.addLayer({
+ id: "subdivisions-fill",
+ type: "fill",
+ source: "subdivisions",
+ paint: {
+ "fill-color": ["get", "fillColor"],
+ "fill-opacity": 0.6,
+ },
+ layout: {
+ visibility: mapView === "subdivisions" ? "visible" : "none",
+ },
+ });
+
+ map.current.addLayer({
+ id: "subdivisions-outline",
+ type: "line",
+ source: "subdivisions",
+ paint: {
+ "line-color": "#ffffff",
+ "line-width": 0.5,
+ "line-opacity": 0.3,
+ },
+ layout: {
+ visibility: mapView === "subdivisions" ? "visible" : "none",
+ },
+ });
+
+ map.current.on("mousemove", "subdivisions-fill", (e) => {
+ if (!map.current || !e.features || e.features.length === 0) return;
+ map.current.getCanvas().style.cursor = "pointer";
+
+ const feature = e.features[0];
+ const code = feature.properties?.iso_3166_2;
+ const name = feature.properties?.name;
+ const count = feature.properties?.count || 0;
+
+ const currentData = subdivisionData?.data;
+ const foundData = currentData?.find((d: any) => d.value === code);
+ const percentage = foundData?.percentage || 0;
+
+ setTooltipContent({
+ name,
+ code,
+ count,
+ percentage,
+ });
+ });
+
+ map.current.on("mouseleave", "subdivisions-fill", () => {
+ if (!map.current) return;
+ map.current.getCanvas().style.cursor = "";
+ setTooltipContent(null);
+ });
+
+ map.current.on("click", "subdivisions-fill", (e) => {
+ if (!e.features || e.features.length === 0) return;
+
+ const feature = e.features[0];
+ const code = feature.properties?.iso_3166_2;
+
+ addFilter({
+ parameter: "region" as FilterParameter,
+ value: [code],
+ type: "equals",
+ });
+ });
+ }
+ };
+
+ addSubdivisionsLayer();
+ }, [subdivisionsGeoData, processedSubdivisionData, colorScale, map, subdivisionData, setTooltipContent, mapLoaded]);
+}
diff --git a/client/src/app/[site]/globe/page.tsx b/client/src/app/[site]/globe/page.tsx
new file mode 100644
index 000000000..e88adf6ea
--- /dev/null
+++ b/client/src/app/[site]/globe/page.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import "mapbox-gl/dist/mapbox-gl.css";
+import { useMemo, useRef } from "react";
+
+import { useSingleCol } from "@/api/analytics/useSingleCol";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { useCountries, useSubdivisions } from "../../../lib/geo";
+import { CountryFlag } from "../components/shared/icons/CountryFlag";
+import { SubHeader } from "../components/SubHeader/SubHeader";
+import MapViewSelector from "./components/ModeSelector";
+import { useMapbox } from "./hooks/useMapbox";
+import { useCountriesLayer } from "./hooks/useCountriesLayer";
+import { useSubdivisionsLayer } from "./hooks/useSubdivisionsLayer";
+import { useLayerVisibility } from "./hooks/useLayerVisibility";
+import { useCoordinatesLayer } from "./hooks/useCoordinatesLayer";
+import { createColorScale } from "./utils/colorScale";
+import { processCountryData, processSubdivisionData } from "./utils/processData";
+import { useGetSessionLocations } from "../../../api/analytics/useGetSessionLocations";
+import { GlobeSessions } from "./components/GlobeSessions";
+import { useGlobeStore } from "./globeStore";
+
+export default function GlobePage() {
+ useSetPageTitle("Rybbit · Globe");
+ const mapContainer = useRef<HTMLDivElement>(null);
+
+ const { tooltipContent, tooltipPosition, mapView, setTooltipContent, setTooltipPosition, setMapView } =
+ useGlobeStore();
+
+ const { data: countryData } = useSingleCol({ parameter: "country" });
+ const { data: subdivisionData } = useSingleCol({ parameter: "region", limit: 10000 });
+ const { data: liveSessionLocations } = useGetSessionLocations();
+
+ const { data: countriesGeoData } = useCountries();
+ const { data: subdivisionsGeoData } = useSubdivisions();
+
+ const processedCountryData = useMemo(() => processCountryData(countryData), [countryData]);
+ const processedSubdivisionData = useMemo(() => processSubdivisionData(subdivisionData), [subdivisionData]);
+
+ const colorScale = useMemo(() => {
+ const dataToUse = mapView === "countries" ? processedCountryData : processedSubdivisionData;
+ return createColorScale(dataToUse);
+ }, [processedCountryData, processedSubdivisionData, mapView]);
+
+ const { map, mapLoaded } = useMapbox(mapContainer);
+
+ useCountriesLayer({
+ map,
+ countriesGeoData,
+ processedCountryData,
+ colorScale,
+ countryData,
+ setTooltipContent,
+ mapLoaded,
+ mapView,
+ });
+
+ useSubdivisionsLayer({
+ map,
+ subdivisionsGeoData,
+ processedSubdivisionData,
+ colorScale,
+ subdivisionData,
+ setTooltipContent,
+ mapLoaded,
+ mapView,
+ });
+
+ useCoordinatesLayer({
+ map,
+ liveSessionLocations,
+ mapLoaded,
+ minutes: 30,
+ setTooltipContent,
+ mapView,
+ });
+
+ useLayerVisibility(map, mapView, mapLoaded);
+
+ return (
+ <DisabledOverlay message="Globe" featurePath="globe">
+ <div
+ className="relative w-full h-dvh"
+ onMouseMove={e => {
+ if (tooltipContent) {
+ setTooltipPosition({
+ x: e.clientX,
+ y: e.clientY,
+ });
+ }
+ }}
+ >
+ <div className="p-2 md:p-4 relative z-50">
+ <SubHeader />
+ </div>
+ <div className="absolute top-0 left-0 right-0 bottom-0 z-10">
+ <div
+ ref={mapContainer}
+ className="w-full h-full [&_.mapboxgl-ctrl-bottom-left]:!hidden [&_.mapboxgl-ctrl-logo]:!hidden"
+ />
+ <div className="absolute bottom-0 left-4 z-99999">
+ <MapViewSelector />
+ </div>
+ <div className="absolute bottom-[60px] left-4 z-99999">
+ <GlobeSessions />
+ </div>
+ </div>
+ {tooltipContent && (
+ <div
+ className="fixed z-50 bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"
+ style={{
+ left: tooltipPosition.x,
+ top: tooltipPosition.y - 10,
+ transform: "translate(-50%, -100%)",
+ }}
+ >
+ <div className="font-sm flex items-center gap-1">
+ {tooltipContent.code && <CountryFlag country={tooltipContent.code.slice(0, 2)} />}
+ {tooltipContent.name}
+ </div>
+ <div>
+ <span className="font-bold text-accent-400">{tooltipContent.count.toLocaleString()}</span>{" "}
+ <span className="text-neutral-300">({tooltipContent.percentage.toFixed(1)}%) sessions</span>
+ </div>
+ </div>
+ )}
+ </div>
+ </DisabledOverlay>
+ );
+}
diff --git a/client/src/app/[site]/globe/utils/colorScale.ts b/client/src/app/[site]/globe/utils/colorScale.ts
new file mode 100644
index 000000000..4f54bb8db
--- /dev/null
+++ b/client/src/app/[site]/globe/utils/colorScale.ts
@@ -0,0 +1,23 @@
+import { scalePow } from "d3-scale";
+
+export function createColorScale(data: any[] | null): (value: number) => string {
+ if (!data) return () => "#eee";
+
+ const getComputedColor = (cssVar: string) => {
+ const hslValues = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
+ return `hsl(${hslValues})`;
+ };
+
+ const accentColor = getComputedColor("--accent-400");
+ const hslMatch = accentColor.match(/hsl\(([^)]+)\)/);
+ const hslValues = hslMatch ? hslMatch[1].split(" ") : ["0", "0%", "50%"];
+ const [h, s, l] = hslValues;
+
+ const values = data.map((d: any) => d.count);
+ const maxValue = Math.max(...values);
+
+ return scalePow<string>()
+ .exponent(0.4)
+ .domain([0, maxValue])
+ .range([`hsla(${h}, ${s}, ${l}, 0.05)`, `hsla(${h}, ${s}, ${l}, 0.8)`]);
+}
diff --git a/client/src/app/[site]/globe/utils/processData.ts b/client/src/app/[site]/globe/utils/processData.ts
new file mode 100644
index 000000000..dfea9b61b
--- /dev/null
+++ b/client/src/app/[site]/globe/utils/processData.ts
@@ -0,0 +1,28 @@
+import { getCountryPopulation } from "../../../../lib/countryPopulation";
+
+export function processCountryData(countryData: any) {
+ if (!countryData?.data) return null;
+
+ return countryData.data.map((item: any) => {
+ const population = getCountryPopulation(item.value);
+ const perCapitaValue = population > 0 ? item.count / population : 0;
+ return {
+ ...item,
+ perCapita: perCapitaValue,
+ };
+ });
+}
+
+export function processSubdivisionData(subdivisionData: any) {
+ if (!subdivisionData?.data) return null;
+
+ return subdivisionData.data.map((item: any) => {
+ const countryCode = item.value?.split("-")[0];
+ const population = getCountryPopulation(countryCode);
+ const perCapitaValue = population > 0 ? item.count / (population / 10) : 0;
+ return {
+ ...item,
+ perCapita: perCapitaValue,
+ };
+ });
+}
diff --git a/client/src/app/[site]/layout.tsx b/client/src/app/[site]/layout.tsx
index 1aff45da5..02d8c44b4 100644
--- a/client/src/app/[site]/layout.tsx
+++ b/client/src/app/[site]/layout.tsx
@@ -47,9 +47,10 @@ export default function SiteLayout({ children }: { children: React.ReactNode })
{/* <div className="px-4 py-2 max-w-[1400px] mx-auto w-full mb-4"> */}
<Header />
<div>{children}</div>
- {!pathname.includes("/map") && !pathname.includes("/realtime") && !pathname.includes("/replay") && (
- <Footer />
- )}
+ {!pathname.includes("/map") &&
+ !pathname.includes("/realtime") &&
+ !pathname.includes("/replay") &&
+ !pathname.includes("/globe") && <Footer />}
</div>
</div>
</div>
diff --git a/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx b/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx
index ccf0d48f3..564cd0c4d 100644
--- a/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx
+++ b/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx
@@ -8,7 +8,7 @@ import { memoize, debounce } from "lodash";
import { useEffect, useMemo, useRef, useState, useCallback } from "react";
import Globe from "react-globe.gl";
import { MeshPhongMaterial } from "three";
-import { useGetLiveSessionLocations } from "../../../../api/analytics/useGetLiveSessionLocations";
+import { useGetSessionLocations } from "../../../../api/analytics/useGetSessionLocations";
import { useAtom } from "jotai";
import { minutesAtom } from "../realtimeStore";
@@ -20,11 +20,7 @@ export const World = ({ width }: { width: number }) => {
const globeEl = useRef<any>(null);
const size = useWindowSize();
- const [minutes] = useAtom(minutesAtom);
-
- const { data: liveSessionLocations, isLoading: isLiveSessionLocationsLoading } = useGetLiveSessionLocations(
- Number(minutes)
- );
+ const { data: liveSessionLocations, isLoading: isLiveSessionLocationsLoading } = useGetSessionLocations();
const { data: countries = { features: [] } } = useQuery({
queryKey: ["countries"],
@@ -36,7 +32,7 @@ export const World = ({ width }: { width: number }) => {
const highest = liveSessionLocations?.reduce((acc, curr) => Math.max(acc, curr.count), 0) ?? 1;
- const normalized = 5 / Number(minutes);
+ const normalized = 5 / Number(30);
const weightColor = scaleSequentialSqrt(interpolateYlOrRd).domain([0, highest * normalized * 15]);
useEffect(() => {
diff --git a/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx b/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
index eaf5adea0..ba34764b5 100644
--- a/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
+++ b/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useGetLiveSessionLocations } from "@/api/analytics/useGetLiveSessionLocations";
+import { useGetSessionLocations } from "@/api/analytics/useGetSessionLocations";
import { scaleSqrt } from "d3-scale";
import { Feature, GeoJsonObject } from "geojson";
import { Layer } from "leaflet";
@@ -28,7 +28,7 @@ interface TooltipPosition {
}
export function RealtimeMap() {
- const { data: liveSessionLocations, isLoading: isLiveSessionLocationsLoading } = useGetLiveSessionLocations();
+ const { data: liveSessionLocations, isLoading: isLiveSessionLocationsLoading } = useGetSessionLocations();
const { data: countriesGeoData } = useCountries();
const [currentZoom, setCurrentZoom] = useState(1.5); // Initial zoom level
const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(null);
diff --git a/client/src/app/layout.tsx b/client/src/app/layout.tsx
index c894ec3d6..29f04e658 100644
--- a/client/src/app/layout.tsx
+++ b/client/src/app/layout.tsx
@@ -8,6 +8,7 @@ import { cn } from "../lib/utils";
import "./globals.css";
import Script from "next/script";
import { useStopImpersonation } from "@/hooks/useStopImpersonation";
+import { useIsProduction } from "@/hooks/useIsProduction";
import { ReactScan } from "./ReactScan";
import { OrganizationInitializer } from "../components/OrganizationInitializer";
import { AuthenticationGuard } from "../components/AuthenticationGuard";
@@ -18,40 +19,41 @@ export default function RootLayout({ children }: { children: React.ReactNode })
// Use the hook to expose stopImpersonating globally
useStopImpersonation();
+ const { isProduction, isAppProduction } = useIsProduction();
+
return (
<html lang="en" className="dark">
- {globalThis?.location?.hostname === "demo.rybbit.io" ||
- (globalThis?.location?.hostname === "app.rybbit.io" && (
- <head>
- <Script id="gtm-script" strategy="afterInteractive">
- {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
+ {isProduction && (
+ <head>
+ <Script id="gtm-script" strategy="afterInteractive">
+ {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-KWZ8K6K9');`}
- </Script>
- <Script
- id="reddit-pixel"
- strategy="afterInteractive"
- dangerouslySetInnerHTML={{
- __html: `!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement("script");t.src="https://www.redditstatic.com/ads/pixel.js",t.async=!0;var s=d.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','a2_hpzt3lz1c1f0');rdt('track', 'PageVisit');`,
- }}
- />
- <Script
- id="twitter-pixel"
- strategy="afterInteractive"
- dangerouslySetInnerHTML={{
- __html: `!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);
+ </Script>
+ <Script
+ id="reddit-pixel"
+ strategy="afterInteractive"
+ dangerouslySetInnerHTML={{
+ __html: `!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement("script");t.src="https://www.redditstatic.com/ads/pixel.js",t.async=!0;var s=d.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','a2_hpzt3lz1c1f0');rdt('track', 'PageVisit');`,
+ }}
+ />
+ <Script
+ id="twitter-pixel"
+ strategy="afterInteractive"
+ dangerouslySetInnerHTML={{
+ __html: `!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);
},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='https://static.ads-twitter.com/uwt.js',
a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');
twq('config','qj0po');`,
- }}
- />
- <Script
- id="facebook-pixel"
- strategy="afterInteractive"
- dangerouslySetInnerHTML={{
- __html: `!function(f,b,e,v,n,t,s)
+ }}
+ />
+ <Script
+ id="facebook-pixel"
+ strategy="afterInteractive"
+ dangerouslySetInnerHTML={{
+ __html: `!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
@@ -61,15 +63,14 @@ s.parentNode.insertBefore(t,s)}(window,document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '816836311029789');
fbq('track', 'PageView');`,
- }}
- />
- </head>
- ))}
+ }}
+ />
+ </head>
+ )}
<ReactScan />
<TooltipProvider>
- <body className={cn("bg-background text-foreground h-full", inter.className)}>
- {(globalThis?.location?.hostname === "demo.rybbit.io" ||
- globalThis?.location?.hostname === "app.rybbit.io") && (
+ <body className={cn("bg-background text-foreground h-full", inter.className)} suppressHydrationWarning>
+ {isProduction && (
<noscript>
<iframe
src="https://www.googletagmanager.com/ns.html?id=GTM-KWZ8K6K9"
@@ -87,7 +88,7 @@ fbq('track', 'PageView');`,
<Toaster />
</body>
</TooltipProvider>
- {globalThis?.location?.hostname === "app.rybbit.io" && (
+ {isAppProduction && (
<>
<Script
src="https://demo.rybbit.io/api/script.js"
diff --git a/client/src/components/Channel.tsx b/client/src/components/Channel.tsx
new file mode 100644
index 000000000..09845a54d
--- /dev/null
+++ b/client/src/components/Channel.tsx
@@ -0,0 +1,155 @@
+import {
+ Link,
+ Search,
+ ExternalLink,
+ Users,
+ Mail,
+ HelpCircle,
+ MousePointerClick,
+ DollarSign,
+ Monitor,
+ Video,
+ Handshake,
+ FileText,
+ ShoppingCart,
+ Calendar,
+ Headphones,
+} from "lucide-react";
+import { Badge } from "./ui/badge";
+import { Favicon } from "./Favicon";
+
+const getChannelIcon = (channel: string) => {
+ switch (channel) {
+ case "Direct":
+ return <Link className="w-4 h-4 text-gray-400" />;
+ case "Organic Search":
+ return <Search className="w-4 h-4 text-gray-400" />;
+ case "Referral":
+ return <ExternalLink className="w-4 h-4 text-gray-400" />;
+ case "Organic Social":
+ return <Users className="w-4 h-4 text-gray-400" />;
+ case "Email":
+ return <Mail className="w-4 h-4 text-gray-400" />;
+ case "Unknown":
+ return <HelpCircle className="w-4 h-4 text-gray-400" />;
+ case "Paid Search":
+ return <Search className="w-4 h-4 text-gray-400" />;
+ case "Paid Unknown":
+ return <DollarSign className="w-4 h-4 text-gray-400" />;
+ case "Paid Social":
+ return <Users className="w-4 h-4 text-gray-400" />;
+ case "Display":
+ return <Monitor className="w-4 h-4 text-gray-400" />;
+ case "Organic Video":
+ return <Video className="w-4 h-4 text-gray-400" />;
+ case "Affiliate":
+ return <Handshake className="w-4 h-4 text-gray-400" />;
+ case "Content":
+ return <FileText className="w-4 h-4 text-gray-400" />;
+ case "Organic Shopping":
+ return <ShoppingCart className="w-4 h-4 text-gray-400" />;
+ case "Event":
+ return <Calendar className="w-4 h-4 text-gray-400" />;
+ case "Audio":
+ return <Headphones className="w-4 h-4 text-gray-400" />;
+ default:
+ return null;
+ }
+};
+
+const getDisplayName = (hostname: string): string => {
+ // Handle Google domains with startsWith
+ if (hostname.startsWith("google.") || hostname.startsWith("www.google.")) {
+ return "Google";
+ }
+ if (hostname === "accounts.google.com") return "Google";
+ if (hostname === "mail.google.com") return "Gmail";
+
+ const commonSites: Record<string, string> = {
+ "bing.com": "Bing",
+ "cn.bing.com": "Bing",
+ "www.bing.com": "Bing",
+ "baidu.com": "Baidu",
+ "www.baidu.com": "Baidu",
+ "naver.com": "Naver",
+ "m.search.naver.com": "Naver",
+ "search.naver.com": "Naver",
+ "www.naver.com": "Naver",
+ "facebook.com": "Facebook",
+ "www.facebook.com": "Facebook",
+ "m.facebook.com": "Facebook",
+ "l.facebook.com": "Facebook",
+ "lm.facebook.com": "Facebook",
+ "instagram.com": "Instagram",
+ "www.instagram.com": "Instagram",
+ "l.instagram.com": "Instagram",
+ "youtube.com": "YouTube",
+ "www.youtube.com": "YouTube",
+ "reddit.com": "Reddit",
+ "www.reddit.com": "Reddit",
+ "out.reddit.com": "Reddit",
+ "twitter.com": "Twitter",
+ "x.com": "X",
+ "t.co": "X",
+ "linkedin.com": "LinkedIn",
+ "www.linkedin.com": "LinkedIn",
+ "github.com": "GitHub",
+ "duckduckgo.com": "DuckDuckGo",
+ "yandex.ru": "Yandex",
+ "ya.ru": "Yandex",
+ "yahoo.com": "Yahoo",
+ "search.yahoo.com": "Yahoo",
+ "tiktok.com": "TikTok",
+ "www.tiktok.com": "TikTok",
+ "pinterest.com": "Pinterest",
+ "www.pinterest.com": "Pinterest",
+ "chatgpt.com": "ChatGPT",
+ "perplexity.ai": "Perplexity",
+ "www.perplexity.ai": "Perplexity",
+ "news.ycombinator.com": "Hacker News",
+ "stripe.com": "Stripe",
+ "checkout.stripe.com": "Stripe",
+ "substack.com": "Substack",
+ "discord.com": "Discord",
+ "wikipedia.org": "Wikipedia",
+ "en.wikipedia.org": "Wikipedia",
+ "www.wikipedia.org": "Wikipedia",
+ };
+
+ return commonSites[hostname] || hostname;
+};
+
+const extractDomain = (url: string): string | null => {
+ try {
+ if (!url || url === "direct") return null;
+ if (url.startsWith("android-app://")) {
+ const match = url.match(/android-app:\/\/([^/]+)/);
+ return match ? match[1] : null;
+ }
+ const urlObj = new URL(url);
+ return urlObj.hostname;
+ } catch {
+ return null;
+ }
+};
+
+export function Channel({ channel, referrer }: { channel: string; referrer: string }) {
+ const domain = extractDomain(referrer);
+
+ if (domain) {
+ const displayName = getDisplayName(domain);
+ return (
+ <Badge className="flex items-center gap-1 bg-neutral-800 text-gray-300">
+ <Favicon domain={domain} className="w-4 h-4" />
+ <span>{displayName}</span>
+ </Badge>
+ );
+ }
+
+ return (
+ <Badge className="flex items-center gap-1 bg-neutral-800 text-gray-300">
+ {getChannelIcon(channel)}
+ <span>{channel}</span>
+ </Badge>
+ );
+}
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index 0ae470b70..553da661f 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -22,6 +22,8 @@ import {
} from "../TooltipIcons/TooltipIcons";
import { Badge } from "../ui/badge";
import { SessionDetails } from "./SessionDetails";
+import { Avatar } from "../Avatar";
+import { Channel } from "../Channel";
interface SessionCardProps {
session: GetSessionsResponse[number];
@@ -60,7 +62,8 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
<div className="p-3 cursor-pointer" onClick={handleCardClick}>
<div className="flex items-center gap-2">
<div className="hidden md:flex items-center gap-2">
- <span className="text-xs font-mono text-gray-400">{session.user_id.slice(0, 12)}</span>
+ {/* <span className="text-xs font-mono text-gray-400">{session.user_id.slice(0, 12)}</span> */}
+ <Avatar size={24} name={session.user_id.slice(0, 12)} />
</div>
{/* Icons section */}
@@ -80,7 +83,7 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
/>
<Tooltip>
<TooltipTrigger asChild>
- <Badge variant="outline" className="flex items-center gap-1 bg-neutral-800 text-gray-300">
+ <Badge className="flex items-center gap-1 bg-neutral-800 text-gray-300">
<FileText className="w-4 h-4 text-blue-500" />
<span>{formatter(session.pageviews)}</span>
</Badge>
@@ -89,31 +92,14 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
- <Badge variant="outline" className="flex items-center gap-1 bg-neutral-800 text-gray-300">
+ <Badge className="flex items-center gap-1 bg-neutral-800 text-gray-300">
<MousePointerClick className="w-4 h-4 text-amber-500" />
<span>{formatter(session.events)}</span>
</Badge>
</TooltipTrigger>
<TooltipContent>Events</TooltipContent>
</Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="outline" className="flex items-center gap-1 bg-neutral-800 text-gray-300">
- <TriangleAlert className="w-4 h-4 text-red-500" />
- <span>{formatter(session.errors)}</span>
- </Badge>
- </TooltipTrigger>
- <TooltipContent>Errors</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="outline" className="flex items-center gap-1 bg-neutral-800 text-gray-300">
- <ExternalLink className="w-4 h-4 text-purple-500" />
- <span>{formatter(session.outbound)}</span>
- </Badge>
- </TooltipTrigger>
- <TooltipContent>Outbound Clicks</TooltipContent>
- </Tooltip>
+ <Channel channel={session.channel} referrer={session.referrer} />
</div>
{/* Pages section with tooltips for long paths */}
@@ -145,7 +131,7 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
{/* Time information */}
- <div className="flex items-center gap-4 text-xs text-gray-300">
+ <div className="flex items-center gap-1.5 text-xs text-gray-300">
<span className="text-gray-400">
{DateTime.fromSQL(session.session_start, {
zone: "utc",
@@ -154,6 +140,7 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
.toLocal()
.toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
</span>
+ <span className="text-gray-400">•</span>
<span className="hidden md:block">{duration}</span>
</div>
diff --git a/client/src/components/ui/badge.tsx b/client/src/components/ui/badge.tsx
index 79f1492fe..522e93605 100644
--- a/client/src/components/ui/badge.tsx
+++ b/client/src/components/ui/badge.tsx
@@ -4,25 +4,18 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
- "inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-neutral-950 focus:ring-offset-2 dark:focus:ring-neutral-300",
+ "inline-flex items-center rounded-md border px-1.5 py-0.5 text-xs font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-neutral-300",
{
variants: {
variant: {
- default:
- "border-neutral-200 bg-neutral-100 text-neutral-900 hover:bg-neutral-200/80 dark:border-neutral-800 dark:bg-neutral-800 dark:text-neutral-100 dark:hover:bg-neutral-700",
- secondary:
- "border-neutral-200/50 bg-neutral-50 text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-300 dark:hover:bg-neutral-800",
- destructive:
- "border-transparent bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:bg-red-500/20 dark:text-red-400 dark:hover:bg-red-500/30",
- warning:
- "border-transparent bg-yellow-500/10 text-yellow-700 hover:bg-yellow-500/20 dark:bg-yellow-500/20 dark:text-yellow-400 dark:hover:bg-yellow-500/30",
- success:
- "border-transparent bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/20 dark:bg-emerald-500/20 dark:text-emerald-400 dark:hover:bg-emerald-500/30",
- info: "border-transparent bg-blue-500/10 text-blue-700 hover:bg-blue-500/20 dark:bg-blue-500/20 dark:text-blue-400 dark:hover:bg-blue-500/30",
- outline:
- "border-neutral-300 bg-transparent text-neutral-700 hover:bg-neutral-50 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800",
- ghost:
- "border-transparent bg-transparent text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800",
+ default: "border-neutral-800 bg-neutral-800 text-neutral-100 hover:bg-neutral-700",
+ secondary: "border-neutral-800 bg-neutral-900 text-neutral-300 hover:bg-neutral-800",
+ destructive: "border-transparent bg-red-500/20 text-red-400 hover:bg-red-500/30",
+ warning: "border-transparent bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30",
+ success: "border-transparent bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30",
+ info: "border-transparent bg-blue-500/20 text-blue-400 hover:bg-blue-500/30",
+ outline: "border-neutral-700 bg-transparent text-neutral-300 hover:bg-neutral-800",
+ ghost: "border-transparent bg-transparent text-neutral-300 hover:bg-neutral-800",
},
},
defaultVariants: {
diff --git a/client/src/components/ui/button-group.tsx b/client/src/components/ui/button-group.tsx
new file mode 100644
index 000000000..0621505f0
--- /dev/null
+++ b/client/src/components/ui/button-group.tsx
@@ -0,0 +1,75 @@
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@/lib/utils";
+import { Separator } from "@/components/ui/separator";
+
+const buttonGroupVariants = cva(
+ "flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
+ {
+ variants: {
+ orientation: {
+ horizontal:
+ "[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
+ vertical:
+ "flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
+ },
+ },
+ defaultVariants: {
+ orientation: "horizontal",
+ },
+ }
+);
+
+function ButtonGroup({
+ className,
+ orientation,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="button-group"
+ data-orientation={orientation}
+ className={cn(buttonGroupVariants({ orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupText({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot : "div";
+
+ return (
+ <Comp
+ className={cn(
+ "bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupSeparator({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="button-group-separator"
+ orientation={orientation}
+ className={cn("bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto", className)}
+ {...props}
+ />
+ );
+}
+
+export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants };
diff --git a/client/src/hooks/useIsProduction.ts b/client/src/hooks/useIsProduction.ts
new file mode 100644
index 000000000..36086833a
--- /dev/null
+++ b/client/src/hooks/useIsProduction.ts
@@ -0,0 +1,7 @@
+export function useIsProduction() {
+ const hostname = typeof window !== "undefined" ? window.location.hostname : "";
+ const isProduction = hostname === "demo.rybbit.io" || hostname === "app.rybbit.io";
+ const isAppProduction = hostname === "app.rybbit.io";
+
+ return { isProduction, isAppProduction };
+}
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 7d3639ea4..a453938b0 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -27,6 +27,8 @@ export const SESSION_PAGE_FILTERS: FilterParameter[] = [
"utm_term",
"utm_content",
"user_id",
+ "lat",
+ "lon",
];
export const SESSION_REPLAY_PAGE_FILTERS: FilterParameter[] = [
@@ -390,14 +392,14 @@ export const goForward = () => {
export const addFilter = (filter: Filter) => {
const { filters, setFilters } = useStore.getState();
- const filterExists = filters.some(
- f =>
- f.parameter === filter.parameter &&
- f.type === filter.type &&
- JSON.stringify(f.value) === JSON.stringify(filter.value)
+ const filterExists = filters.findIndex(
+ f => f.parameter === filter.parameter && f.type === filter.type
+ // JSON.stringify(f.value) === JSON.stringify(filter.value)
);
- if (!filterExists) {
+ if (filterExists === -1) {
setFilters([...filters, filter]);
+ } else {
+ setFilters(filters.map((f, i) => (i === filterExists ? filter : f)));
}
};
diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml
index be8d65556..bdaa7fee4 100644
--- a/docker-compose.cloud.yml
+++ b/docker-compose.cloud.yml
@@ -134,11 +134,13 @@ services:
NEXT_PUBLIC_BACKEND_URL: ${BASE_URL}
NEXT_PUBLIC_DISABLE_SIGNUP: ${DISABLE_SIGNUP}
NEXT_PUBLIC_CLOUD: ${CLOUD}
+ NEXT_PUBLIC_MAPBOX_TOKEN: ${NEXT_PUBLIC_MAPBOX_TOKEN}
environment:
- NODE_ENV=production
- NEXT_PUBLIC_BACKEND_URL=${BASE_URL}
- NEXT_PUBLIC_DISABLE_SIGNUP=${DISABLE_SIGNUP}
- NEXT_PUBLIC_CLOUD=${CLOUD}
+ - NEXT_PUBLIC_MAPBOX_TOKEN=${NEXT_PUBLIC_MAPBOX_TOKEN}
depends_on:
- backend
restart: unless-stopped
diff --git a/docker-compose.yml b/docker-compose.yml
index bdefc37e9..6b5fa94ed 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -121,12 +121,14 @@ services:
args:
NEXT_PUBLIC_BACKEND_URL: ${BASE_URL}
NEXT_PUBLIC_DISABLE_SIGNUP: ${DISABLE_SIGNUP}
+ NEXT_PUBLIC_MAPBOX_TOKEN: ${NEXT_PUBLIC_MAPBOX_TOKEN}
ports:
- "${HOST_CLIENT_PORT:-127.0.0.1:3002:3002}"
environment:
- NODE_ENV=production
- NEXT_PUBLIC_BACKEND_URL=${BASE_URL}
- NEXT_PUBLIC_DISABLE_SIGNUP=${DISABLE_SIGNUP}
+ - NEXT_PUBLIC_MAPBOX_TOKEN=${NEXT_PUBLIC_MAPBOX_TOKEN}
depends_on:
- backend
restart: unless-stopped
diff --git a/server/src/api/analytics/getLiveSessionLocations.ts b/server/src/api/analytics/getSessionLocations.ts
similarity index 65%
rename from server/src/api/analytics/getLiveSessionLocations.ts
rename to server/src/api/analytics/getSessionLocations.ts
index 3c320a4a0..6a1b5bfd6 100644
--- a/server/src/api/analytics/getLiveSessionLocations.ts
+++ b/server/src/api/analytics/getSessionLocations.ts
@@ -1,23 +1,21 @@
-import { FastifyRequest, FastifyReply } from "fastify";
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { processResults } from "./utils.js";
-import SqlString from "sqlstring";
+import { getFilterStatement, getTimeStatement, processResults } from "./utils.js";
-export async function getLiveSessionLocations(
+export async function getSessionLocations(
req: FastifyRequest<{
Params: {
site: string;
};
- Querystring: {
- time: number;
- };
+ Querystring: FilterParams<{}>;
}>,
res: FastifyReply
) {
const { site } = req.params;
- if (isNaN(Number(req.query.time))) {
- return res.status(400).send({ error: "Invalid time" });
- }
+
+ const filterStatement = getFilterStatement(req.query.filters);
+ const timeStatement = getTimeStatement(req.query);
const result = await clickhouse.query({
query: `
@@ -31,7 +29,8 @@ WITH stuff AS (
events
WHERE
site_id = {site:Int32}
- AND timestamp > now() - interval ${SqlString.escape(Number(req.query.time))} minute
+ ${timeStatement}
+ ${filterStatement}
GROUP BY
session_id
)
diff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.ts
index 2cfb73a10..ce4eaf89d 100644
--- a/server/src/api/analytics/getSessions.ts
+++ b/server/src/api/analytics/getSessions.ts
@@ -91,7 +91,9 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:
countIf(type = 'custom_event') AS events,
countIf(type = 'error') AS errors,
countIf(type = 'outbound') AS outbound,
- argMax(ip, timestamp) AS ip
+ argMax(ip, timestamp) AS ip,
+ argMax(lat, timestamp) AS lat,
+ argMax(lon, timestamp) AS lon
FROM events
WHERE
site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/query-validation.ts b/server/src/api/analytics/query-validation.ts
index e72543536..c6845006f 100644
--- a/server/src/api/analytics/query-validation.ts
+++ b/server/src/api/analytics/query-validation.ts
@@ -251,6 +251,8 @@ export const filterParamSchema = z.enum([
"browser_version",
"operating_system_version",
"user_id",
+ "lat",
+ "lon",
]);
/**
@@ -259,7 +261,7 @@ export const filterParamSchema = z.enum([
const filterSchema = z.object({
parameter: filterParamSchema,
type: filterTypeSchema,
- value: z.array(z.string()),
+ value: z.array(z.string().or(z.number())),
});
// =============================================================================
diff --git a/server/src/api/analytics/utils.ts b/server/src/api/analytics/utils.ts
index 0ac9b6eb7..2171c2f4d 100644
--- a/server/src/api/analytics/utils.ts
+++ b/server/src/api/analytics/utils.ts
@@ -155,18 +155,19 @@ export function getFilterStatement(filters: string) {
filtersArray
.map(filter => {
const x = filter.type === "contains" || filter.type === "not_contains" ? "%" : "";
+ const isNumericParam = filter.parameter === "lat" || filter.parameter === "lon";
if (filter.parameter === "entry_page") {
if (filter.value.length === 1) {
return `session_id IN (
- SELECT session_id
+ SELECT session_id
FROM (
- SELECT
- session_id,
+ SELECT
+ session_id,
argMin(pathname, timestamp) AS entry_pathname
- FROM events
+ FROM events
GROUP BY session_id
- )
+ )
WHERE entry_pathname ${filterTypeToOperator(filter.type)} ${SqlString.escape(x + filter.value[0] + x)}
)`;
}
@@ -176,14 +177,14 @@ export function getFilterStatement(filters: string) {
);
return `session_id IN (
- SELECT session_id
+ SELECT session_id
FROM (
- SELECT
- session_id,
+ SELECT
+ session_id,
argMin(pathname, timestamp) AS entry_pathname
- FROM events
+ FROM events
GROUP BY session_id
- )
+ )
WHERE (${valuesWithOperator.join(" OR ")})
)`;
}
@@ -191,14 +192,14 @@ export function getFilterStatement(filters: string) {
if (filter.parameter === "exit_page") {
if (filter.value.length === 1) {
return `session_id IN (
- SELECT session_id
+ SELECT session_id
FROM (
- SELECT
- session_id,
+ SELECT
+ session_id,
argMax(pathname, timestamp) AS exit_pathname
- FROM events
+ FROM events
GROUP BY session_id
- )
+ )
WHERE exit_pathname ${filterTypeToOperator(filter.type)} ${SqlString.escape(x + filter.value[0] + x)}
)`;
}
@@ -208,28 +209,43 @@ export function getFilterStatement(filters: string) {
);
return `session_id IN (
- SELECT session_id
+ SELECT session_id
FROM (
- SELECT
- session_id,
+ SELECT
+ session_id,
argMax(pathname, timestamp) AS exit_pathname
- FROM events
+ FROM events
GROUP BY session_id
- )
+ )
WHERE (${valuesWithOperator.join(" OR ")})
)`;
}
+ // Special handling for lat/lon with tolerance
+ if (filter.parameter === "lat" || filter.parameter === "lon") {
+ const tolerance = 0.001;
+ if (filter.value.length === 1) {
+ const targetValue = Number(filter.value[0]);
+ return `${filter.parameter} >= ${targetValue - tolerance} AND ${filter.parameter} <= ${targetValue + tolerance}`;
+ }
+
+ const rangeConditions = filter.value.map(value => {
+ const targetValue = Number(value);
+ return `(${filter.parameter} >= ${targetValue - tolerance} AND ${filter.parameter} <= ${targetValue + tolerance})`;
+ });
+
+ return `(${rangeConditions.join(" OR ")})`;
+ }
+
if (filter.value.length === 1) {
- return `${getSqlParam(filter.parameter)} ${filterTypeToOperator(
- filter.type
- )} ${SqlString.escape(x + filter.value[0] + x)}`;
+ const value = isNumericParam ? filter.value[0] : SqlString.escape(x + filter.value[0] + x);
+ return `${getSqlParam(filter.parameter)} ${filterTypeToOperator(filter.type)} ${value}`;
}
- const valuesWithOperator = filter.value.map(
- value =>
- `${getSqlParam(filter.parameter)} ${filterTypeToOperator(filter.type)} ${SqlString.escape(x + value + x)}`
- );
+ const valuesWithOperator = filter.value.map(value => {
+ const escapedValue = isNumericParam ? value : SqlString.escape(x + value + x);
+ return `${getSqlParam(filter.parameter)} ${filterTypeToOperator(filter.type)} ${escapedValue}`;
+ });
return `(${valuesWithOperator.join(" OR ")})`;
})
diff --git a/server/src/index.ts b/server/src/index.ts
index 33de2da1f..718e2cd0e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -19,7 +19,7 @@ import { getErrorBucketed } from "./api/analytics/getErrorBucketed.js";
import { getErrorEvents } from "./api/analytics/getErrorEvents.js";
import { getErrorNames } from "./api/analytics/getErrorNames.js";
import { getJourneys } from "./api/analytics/getJourneys.js";
-import { getLiveSessionLocations } from "./api/analytics/getLiveSessionLocations.js";
+import { getSessionLocations } from "./api/analytics/getSessionLocations.js";
import { getLiveUsercount } from "./api/analytics/getLiveUsercount.js";
import { getOrgEventCount } from "./api/analytics/getOrgEventCount.js";
import { getOverview } from "./api/analytics/getOverview.js";
@@ -218,7 +218,7 @@ const ANALYTICS_ROUTES = [
"/api/users/",
"/api/user/info/",
"/api/user/session-count/",
- "/api/live-session-locations/",
+ "/api/session-locations/",
"/api/funnels/",
"/api/funnel/",
"/api/journeys/",
@@ -302,7 +302,7 @@ server.get("/api/users/:site", getUsers);
server.get("/api/user/:userId/sessions/:site", getUserSessions);
server.get("/api/user/session-count/:site", getUserSessionCount);
server.get("/api/user/info/:userId/:site", getUserInfo);
-server.get("/api/live-session-locations/:site", getLiveSessionLocations);
+server.get("/api/session-locations/:site", getSessionLocations);
server.get("/api/funnels/:site", getFunnels);
server.get("/api/journeys/:site", getJourneys);
server.post("/api/funnel/:site", getFunnel);
diff --git a/shared/src/filters.ts b/shared/src/filters.ts
index babbe8885..d7cb90eec 100644
--- a/shared/src/filters.ts
+++ b/shared/src/filters.ts
@@ -25,7 +25,9 @@ export type FilterParameter =
| "dimensions"
| "browser_version"
| "operating_system_version"
- | "user_id";
+ | "user_id"
+ | "lat"
+ | "lon";
export interface Filter {
parameter: FilterParameter;