@mrksbnc/livekit-vue 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -0
  3. package/dist/components.cjs +2 -0
  4. package/dist/components.cjs.map +1 -0
  5. package/dist/components.d.ts +1 -0
  6. package/dist/components.mjs +213 -0
  7. package/dist/components.mjs.map +1 -0
  8. package/dist/composables.cjs +2 -0
  9. package/dist/composables.cjs.map +1 -0
  10. package/dist/composables.d.ts +1 -0
  11. package/dist/composables.mjs +913 -0
  12. package/dist/composables.mjs.map +1 -0
  13. package/dist/contexts-BGR-EyiF.mjs +227 -0
  14. package/dist/contexts-BGR-EyiF.mjs.map +1 -0
  15. package/dist/favicon.ico +0 -0
  16. package/dist/index.cjs +2 -0
  17. package/dist/index.cjs.map +1 -0
  18. package/dist/index.css +1 -0
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.mjs +74 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/shared-B72lPzrj.cjs +2 -0
  23. package/dist/shared-B72lPzrj.cjs.map +1 -0
  24. package/dist/shared-Bt-fJtlk.cjs +2 -0
  25. package/dist/shared-Bt-fJtlk.cjs.map +1 -0
  26. package/dist/shared-UqxyWhFA.cjs +2 -0
  27. package/dist/shared-UqxyWhFA.cjs.map +1 -0
  28. package/package.json +78 -0
  29. package/src/App.vue +16 -0
  30. package/src/assets/icons/chevron-down.svg +4 -0
  31. package/src/assets/icons/chevron-up.svg +4 -0
  32. package/src/assets/icons/frown.svg +7 -0
  33. package/src/assets/icons/heart.svg +6 -0
  34. package/src/assets/icons/mic-off.svg +8 -0
  35. package/src/assets/icons/mic.svg +7 -0
  36. package/src/assets/icons/phone-hang-up.svg +9 -0
  37. package/src/assets/icons/share-screen-off.svg +6 -0
  38. package/src/assets/icons/share-screen.svg +7 -0
  39. package/src/assets/icons/smile.svg +7 -0
  40. package/src/assets/icons/thumbs-down.svg +6 -0
  41. package/src/assets/icons/thumbs-up.svg +6 -0
  42. package/src/assets/icons/video-off.svg +5 -0
  43. package/src/assets/icons/video.svg +5 -0
  44. package/src/assets/index.ts +1 -0
  45. package/src/assets/placeholders/participant.svg +8 -0
  46. package/src/components/controls/TrackToggle.vue +27 -0
  47. package/src/components/controls/buttons.ts +5 -0
  48. package/src/components/controls/index.ts +3 -0
  49. package/src/components/controls/track_toggle.ts +13 -0
  50. package/src/components/icons/ParticipantPlaceholderIcon.vue +7 -0
  51. package/src/components/icons/TrackIcon.vue +55 -0
  52. package/src/components/index.ts +3 -0
  53. package/src/components/participant/AudioTrack.vue +17 -0
  54. package/src/components/participant/audio_track.ts +8 -0
  55. package/src/composables/index.ts +89 -0
  56. package/src/composables/private/useObservableState.ts +44 -0
  57. package/src/composables/useAudioPlayback.ts +42 -0
  58. package/src/composables/useClearPinButton.ts +41 -0
  59. package/src/composables/useConnectionQualityIndicator.ts +39 -0
  60. package/src/composables/useConnectionState.ts +21 -0
  61. package/src/composables/useDataChannel.ts +56 -0
  62. package/src/composables/useDisconnectButton.ts +28 -0
  63. package/src/composables/useFacingMode.ts +28 -0
  64. package/src/composables/useFocusToggle.ts +38 -0
  65. package/src/composables/useGridLayout.ts +44 -0
  66. package/src/composables/useIsEncrypted.ts +34 -0
  67. package/src/composables/useIsMuted.ts +56 -0
  68. package/src/composables/useIsRecording.ts +30 -0
  69. package/src/composables/useIsSpeaking.ts +23 -0
  70. package/src/composables/useLiveKitRoom.ts +219 -0
  71. package/src/composables/useLocalParticipant.ts +64 -0
  72. package/src/composables/useParticipantTile.ts +68 -0
  73. package/src/composables/useParticipantTracks.ts +36 -0
  74. package/src/composables/useParticipants.ts +25 -0
  75. package/src/composables/usePersistentUserChoices.ts +64 -0
  76. package/src/composables/usePinnedTracks.ts +16 -0
  77. package/src/composables/useRemoteParticipant.ts +42 -0
  78. package/src/composables/useRemoteParticipants.ts +27 -0
  79. package/src/composables/useRoomInfo.ts +42 -0
  80. package/src/composables/useSortedParticipants.ts +21 -0
  81. package/src/composables/useSpeakingParticipants.ts +22 -0
  82. package/src/composables/useStartAudio.ts +53 -0
  83. package/src/composables/useStartVideo.ts +53 -0
  84. package/src/composables/useToken.ts +40 -0
  85. package/src/composables/useTrack.ts +11 -0
  86. package/src/composables/useTrackByName.ts +11 -0
  87. package/src/composables/useTrackMutedIndicator.ts +34 -0
  88. package/src/composables/useTrackRefBySourceOrName.ts +39 -0
  89. package/src/composables/useTrackSyncTime.ts +32 -0
  90. package/src/composables/useTrackToggle.ts +113 -0
  91. package/src/composables/useTrackVolume.ts +268 -0
  92. package/src/composables/useTracks.ts +122 -0
  93. package/src/composables/useVisualStableUpdate.ts +57 -0
  94. package/src/context/index.ts +6 -0
  95. package/src/context/layout.context.ts +46 -0
  96. package/src/context/participant.context.ts +33 -0
  97. package/src/context/pin.context.ts +50 -0
  98. package/src/context/room.context.ts +31 -0
  99. package/src/context/track_reference.context.ts +29 -0
  100. package/src/context/widget.context.ts +17 -0
  101. package/src/index.css +1 -0
  102. package/src/index.ts +5 -0
  103. package/src/main.ts +6 -0
  104. package/src/types/livekit_room.types.ts +78 -0
  105. package/src/utils/room.utils.ts +9 -0
