diff --git a/.github/workflows/web-sdk-react.yml b/.github/workflows/web-sdk-react.yml new file mode 100644 index 0000000..487cf11 --- /dev/null +++ b/.github/workflows/web-sdk-react.yml @@ -0,0 +1,79 @@ +name: web-sdk-react + +on: + pull_request: + paths: + - 'web-sdk-react/**' + - '.github/workflows/web-sdk-react.yml' + push: + branches: [master] + paths: + - 'web-sdk-react/**' + - '.github/workflows/web-sdk-react.yml' + workflow_dispatch: + inputs: + target: + description: 'Where to deploy' + required: true + type: choice + options: [staging, production] + version: + description: 'Release version for production, e.g. 2.0.0' + required: false + type: string + +defaults: + run: + working-directory: web-sdk-react + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: yarn + cache-dependency-path: web-sdk-react/yarn.lock + + - run: yarn install --frozen-lockfile + - run: yarn lint + - run: yarn typecheck + - run: yarn build + + image: + needs: check + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Resolve image tag + id: tag + env: + TARGET: ${{ inputs.target }} + VERSION: ${{ inputs.version }} + run: | + if [ "$TARGET" = "production" ]; then + echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || { echo "version must look like 2.0.0"; exit 1; } + echo "value=$VERSION" >> "$GITHUB_OUTPUT" + else + echo "value=staging-${GITHUB_SHA::8}-$(date +%s)" >> "$GITHUB_OUTPUT" + fi + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - uses: docker/build-push-action@v6 + with: + context: web-sdk-react + push: true + tags: ${{ secrets.DOCKER_HUB_USERNAME }}/sdk-demo:${{ steps.tag.outputs.value }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/README.md b/README.md index 06fb05a..09fdf82 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ # examples -[WebSDK Typescript](web-sdk-ts/README.md) - A simplest example +- [Web SDK + React](web-sdk-react/README.md) — a complete video-call app with a token backend, live at [sdk-demo.livedigital.space](https://sdk-demo.livedigital.space) +- [Web SDK + TypeScript](web-sdk-ts/README.md) — the simplest example diff --git a/web-sdk-react/.dockerignore b/web-sdk-react/.dockerignore new file mode 100644 index 0000000..cb0c333 --- /dev/null +++ b/web-sdk-react/.dockerignore @@ -0,0 +1,3 @@ +**/node_modules +**/dist +.env diff --git a/web-sdk-react/.env.example b/web-sdk-react/.env.example new file mode 100644 index 0000000..876d28f --- /dev/null +++ b/web-sdk-react/.env.example @@ -0,0 +1,8 @@ +LIVEDIGITAL_PERSONAL_TOKEN= +LIVEDIGITAL_SPACE_ID= + +# LIVEDIGITAL_API_URL=https://moodhood-api.livedigital.space/v1 +# LIVEDIGITAL_SIGNALING_URL= +# LIVEDIGITAL_ANALYTICS_URL= +# LIVEDIGITAL_STATIC_URL=https://static.prod.livedigital.space +# PORT=3000 diff --git a/web-sdk-react/.gitignore b/web-sdk-react/.gitignore new file mode 100644 index 0000000..02551b4 --- /dev/null +++ b/web-sdk-react/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist +.env +.idea diff --git a/web-sdk-react/Dockerfile b/web-sdk-react/Dockerfile new file mode 100644 index 0000000..4420c41 --- /dev/null +++ b/web-sdk-react/Dockerfile @@ -0,0 +1,21 @@ +FROM node:24-alpine AS build +WORKDIR /app +COPY package.json yarn.lock ./ +COPY client/package.json client/ +COPY server/package.json server/ +RUN yarn install --frozen-lockfile +COPY client client +RUN yarn workspace client build + +FROM node:24-alpine +WORKDIR /app +ENV NODE_ENV=production +COPY package.json yarn.lock ./ +COPY client/package.json client/ +COPY server/package.json server/ +RUN yarn install --frozen-lockfile --production && yarn cache clean +COPY server/src server/src +COPY --from=build /app/client/dist client/dist +USER node +EXPOSE 3000 +CMD ["node", "server/src/index.ts"] diff --git a/web-sdk-react/README.md b/web-sdk-react/README.md new file mode 100644 index 0000000..d1e44af --- /dev/null +++ b/web-sdk-react/README.md @@ -0,0 +1,87 @@ +# livedigital Web SDK — React example + +[Русская версия](#русская-версия) + +A reference video-call app built on [`@livedigital/client`](https://www.npmjs.com/package/@livedigital/client). +It runs live at [sdk-demo.livedigital.space](https://sdk-demo.livedigital.space). + +- `server/` — a small Node.js backend. It keeps the Personal Token, creates rooms and issues a `signalingToken` + for every participant. The three livedigital API calls live in [`server/src/livedigital.ts`](server/src/livedigital.ts). +- `client/` — a React + Vite + TypeScript app structured with [Feature-Sliced Design](https://feature-sliced.design). + +## Run locally + +Requires Node.js 24+ and yarn. + +1. [Create a Personal Token](https://docs.livedigital.space/docs/tutorials/auth/create_personal_token) and a + [space](https://docs.livedigital.space/docs/tutorials/spaces) for the demo rooms. +2. Configure and start: + +```bash +cp .env.example .env # fill in LIVEDIGITAL_PERSONAL_TOKEN and LIVEDIGITAL_SPACE_ID +yarn install +yarn dev # client on http://localhost:5173, API on http://localhost:3000 +``` + +The Personal Token is a management key: it must stay on the server and never reach the browser. + +## Where to look + +| What | Where | +| --- | --- | +| Room, participant and `signalingToken` on the backend | `server/src/livedigital.ts` | +| Single `Client` instance | `client/src/shared/sdk` | +| Join, state sync, reconnect, subscriptions | `client/src/entities/session` | +| Rendering participants and their tracks | `client/src/entities/peer` | +| Publishing camera and microphone | `client/src/features/local-media` | + +## Production build + +```bash +docker build -t sdk-demo . +docker run --env-file .env -p 3000:3000 sdk-demo +``` + +--- + +## Русская версия + +Пример приложения для видеозвонков на [`@livedigital/client`](https://www.npmjs.com/package/@livedigital/client). +Работает на [sdk-demo.livedigital.space](https://sdk-demo.livedigital.space). + +- `server/` — небольшой бэкенд на Node.js. Хранит Personal Token, создаёт комнаты и выпускает `signalingToken` + для каждого участника. Три вызова API livedigital лежат в [`server/src/livedigital.ts`](server/src/livedigital.ts). +- `client/` — приложение на React + Vite + TypeScript с архитектурой [Feature-Sliced Design](https://feature-sliced.design). + +## Локальный запуск + +Нужны Node.js 24+ и yarn. + +1. [Создайте Personal Token](https://docs.livedigital.space/docs/tutorials/auth/create_personal_token) и + [пространство](https://docs.livedigital.space/docs/tutorials/spaces) для комнат демо. +2. Настройте и запустите: + +```bash +cp .env.example .env # заполните LIVEDIGITAL_PERSONAL_TOKEN и LIVEDIGITAL_SPACE_ID +yarn install +yarn dev # клиент на http://localhost:5173, API на http://localhost:3000 +``` + +Personal Token — управляющий ключ: он живёт только на сервере и не должен попадать в браузер. + +## Где что смотреть + +| Что | Где | +| --- | --- | +| Комната, участник и `signalingToken` на бэкенде | `server/src/livedigital.ts` | +| Единственный экземпляр `Client` | `client/src/shared/sdk` | +| Вход, синхронизация состояния, реконнект, подписки | `client/src/entities/session` | +| Отрисовка участников и их треков | `client/src/entities/peer` | +| Публикация камеры и микрофона | `client/src/features/local-media` | + +## Сборка для продакшена + +```bash +docker build -t sdk-demo . +docker run --env-file .env -p 3000:3000 sdk-demo +``` diff --git a/web-sdk-react/client/eslint.config.js b/web-sdk-react/client/eslint.config.js new file mode 100644 index 0000000..4ee69c6 --- /dev/null +++ b/web-sdk-react/client/eslint.config.js @@ -0,0 +1,7 @@ +import reactHooks from 'eslint-plugin-react-hooks'; +import tseslint from 'typescript-eslint'; + +export default tseslint.config( + ...tseslint.configs.recommended, + reactHooks.configs.flat.recommended, +); diff --git a/web-sdk-react/client/index.html b/web-sdk-react/client/index.html new file mode 100644 index 0000000..bb7599d --- /dev/null +++ b/web-sdk-react/client/index.html @@ -0,0 +1,13 @@ + + + + + + + livedigital SDK demo + + +
+ + + diff --git a/web-sdk-react/client/package.json b/web-sdk-react/client/package.json new file mode 100644 index 0000000..3247a30 --- /dev/null +++ b/web-sdk-react/client/package.json @@ -0,0 +1,35 @@ +{ + "name": "client", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "lint:fsd": "steiger src" + }, + "dependencies": { + "@livedigital/client": "3.63.2", + "events": "^3.3.0", + "i18next": "^27.2.2", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-i18next": "^18.0.3", + "react-router": "^7.18.6", + "zustand": "^5.1.0" + }, + "devDependencies": { + "@feature-sliced/steiger-plugin": "^0.8.2", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^6.3.0", + "eslint": "^10.15.0", + "eslint-plugin-react-hooks": "^7.1.1", + "steiger": "^0.10.0", + "typescript": "^5.9.0", + "typescript-eslint": "^8.73.0", + "vite": "^8.3.8" + } +} diff --git a/web-sdk-react/client/public/favicon.svg b/web-sdk-react/client/public/favicon.svg new file mode 100644 index 0000000..0c1c5e6 --- /dev/null +++ b/web-sdk-react/client/public/favicon.svg @@ -0,0 +1 @@ + diff --git a/web-sdk-react/client/src/app/App.tsx b/web-sdk-react/client/src/app/App.tsx new file mode 100644 index 0000000..e7c159e --- /dev/null +++ b/web-sdk-react/client/src/app/App.tsx @@ -0,0 +1,15 @@ +import { BrowserRouter, Navigate, Route, Routes } from 'react-router'; +import { HomePage } from '@/pages/home'; +import { RoomPage } from '@/pages/room'; + +export function App() { + return ( + + + } /> + } /> + } /> + + + ); +} diff --git a/web-sdk-react/client/src/app/index.tsx b/web-sdk-react/client/src/app/index.tsx new file mode 100644 index 0000000..0f36cc8 --- /dev/null +++ b/web-sdk-react/client/src/app/index.tsx @@ -0,0 +1,18 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { bindSessionEvents } from '@/entities/session'; +import { demoApi } from '@/shared/api'; +import { initI18n } from '@/shared/i18n'; +import { createSdkClient } from '@/shared/sdk'; +import { App } from './App'; +import './styles/index.css'; + +const [sdkConfig] = await Promise.all([demoApi.getSdkConfig(), initI18n()]); + +bindSessionEvents(createSdkClient({ ...sdkConfig, logLevel: 4 })); + +createRoot(document.getElementById('root')!).render( + + + , +); diff --git a/web-sdk-react/client/src/app/styles/index.css b/web-sdk-react/client/src/app/styles/index.css new file mode 100644 index 0000000..cb85c4e --- /dev/null +++ b/web-sdk-react/client/src/app/styles/index.css @@ -0,0 +1,327 @@ +:root { + --bg: #0f1115; + --surface: #181b22; + --surface-raised: #222631; + --border: #2c313d; + --text: #eceef2; + --text-muted: #9aa1b0; + --accent: #4f6bff; + --accent-hover: #6a82ff; + --danger: #e5484d; + --success: #3dd68c; + --radius: 12px; + + color-scheme: dark; + font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + font-size: 15px; + line-height: 1.5; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); +} + +a { + color: var(--accent-hover); + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +h1 { + margin: 0; + font-size: 24px; + line-height: 1.25; +} + +.page { + display: flex; + flex-direction: column; + min-height: 100dvh; +} + +.page--room { + height: 100dvh; +} + +.page__center { + display: flex; + flex: 1; + align-items: center; + justify-content: center; + padding: 16px; +} + +.page__stage { + flex: 1; + min-height: 0; + padding: 12px 16px; +} + +.header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); +} + +.header__title { + color: var(--text); + font-weight: 600; +} + +.header__nav { + display: flex; + align-items: center; + gap: 16px; + font-size: 14px; +} + +.card { + width: 100%; + max-width: 440px; + padding: 28px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.hero { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 16px; +} + +.hero p { + margin: 0; + color: var(--text-muted); +} + +.form { + display: flex; + flex-direction: column; + gap: 16px; +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; + color: var(--text-muted); + font-size: 13px; +} + +.field input, +.field select { + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg); + color: var(--text); + font: inherit; +} + +.field input:focus-visible, +.field select:focus-visible, +.button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +.button { + padding: 10px 16px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface-raised); + color: var(--text); + font: inherit; + font-weight: 500; + cursor: pointer; + transition: background 0.15s, border-color 0.15s; +} + +.button:hover:not(:disabled) { + border-color: var(--text-muted); +} + +.button:disabled { + opacity: 0.55; + cursor: default; +} + +.button--primary { + border-color: var(--accent); + background: var(--accent); +} + +.button--primary:hover:not(:disabled) { + border-color: var(--accent-hover); + background: var(--accent-hover); +} + +.button--danger { + border-color: var(--danger); + background: var(--danger); +} + +.button--active { + border-color: var(--success); + color: var(--success); +} + +.error { + margin: 0; + color: var(--danger); + font-size: 14px; +} + +.language-switcher { + display: flex; + overflow: hidden; + border: 1px solid var(--border); + border-radius: 8px; +} + +.language-switcher__item { + padding: 4px 10px; + border: 0; + background: transparent; + color: var(--text-muted); + font: inherit; + font-size: 13px; + cursor: pointer; +} + +.language-switcher__item--active { + background: var(--surface-raised); + color: var(--text); +} + +.status-banner { + padding: 8px 16px; + background: var(--surface-raised); + color: var(--text-muted); + text-align: center; + font-size: 14px; +} + +.video-grid { + display: grid; + grid-template-columns: repeat(var(--columns, 1), minmax(0, 1fr)); + grid-auto-rows: minmax(0, 1fr); + gap: 12px; + height: 100%; +} + +.video-grid[data-count='2'], +.video-grid[data-count='3'], +.video-grid[data-count='4'] { + --columns: 2; +} + +.video-grid[data-count='5'], +.video-grid[data-count='6'], +.video-grid[data-count='7'], +.video-grid[data-count='8'], +.video-grid[data-count='9'] { + --columns: 3; +} + +.peer-tile { + position: relative; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + min-height: 0; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.peer-tile__avatar { + display: flex; + align-items: center; + justify-content: center; + width: 88px; + height: 88px; + border-radius: 50%; + background: var(--surface-raised); + color: var(--text-muted); + font-size: 36px; + font-weight: 600; +} + +.peer-tile__caption { + position: absolute; + bottom: 10px; + left: 10px; + display: flex; + align-items: center; + gap: 8px; + max-width: calc(100% - 20px); + padding: 4px 10px; + border-radius: 6px; + background: rgb(0 0 0 / 55%); + font-size: 13px; +} + +.peer-tile__mic { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--danger); +} + +.peer-tile__mic--on { + background: var(--success); +} + +.video { + width: 100%; + height: 100%; + object-fit: cover; +} + +.video--mirrored { + transform: scaleX(-1); +} + +.control-bar { + padding: 12px 16px; + border-top: 1px solid var(--border); +} + +.control-bar__buttons { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 10px; +} + +.control-bar__error { + margin-bottom: 8px; + text-align: center; +} + +@media (max-width: 640px) { + .header__nav a { + display: none; + } + + .video-grid { + --columns: 1 !important; + } +} diff --git a/web-sdk-react/client/src/entities/peer/index.ts b/web-sdk-react/client/src/entities/peer/index.ts new file mode 100644 index 0000000..aa74a99 --- /dev/null +++ b/web-sdk-react/client/src/entities/peer/index.ts @@ -0,0 +1 @@ +export { PeerTile } from './ui/PeerTile'; diff --git a/web-sdk-react/client/src/entities/peer/model/usePeerDisplayName.ts b/web-sdk-react/client/src/entities/peer/model/usePeerDisplayName.ts new file mode 100644 index 0000000..3859322 --- /dev/null +++ b/web-sdk-react/client/src/entities/peer/model/usePeerDisplayName.ts @@ -0,0 +1,22 @@ +import type { Peer } from '@livedigital/client'; +import { useEffect, useState } from 'react'; + +const readDisplayName = (appData: Record) => ( + typeof appData.displayName === 'string' ? appData.displayName : '' +); + +export function usePeerDisplayName(peer: Peer): string { + const [displayName, setDisplayName] = useState(() => readDisplayName(peer.appData)); + + useEffect(() => { + const handler = (appData: Record) => setDisplayName(readDisplayName(appData)); + + peer.observer.on('app-data-updated', handler); + + return () => { + peer.observer.off('app-data-updated', handler); + }; + }, [peer]); + + return displayName; +} diff --git a/web-sdk-react/client/src/entities/peer/model/usePeerTracks.ts b/web-sdk-react/client/src/entities/peer/model/usePeerTracks.ts new file mode 100644 index 0000000..457b417 --- /dev/null +++ b/web-sdk-react/client/src/entities/peer/model/usePeerTracks.ts @@ -0,0 +1,44 @@ +import type { Peer, PeerTrack } from '@livedigital/client'; +import { useEffect, useState } from 'react'; + +type TracksByLabel = Map; + +const TRACK_EVENTS = ['track-start', 'track-end', 'track-paused', 'track-resumed'] as const; + +const collectTracks = (peer: Peer): TracksByLabel => ( + new Map([...peer.tracks.values()].map((track) => [track.label, track])) +); + +export function usePeerTracks(peer: Peer): TracksByLabel { + const [tracks, setTracks] = useState(() => collectTracks(peer)); + + useEffect(() => { + const update = (track: PeerTrack, event: typeof TRACK_EVENTS[number]) => { + setTracks((current) => { + const next = new Map(current); + + if (event === 'track-end') { + next.delete(track.label); + } else { + next.set(track.label, track); + } + + return next; + }); + }; + + const handlers = TRACK_EVENTS.map((event) => { + const handler = (track: PeerTrack) => update(track, event); + + peer.observer.on(event, handler); + + return { event, handler }; + }); + + return () => { + handlers.forEach(({ event, handler }) => peer.observer.off(event, handler)); + }; + }, [peer]); + + return tracks; +} diff --git a/web-sdk-react/client/src/entities/peer/model/usePublishedMedia.ts b/web-sdk-react/client/src/entities/peer/model/usePublishedMedia.ts new file mode 100644 index 0000000..3ce52e3 --- /dev/null +++ b/web-sdk-react/client/src/entities/peer/model/usePublishedMedia.ts @@ -0,0 +1,20 @@ +import type { PayloadOfPublishedMedia, Peer } from '@livedigital/client'; +import { useEffect, useState } from 'react'; + +const PUBLICATION_EVENTS = ['media-published', 'media-unpublished', 'publisher-paused', 'publisher-resumed'] as const; + +export function usePublishedMedia(peer: Peer): PayloadOfPublishedMedia[] { + const [media, setMedia] = useState(() => peer.publishedMedia); + + useEffect(() => { + const update = () => setMedia(peer.publishedMedia); + + PUBLICATION_EVENTS.forEach((event) => peer.observer.on(event, update)); + + return () => { + PUBLICATION_EVENTS.forEach((event) => peer.observer.off(event, update)); + }; + }, [peer]); + + return media; +} diff --git a/web-sdk-react/client/src/entities/peer/ui/PeerTile.tsx b/web-sdk-react/client/src/entities/peer/ui/PeerTile.tsx new file mode 100644 index 0000000..e64fa8a --- /dev/null +++ b/web-sdk-react/client/src/entities/peer/ui/PeerTile.tsx @@ -0,0 +1,34 @@ +import type { Peer } from '@livedigital/client'; +import { useTranslation } from 'react-i18next'; +import { usePeerDisplayName } from '../model/usePeerDisplayName'; +import { usePeerTracks } from '../model/usePeerTracks'; +import { usePublishedMedia } from '../model/usePublishedMedia'; +import { VideoView } from './VideoView'; + +interface PeerTileProps { + peer: Peer; +} + +export function PeerTile({ peer }: PeerTileProps) { + const { t } = useTranslation(); + const tracks = usePeerTracks(peer); + const displayName = usePeerDisplayName(peer); + const publishedMedia = usePublishedMedia(peer); + + const camera = tracks.get('camera'); + const isCameraVisible = camera && !camera.isPaused; + const isMicrophoneOn = publishedMedia.some(({ label, paused }) => label === 'microphone' && !paused); + const name = peer.isMe ? `${displayName} (${t('room.you')})` : displayName; + + return ( +
+ {isCameraVisible + ? + :
{displayName.slice(0, 1).toUpperCase() || '?'}
} +
+ + {name} +
+
+ ); +} diff --git a/web-sdk-react/client/src/entities/peer/ui/VideoView.tsx b/web-sdk-react/client/src/entities/peer/ui/VideoView.tsx new file mode 100644 index 0000000..c86b605 --- /dev/null +++ b/web-sdk-react/client/src/entities/peer/ui/VideoView.tsx @@ -0,0 +1,35 @@ +import { useEffect, useRef } from 'react'; + +interface VideoViewProps { + track: MediaStreamTrack; + mirrored?: boolean; +} + +export function VideoView({ track, mirrored }: VideoViewProps) { + const videoRef = useRef(null); + + useEffect(() => { + const video = videoRef.current; + + if (!video) { + return; + } + + video.srcObject = new MediaStream([track]); + video.play().catch(() => undefined); + + return () => { + video.srcObject = null; + }; + }, [track]); + + return ( +