@@ -0,0 +1,39 @@
1
+ import {
2
+ getTrackByIdentifier,
3
+ setupMediaTrack,
4
+ type TrackReferenceOrPlaceholder,
5
+ type TrackSource,
6
+ } from '@livekit/components-core';
7
+ import { useSubscription } from '@vueuse/rxjs';
8
+ import { Track, TrackPublication } from 'livekit-client';
9
+ import { computed, ref, toRefs, type ShallowRef } from 'vue';
10
+
11
+ export function useTrackRefBySourceOrName(
12
+ source: TrackSource<Track.Source>,
13
+ ): ShallowRef<TrackReferenceOrPlaceholder> {
14
+ const publication = ref<TrackPublication | undefined>(getTrackByIdentifier(source));
15
+
16
+ const mediaTrackSetupResult = computed<ReturnType<typeof setupMediaTrack>>(() =>
17
+ setupMediaTrack(source),
18
+ );
19
+
20
+ const { trackObserver } = toRefs(mediaTrackSetupResult.value);
21
+
22
+ useSubscription(
23
+ trackObserver.value.subscribe((pub) => {
24
+ publication.value = pub;
25
+ }),
26
+ );
27
+
28
+ const trackReference = computed<TrackReferenceOrPlaceholder>(() => {
29
+ const track: TrackReferenceOrPlaceholder = {
30
+ participant: source.participant,
31
+ source: source.source ?? Track.Source.Unknown,
32
+ publication: publication.value as TrackPublication,
33
+ };
34
+
35
+ return track;
36
+ });
37
+
38
+ return trackReference;
39
+ }
@@ -0,0 +1,32 @@
1
+ import { trackSyncTimeObserver, type TrackReferenceOrPlaceholder } from '@livekit/components-core';
2
+ import { useObservable } from '@vueuse/rxjs';
3
+ import type { Observable } from 'rxjs';
4
+ import type { ShallowRef } from 'vue';
5
+ import { useObservableState } from './private/useObservableState';
6
+
7
+ export function useTrackSyncTime(ref: TrackReferenceOrPlaceholder | undefined): ShallowRef<{
8
+ timestamp: number;
9
+ rtpTimestamp: number | undefined;
10
+ }> {
11
+ const observable = ref?.publication?.track
12
+ ? // @ts-expect-error - Observer type mismatch
13
+ useObservable(trackSyncTimeObserver(ref?.publication.track))
14
+ : undefined;
15
+
16
+ if (!observable) {
17
+ throw new Error('Please provide a valid observable when using `useTrackSyncTime`');
18
+ }
19
+
20
+ const observedState = useObservableState({
21
+ observable: observable?.value as unknown as Observable<{
22
+ timestamp: number;
23
+ rtpTimestamp: number;
24
+ }>,
25
+ startWith: {
26
+ timestamp: Date.now(),
27
+ rtpTimestamp: ref?.publication?.track?.rtpTimestamp,
28
+ },
29
+ });
30
+
31
+ return observedState;
32
+ }
@@ -0,0 +1,113 @@
1
+ import type { TrackToggleProps } from '@/components/controls/track_toggle';
2
+ import { useMaybeRoomContext } from '@/context/room.context';
3
+ import {
4
+ setupManualToggle,
5
+ setupMediaToggle,
6
+ type CaptureOptionsBySource,
7
+ type ToggleSource,
8
+ } from '@livekit/components-core';
9
+ import type { LocalTrackPublication } from 'livekit-client';
10
+ import type { Observable } from 'rxjs';
11
+ import { computed, onMounted, ref, toRefs, watch, type ShallowRef } from 'vue';
12
+ import { useObservableState } from './private/useObservableState';
13
+
14
+ export type UseTrackToggleProps<T extends ToggleSource> = Omit<TrackToggleProps<T>, 'showIcon'>;
15
+
16
+ export type StateObserver = Observable<boolean>;
17
+
18
+ export type UseTrackToggleReturnType<T extends ToggleSource> = {
19
+ toggle?: ShallowRef<
20
+ | ((forceState?: boolean) => Promise<void>)
21
+ | ((
22
+ forceState?: boolean,
23
+ captureOptions?: CaptureOptionsBySource<T> | undefined,
24
+ ) => Promise<boolean | undefined>)
25
+ >;
26
+ enabled: ShallowRef<boolean>;
27
+ pending: ShallowRef<boolean>;
28
+ track: ShallowRef<LocalTrackPublication | undefined>;
29
+ buttonProps: {
30
+ 'aria-pressed': boolean;
31
+ 'data-lk-source': T;
32
+ 'data-lk-enabled': boolean;
33
+ disabled: boolean;
34
+ onClick: (evt: MouseEvent) => void;
35
+ };
36
+ };
37
+
38
+ export function useTrackToggle<T extends ToggleSource>(
39
+ options: UseTrackToggleProps<T>,
40
+ ): UseTrackToggleReturnType<T> {
41
+ const room = useMaybeRoomContext();
42
+
43
+ const userInteractionRef = ref<boolean>(false);
44
+
45
+ const track = computed<LocalTrackPublication | undefined>(() =>
46
+ room?.value?.localParticipant?.getTrackPublication(options.source),
47
+ );
48
+
49
+ const setupMediaToggleResult = computed(() =>
50
+ room
51
+ ? setupMediaToggle<T>(
52
+ options.source,
53
+ room.value,
54
+ options.captureOptions,
55
+ options.publishOptions,
56
+ options.onDeviceError,
57
+ )
58
+ : setupManualToggle(),
59
+ );
60
+
61
+ const { className, enabledObserver, pendingObserver, toggle } = toRefs(
62
+ setupMediaToggleResult.value,
63
+ );
64
+
65
+ const pending = useObservableState({
66
+ observable: pendingObserver.value as unknown as StateObserver,
67
+ startWith: false,
68
+ });
69
+
70
+ const enabled = useObservableState({
71
+ observable: enabledObserver.value as unknown as StateObserver,
72
+ startWith: options.initialState ?? !!track.value?.isEnabled,
73
+ });
74
+
75
+ function onOnClick(evt: MouseEvent) {
76
+ evt.preventDefault();
77
+ evt.stopPropagation();
78
+
79
+ userInteractionRef.value = true;
80
+
81
+ toggle?.value().catch(() => (userInteractionRef.value = false));
82
+
83
+ if (options.customOnClickHandler) {
84
+ options.customOnClickHandler(evt);
85
+ }
86
+ }
87
+
88
+ watch(enabled, (enabled) => {
89
+ options?.onChange?.(enabled, userInteractionRef.value);
90
+ userInteractionRef.value = false;
91
+ });
92
+
93
+ onMounted(() => {
94
+ if (options.initialState !== undefined) {
95
+ console.debug('forcing initial toggle state', options.source, options.initialState);
96
+ toggle?.value(options.initialState);
97
+ }
98
+ });
99
+
100
+ return {
101
+ toggle,
102
+ enabled,
103
+ pending,
104
+ track,
105
+ buttonProps: {
106
+ 'aria-pressed': enabled.value,
107
+ 'data-lk-source': options.source,
108
+ 'data-lk-enabled': enabled.value,
109
+ disabled: pending.value ?? false,
110
+ onClick: onOnClick,
111
+ },
112
+ };
113
+ }
@@ -0,0 +1,268 @@
1
+ import {
2
+ isTrackReference,
3
+ type TrackReference,
4
+ type TrackReferenceOrPlaceholder,
5
+ } from '@livekit/components-core';
6
+ import {
7
+ createAudioAnalyser,
8
+ Track,
9
+ type AudioAnalyserOptions,
10
+ type LocalAudioTrack,
11
+ type RemoteAudioTrack,
12
+ } from 'livekit-client';
13
+ import { onBeforeMount, onWatcherCleanup, ref, watch, type ShallowRef } from 'vue';
14
+
15
+ export type MultiBandTrackVolumeOptions = {
16
+ bands?: number;
17
+ /**
18
+ * cut off of frequency bins on the lower end
19
+ * Note: this is not a frequency measure, but in relation to analyserOptions.fftSize,
20
+ */
21
+ loPass?: number;
22
+ /**
23
+ * cut off of frequency bins on the higher end
24
+ * Note: this is not a frequency measure, but in relation to analyserOptions.fftSize,
25
+ */
26
+ hiPass?: number;
27
+ updateInterval?: number;
28
+ analyserOptions?: AnalyserOptions;
29
+ };
30
+
31
+ export type AudioWaveformOptions = {
32
+ barCount?: number;
33
+ volMultiplier?: number;
34
+ updateInterval?: number;
35
+ };
36
+
37
+ const multibandDefaults = {
38
+ bands: 5,
39
+ loPass: 100,
40
+ hiPass: 600,
41
+ updateInterval: 32,
42
+ analyserOptions: { fftSize: 2048 },
43
+ } as const satisfies MultiBandTrackVolumeOptions;
44
+
45
+ const waveformDefaults = {
46
+ barCount: 120,
47
+ volMultiplier: 5,
48
+ updateInterval: 20,
49
+ } as const satisfies AudioWaveformOptions;
50
+
51
+ function normalizeFrequencies(frequencies: Float32Array): Float32Array<ArrayBuffer> {
52
+ const normalizeDb = (value: number) => {
53
+ const minDb = -100;
54
+ const maxDb = -10;
55
+ let db = 1 - (Math.max(minDb, Math.min(maxDb, value)) * -1) / 100;
56
+ db = Math.sqrt(db);
57
+
58
+ return db;
59
+ };
60
+
61
+ // Normalize all frequency values
62
+ return frequencies.map((value) => {
63
+ if (value === -Infinity) {
64
+ return 0;
65
+ }
66
+ return normalizeDb(value);
67
+ });
68
+ }
69
+
70
+ function getFFTSizeValue(x: number): number {
71
+ if (x < 32) return 32;
72
+ else return pow2ceil(x);
73
+ }
74
+
75
+ function pow2ceil(v: number): number {
76
+ let p = 2;
77
+ while ((v >>= 1)) {
78
+ p <<= 1;
79
+ }
80
+ return p;
81
+ }
82
+
83
+ function filterData(audioData: Float32Array, numSamples: number): Float32Array {
84
+ const blockSize = Math.floor(audioData.length / numSamples); // the number of samples in each subdivision
85
+ const filteredData = new Float32Array(numSamples);
86
+ for (let i = 0; i < numSamples; i++) {
87
+ const blockStart = blockSize * i; // the location of the first sample in the block
88
+ let sum = 0;
89
+ for (let j = 0; j < blockSize; j++) {
90
+ sum = sum + Math.abs(audioData[blockStart + j]); // find the sum of all the samples in the block
91
+ }
92
+ filteredData[i] = sum / blockSize; // divide the sum by the block size to get the average
93
+ }
94
+ return filteredData;
95
+ }
96
+
97
+ export function useTrackVolume(
98
+ trackOrTrackReference?: LocalAudioTrack | RemoteAudioTrack | TrackReference,
99
+ options: AudioAnalyserOptions = { fftSize: 32, smoothingTimeConstant: 0 },
100
+ ): ShallowRef<number> {
101
+ const track = isTrackReference(trackOrTrackReference)
102
+ ? <LocalAudioTrack | RemoteAudioTrack | undefined>trackOrTrackReference.publication.track
103
+ : trackOrTrackReference;
104
+
105
+ const volume = ref<number>(0);
106
+
107
+ watch(
108
+ () => track,
109
+ (val) => {
110
+ if (!val || !val.mediaStream) {
111
+ return;
112
+ }
113
+
114
+ const { cleanup, analyser } = createAudioAnalyser(val, options);
115
+
116
+ const bufferLength = analyser.frequencyBinCount;
117
+ const dataArray = new Uint8Array(bufferLength);
118
+
119
+ function updateVolume() {
120
+ analyser.getByteFrequencyData(dataArray);
121
+ let sum = 0;
122
+ for (let i = 0; i < dataArray.length; i++) {
123
+ const a = dataArray[i];
124
+ sum += a * a;
125
+ }
126
+ volume.value = Math.sqrt(sum / dataArray.length) / 255;
127
+ }
128
+
129
+ const interval = setInterval(updateVolume, 1000 / 30);
130
+
131
+ onWatcherCleanup(() => {
132
+ cleanup();
133
+ clearInterval(interval);
134
+ });
135
+ },
136
+ { deep: true },
137
+ );
138
+
139
+ return volume;
140
+ }
141
+
142
+ export function useMultibandTrackVolume(
143
+ trackOrTrackReference?: LocalAudioTrack | RemoteAudioTrack | TrackReferenceOrPlaceholder,
144
+ options: MultiBandTrackVolumeOptions = {},
145
+ ): ShallowRef<number[]> {
146
+ const track =
147
+ trackOrTrackReference instanceof Track
148
+ ? trackOrTrackReference
149
+ : <LocalAudioTrack | RemoteAudioTrack | undefined>trackOrTrackReference?.publication?.track;
150
+
151
+ const opts = { ...multibandDefaults, ...options };
152
+ const frequencyBands = ref<number[]>(new Array(opts.bands).fill(0));
153
+
154
+ watch(
155
+ [track, options],
156
+ () => {
157
+ if (!track || !track?.mediaStream) {
158
+ return;
159
+ }
160
+ const { analyser, cleanup } = createAudioAnalyser(track, opts.analyserOptions);
161
+
162
+ const bufferLength = analyser.frequencyBinCount;
163
+ const dataArray = new Float32Array(bufferLength);
164
+
165
+ const updateVolume = () => {
166
+ analyser.getFloatFrequencyData(dataArray);
167
+
168
+ let frequencies: Float32Array = new Float32Array(dataArray.length);
169
+
170
+ for (let i = 0; i < dataArray.length; i++) {
171
+ frequencies[i] = dataArray[i];
172
+ }
173
+
174
+ frequencies = frequencies.slice(options.loPass, options.hiPass);
175
+
176
+ const chunks: Array<number> = [];
177
+ const normalizedFrequencies = normalizeFrequencies(frequencies);
178
+ const chunkSize = Math.ceil(normalizedFrequencies.length / opts.bands);
179
+
180
+ for (let i = 0; i < opts.bands; i++) {
181
+ const summedVolumes = normalizedFrequencies
182
+ .slice(i * chunkSize, (i + 1) * chunkSize)
183
+ .reduce((acc, val) => (acc += val), 0);
184
+
185
+ chunks.push(summedVolumes / chunkSize);
186
+ }
187
+
188
+ frequencyBands.value = chunks;
189
+ };
190
+
191
+ const interval = setInterval(updateVolume, opts.updateInterval);
192
+
193
+ onWatcherCleanup(() => {
194
+ cleanup();
195
+ clearInterval(interval);
196
+ });
197
+ },
198
+ { deep: true },
199
+ );
200
+
201
+ return frequencyBands;
202
+ }
203
+
204
+ export function useAudioWaveform(
205
+ trackOrTrackReference?: LocalAudioTrack | RemoteAudioTrack | TrackReferenceOrPlaceholder,
206
+ options: AudioWaveformOptions = {},
207
+ ): {
208
+ bars: ShallowRef<number[]>;
209
+ } {
210
+ const track =
211
+ trackOrTrackReference instanceof Track
212
+ ? trackOrTrackReference
213
+ : <LocalAudioTrack | RemoteAudioTrack | undefined>trackOrTrackReference?.publication?.track;
214
+ const opts = { ...waveformDefaults, ...options };
215
+
216
+ const aggregateWave = ref<Float32Array<ArrayBuffer>>(new Float32Array());
217
+ const timeRef = ref<number>(performance.now());
218
+ const updates = ref<number>(0);
219
+ const bars = ref<number[]>([]);
220
+
221
+ function onUpdate(wave: Float32Array) {
222
+ bars.value = Array.from(
223
+ filterData(wave, opts.barCount).map((v) => Math.sqrt(v) * opts.volMultiplier),
224
+ );
225
+ }
226
+
227
+ watch([track, options], () => {
228
+ if (!track || !track?.mediaStream) {
229
+ return;
230
+ }
231
+
232
+ const { analyser, cleanup } = createAudioAnalyser(track, {
233
+ fftSize: getFFTSizeValue(opts.barCount),
234
+ });
235
+
236
+ const bufferLength = getFFTSizeValue(opts.barCount);
237
+ const dataArray = new Float32Array(bufferLength);
238
+
239
+ const update = () => {
240
+ updateWaveform = requestAnimationFrame(update);
241
+ analyser.getFloatTimeDomainData(dataArray);
242
+ aggregateWave.value.map((v, i) => v + dataArray[i]);
243
+ updates.value += 1;
244
+
245
+ if (performance.now() - timeRef.value >= opts.updateInterval) {
246
+ const newData = dataArray.map((v) => v / updates.value);
247
+ onUpdate(newData);
248
+ timeRef.value = performance.now();
249
+ updates.value = 0;
250
+ }
251
+ };
252
+
253
+ let updateWaveform = requestAnimationFrame(update);
254
+
255
+ onWatcherCleanup(() => {
256
+ cleanup();
257
+ cancelAnimationFrame(updateWaveform);
258
+ });
259
+ });
260
+
261
+ onBeforeMount(() => {
262
+ onUpdate(aggregateWave.value);
263
+ });
264
+
265
+ return {
266
+ bars,
267
+ };
268
+ }
@@ -0,0 +1,122 @@
1
+ import { useEnsureRoomContext } from '@/context/room.context';
2
+ import {
3
+ isSourcesWithOptions,
4
+ isSourceWitOptions,
5
+ type SourcesArray,
6
+ type TrackReference,
7
+ type TrackReferenceOrPlaceholder,
8
+ type TrackReferencePlaceholder,
9
+ type TrackSourceWithOptions,
10
+ } from '@livekit/components-core';
11
+ import { Participant, Track, type Room, type RoomEvent } from 'livekit-client';
12
+ import { computed, ref } from 'vue';
13
+
14
+ export type UseTracksOptions = {
15
+ updateOnlyOn?: RoomEvent[];
16
+ onlySubscribed?: boolean;
17
+ room?: Room;
18
+ };
19
+
20
+ export type UseTracksHookReturnType<T> = T extends Track.Source[]
21
+ ? TrackReference[]
22
+ : T extends TrackSourceWithOptions[]
23
+ ? TrackReferenceOrPlaceholder[]
24
+ : never;
25
+
26
+ function difference<T>(setA: Set<T>, setB: Set<T>): Set<T> {
27
+ const _difference = new Set(setA);
28
+ for (const elem of setB) {
29
+ _difference.delete(elem);
30
+ }
31
+ return _difference;
32
+ }
33
+
34
+ export function requiredPlaceholders<T extends SourcesArray>(
35
+ sources: T,
36
+ participants: Participant[],
37
+ ): Map<Participant['identity'], Track.Source[]> {
38
+ const placeholderMap = new Map<Participant['identity'], Track.Source[]>();
39
+ if (isSourcesWithOptions(sources)) {
40
+ const sourcesThatNeedPlaceholder = sources
41
+ .filter((sourceWithOption) => sourceWithOption.withPlaceholder)
42
+ .map((sourceWithOption) => sourceWithOption.source);
43
+
44
+ participants.forEach((participant) => {
45
+ const sourcesOfSubscribedTracks = participant
46
+ .getTrackPublications()
47
+ .map((pub) => pub.track?.source)
48
+ .filter((trackSource): trackSource is Track.Source => trackSource !== undefined);
49
+ const placeholderNeededForThisParticipant = Array.from(
50
+ difference(new Set(sourcesThatNeedPlaceholder), new Set(sourcesOfSubscribedTracks)),
51
+ );
52
+ // If the participant needs placeholder add it to the placeholder map.
53
+ if (placeholderNeededForThisParticipant.length > 0) {
54
+ placeholderMap.set(participant.identity, placeholderNeededForThisParticipant);
55
+ }
56
+ });
57
+ }
58
+ return placeholderMap;
59
+ }
60
+
61
+ export function useTracks<T extends SourcesArray = Track.Source[]>(
62
+ sources: T = [
63
+ Track.Source.Camera,
64
+ Track.Source.Microphone,
65
+ Track.Source.ScreenShare,
66
+ Track.Source.ScreenShareAudio,
67
+ Track.Source.Unknown,
68
+ ] as T,
69
+ options: UseTracksOptions = {},
70
+ ): UseTracksHookReturnType<T> {
71
+ const room = useEnsureRoomContext(options.room);
72
+ const trackReferences = ref<TrackReference[]>([]);
73
+ const participants = ref<Participant[]>([]);
74
+
75
+ const computedSources = computed(() =>
76
+ sources.map((s) => (isSourceWitOptions(s) ? s.source : s)),
77
+ );
78
+
79
+ const maybeTrackReferences = computed(() => {
80
+ if (isSourcesWithOptions(sources)) {
81
+ const requirePlaceholder = requiredPlaceholders(sources, participants.value as Participant[]);
82
+
83
+ const trackReferencesWithPlaceholders = Array.from(
84
+ trackReferences.value,
85
+ ) as TrackReferenceOrPlaceholder[];
86
+
87
+ for (const participant of participants.value) {
88
+ if (requirePlaceholder.has(participant.identity)) {
89
+ const sourcesToAddPlaceholder = requirePlaceholder.get(participant.identity) ?? [];
90
+
91
+ for (const placeholderSource of sourcesToAddPlaceholder) {
92
+ if (
93
+ trackReferencesWithPlaceholders.find(
94
+ ({ participant: p, publication }) =>
95
+ participant.identity === p.identity && publication?.source === placeholderSource,
96
+ )
97
+ ) {
98
+ continue;
99
+ }
100
+
101
+ console.debug(
102
+ `Add ${placeholderSource} placeholder for participant ${participant.identity}.`,
103
+ );
104
+
105
+ const placeholder: TrackReferencePlaceholder = {
106
+ participant: participant as Participant,
107
+ source: placeholderSource as Track.Source,
108
+ };
109
+
110
+ trackReferencesWithPlaceholders.push(placeholder);
111
+ }
112
+ }
113
+ }
114
+
115
+ return trackReferencesWithPlaceholders;
116
+ } else {
117
+ return trackReferences;
118
+ }
119
+ });
120
+
121
+ return maybeTrackReferences.value as UseTracksHookReturnType<T>;
122
+ }
@@ -0,0 +1,57 @@
1
+ import { updatePages, type TrackReferenceOrPlaceholder } from '@livekit/components-core';
2
+ import { computed, ref, watch, type ShallowRef } from 'vue';
3
+
4
+ export interface UseVisualStableUpdateOptions {
5
+ customSortFunction?: (
6
+ trackReferences: TrackReferenceOrPlaceholder[],
7
+ ) => TrackReferenceOrPlaceholder[];
8
+ }
9
+
10
+ export function useVisualStableUpdate(
11
+ /** `TrackReference`s to display in the grid. */
12
+ trackReferences: TrackReferenceOrPlaceholder[],
13
+ maxItemsOnPage: number,
14
+ options: UseVisualStableUpdateOptions = {},
15
+ ): ShallowRef<TrackReferenceOrPlaceholder[]> {
16
+ const lastMaxItemsOnPage = ref<number>(-1);
17
+ const lastTrackRefs = ref<TrackReferenceOrPlaceholder[]>([]);
18
+
19
+ const isLayoutChanged = computed<boolean>(() => {
20
+ return maxItemsOnPage !== lastMaxItemsOnPage.value;
21
+ });
22
+
23
+ const sortedTrackReferences = computed<TrackReferenceOrPlaceholder[]>(() => {
24
+ return options.customSortFunction
25
+ ? options.customSortFunction(trackReferences)
26
+ : trackReferences;
27
+ });
28
+
29
+ const updatedTrackReferences = ref<TrackReferenceOrPlaceholder[]>([
30
+ ...sortedTrackReferences.value,
31
+ ]);
32
+
33
+ function updateTrackReferences(): void {
34
+ if (!isLayoutChanged.value) {
35
+ try {
36
+ updatedTrackReferences.value = updatePages(
37
+ lastTrackRefs.value as TrackReferenceOrPlaceholder[],
38
+ sortedTrackReferences.value,
39
+ maxItemsOnPage,
40
+ );
41
+ } catch (error) {
42
+ console.error('Error while running updatePages(): ', error);
43
+ }
44
+ }
45
+
46
+ if (isLayoutChanged.value) {
47
+ lastTrackRefs.value = sortedTrackReferences.value;
48
+ } else {
49
+ lastTrackRefs.value = updatedTrackReferences.value;
50
+ }
51
+ lastMaxItemsOnPage.value = maxItemsOnPage;
52
+ }
53
+
54
+ watch(() => sortedTrackReferences, updateTrackReferences);
55
+
56
+ return updatedTrackReferences as ShallowRef<TrackReferenceOrPlaceholder[]>;
57
+ }
@@ -0,0 +1,6 @@
1
+ export * from './layout.context';
2
+ export * from './participant.context';
3
+ export * from './pin.context';
4
+ export * from './room.context';
5
+ export * from './track_reference.context';
6
+ export * from './widget.context';
@@ -0,0 +1,46 @@
1
+ import { createInjectionState } from '@vueuse/core';
2
+ import { shallowRef, type ShallowRef } from 'vue';
3
+ import { usePinContext, type PinContext } from './pin.context';
4
+ import { useWidgetContext, type WidgetContextType } from './widget.context';
5
+
6
+ export type LayoutState = {
7
+ pin: PinContext;
8
+ widget: WidgetContextType;
9
+ };
10
+
11
+ const [useProvideLayoutContext, useLayoutContext] = createInjectionState(
12
+ (initialValue: LayoutState): ShallowRef<LayoutState> => {
13
+ const state = shallowRef(initialValue);
14
+
15
+ return state;
16
+ },
17
+ );
18
+
19
+ export { useLayoutContext, useProvideLayoutContext };
20
+
21
+ export function useMaybeLayoutContext(): ShallowRef<LayoutState> | undefined {
22
+ return useLayoutContext();
23
+ }
24
+
25
+ export function useEnsureLayoutContext(layoutContext?: LayoutState) {
26
+ const lc = layoutContext ? shallowRef(layoutContext) : useLayoutContext();
27
+
28
+ if (!lc) {
29
+ throw Error('Tried to access LayoutContext context outside a LayoutContextProvider provider.');
30
+ }
31
+ return lc;
32
+ }
33
+
34
+ export function useCreateLayoutContext() {
35
+ return {
36
+ pin: usePinContext(),
37
+ widget: useWidgetContext(),
38
+ };
39
+ }
40
+
41
+ export function useEnsureCreateLayoutContext(layoutContext?: {
42
+ pin: PinContext;
43
+ widget: WidgetContextType;
44
+ }) {
45
+ return shallowRef(layoutContext) ?? useCreateLayoutContext();
46
+ }