@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,41 @@
1
+ import { useEnsureLayoutContext } from '@/context/layout.context';
2
+ import type { PinContext } from '@/context/pin.context';
3
+ import { type PinState } from '@livekit/components-core';
4
+ import { computed, type HTMLAttributes, type ShallowRef } from 'vue';
5
+
6
+ export type UseClearButtonReturnType = {
7
+ elementProps: ShallowRef<HTMLAttributes>;
8
+ };
9
+
10
+ export function useClearPinButton(props: HTMLAttributes): UseClearButtonReturnType {
11
+ const layoutContext = useEnsureLayoutContext();
12
+
13
+ const pinState = computed<PinContext>(() => {
14
+ return layoutContext.value.pin;
15
+ });
16
+
17
+ const state = computed<PinState>(() => {
18
+ return pinState.value.state;
19
+ });
20
+
21
+ const dispatch = computed<PinContext['dispatch']>(() => {
22
+ return pinState.value.dispatch;
23
+ });
24
+
25
+ const elementProps = computed<HTMLAttributes>(() => {
26
+ return {
27
+ ...props,
28
+ class: 'lk-clear-pin-button',
29
+ disabled: !state.value?.length,
30
+ onClick: () => {
31
+ if (dispatch.value) {
32
+ dispatch.value({ msg: 'clear_pin' });
33
+ }
34
+ },
35
+ };
36
+ });
37
+
38
+ return {
39
+ elementProps,
40
+ };
41
+ }
@@ -0,0 +1,39 @@
1
+ import { useEnsureParticipant } from '@/context/participant.context';
2
+ import { setupConnectionQualityIndicator } from '@livekit/components-core';
3
+ import { ConnectionQuality, type Participant } from 'livekit-client';
4
+ import type { Observable } from 'rxjs';
5
+ import { computed, toRefs, type ShallowRef } from 'vue';
6
+ import { useObservableState } from './private/useObservableState';
7
+
8
+ export type ConnectionQualityIndicatorOptions = {
9
+ participant?: Participant;
10
+ };
11
+
12
+ export type ConnectionQualityIndicatorReturnType = {
13
+ className: ShallowRef<string>;
14
+ quality: ShallowRef<ConnectionQuality>;
15
+ };
16
+
17
+ export function useConnectionQualityIndicator(
18
+ options: ConnectionQualityIndicatorOptions = {},
19
+ ): ConnectionQualityIndicatorReturnType {
20
+ const p = useEnsureParticipant(options.participant);
21
+
22
+ const setupConnectionQualityIndicatorResult = computed(() =>
23
+ setupConnectionQualityIndicator(p.value),
24
+ );
25
+
26
+ const { className, connectionQualityObserver } = toRefs(
27
+ setupConnectionQualityIndicatorResult.value,
28
+ );
29
+
30
+ const quality = useObservableState({
31
+ observable: connectionQualityObserver.value as unknown as Observable<ConnectionQuality>,
32
+ startWith: ConnectionQuality.Unknown,
33
+ });
34
+
35
+ return {
36
+ className,
37
+ quality,
38
+ };
39
+ }
@@ -0,0 +1,21 @@
1
+ import { useEnsureRoomContext } from '@/context/room.context';
2
+ import { connectionStateObserver } from '@livekit/components-core';
3
+ import { ConnectionState, type Room } from 'livekit-client';
4
+ import { Observable } from 'rxjs';
5
+ import { computed, type ShallowRef } from 'vue';
6
+ import { useObservableState } from './private/useObservableState';
7
+
8
+ export function useConnectionState(room?: Room): ShallowRef<ConnectionState> {
9
+ const r = useEnsureRoomContext(room);
10
+
11
+ const observable = computed<Observable<ConnectionState>>(
12
+ () => connectionStateObserver(r.value) as unknown as Observable<ConnectionState>,
13
+ );
14
+
15
+ const connectionState = useObservableState({
16
+ observable: observable.value as unknown as Observable<ConnectionState>,
17
+ startWith: r.value.state,
18
+ });
19
+
20
+ return connectionState;
21
+ }
@@ -0,0 +1,56 @@
1
+ import { useEnsureRoomContext } from '@/context/room.context';
2
+ import { setupDataMessageHandler, type ReceivedDataMessage } from '@livekit/components-core';
3
+ import type { DataPublishOptions, RemoteParticipant } from 'livekit-client';
4
+ import type { Observable } from 'rxjs';
5
+ import { computed, toRefs, type ShallowRef } from 'vue';
6
+ import { useObservableState } from './private/useObservableState';
7
+
8
+ export type MessagePayload<T extends string | undefined = undefined> = {
9
+ payload: Uint8Array;
10
+ topic: T;
11
+ from: RemoteParticipant | undefined;
12
+ };
13
+
14
+ export type UseDataChannelReturnType<T extends string | undefined = undefined> = {
15
+ isSending: ShallowRef<boolean>;
16
+ send: ShallowRef<(payload: Uint8Array, options?: DataPublishOptions) => Promise<void>>;
17
+ message: ShallowRef<MessagePayload<T> | undefined>;
18
+ };
19
+
20
+ export function useDataChannel<T extends string>(
21
+ topic: T,
22
+ onMessage?: (msg: ReceivedDataMessage<T>) => void,
23
+ ): UseDataChannelReturnType<T>;
24
+ export function useDataChannel(
25
+ onMessage?: (msg: ReceivedDataMessage) => void,
26
+ ): UseDataChannelReturnType;
27
+ export function useDataChannel<T extends string>(
28
+ topicOrCallback?: T | ((msg: ReceivedDataMessage) => void),
29
+ callback?: (msg: ReceivedDataMessage<T>) => void,
30
+ ): UseDataChannelReturnType {
31
+ const onMessage = typeof topicOrCallback === 'function' ? topicOrCallback : callback;
32
+ const topic = typeof topicOrCallback === 'string' ? topicOrCallback : undefined;
33
+ const room = useEnsureRoomContext();
34
+
35
+ const messageHandler = computed(() => {
36
+ return setupDataMessageHandler(room?.value, topic, onMessage);
37
+ });
38
+
39
+ const { send, messageObservable, isSendingObservable } = toRefs(messageHandler.value);
40
+
41
+ const message = useObservableState({
42
+ observable: messageObservable as unknown as Observable<MessagePayload>,
43
+ startWith: undefined,
44
+ });
45
+
46
+ const isSending = useObservableState({
47
+ observable: isSendingObservable as unknown as Observable<boolean>,
48
+ startWith: false,
49
+ });
50
+
51
+ return {
52
+ message,
53
+ send,
54
+ isSending,
55
+ };
56
+ }
@@ -0,0 +1,28 @@
1
+ import type { DisconnectButtonProps } from '@/components/controls/buttons';
2
+ import { useEnsureRoomContext } from '@/context/room.context';
3
+ import { ConnectionState } from 'livekit-client';
4
+ import { computed, type HTMLAttributes, type ShallowRef } from 'vue';
5
+ import { useConnectionState } from './useConnectionState';
6
+
7
+ export function useDisconnectButton(props: DisconnectButtonProps): {
8
+ buttonProps: ShallowRef<HTMLAttributes>;
9
+ } {
10
+ const room = useEnsureRoomContext();
11
+ const connectionState = useConnectionState(room.value);
12
+
13
+ function disconnect(stopTracks?: boolean) {
14
+ room.value.disconnect(stopTracks);
15
+ }
16
+
17
+ const buttonProps = computed<HTMLAttributes>(() => {
18
+ return {
19
+ ...props,
20
+ onClick: () => disconnect(),
21
+ disabled: connectionState.value === ConnectionState.Disconnected,
22
+ };
23
+ });
24
+
25
+ return {
26
+ buttonProps,
27
+ };
28
+ }
@@ -0,0 +1,28 @@
1
+ import type { TrackReferenceOrPlaceholder } from '@livekit/components-core';
2
+ import { facingModeFromLocalTrack, LocalTrackPublication } from 'livekit-client';
3
+ import { ref, watch, type ShallowRef } from 'vue';
4
+
5
+ export enum FacingMode {
6
+ User = 'user',
7
+ Environment = 'environment',
8
+ Left = 'left',
9
+ Right = 'right',
10
+ Undefined = 'undefined',
11
+ }
12
+
13
+ export function useFacingMode(trackReference: TrackReferenceOrPlaceholder): ShallowRef<FacingMode> {
14
+ const state = ref<FacingMode>(FacingMode.Undefined);
15
+
16
+ watch(trackReference, () => {
17
+ if (trackReference.publication instanceof LocalTrackPublication) {
18
+ const localTrack = trackReference.publication.track;
19
+ if (localTrack) {
20
+ const { facingMode } = facingModeFromLocalTrack(localTrack);
21
+ state.value = FacingMode[facingMode as keyof typeof FacingMode];
22
+ }
23
+ }
24
+ return state.value;
25
+ });
26
+
27
+ return state;
28
+ }
@@ -0,0 +1,38 @@
1
+ import { useMaybeLayoutContext } from '@/context/layout.context';
2
+ import { useEnsureTrackRef } from '@/context/track_reference.context';
3
+ import { isTrackReferencePinned, type TrackReferenceOrPlaceholder } from '@livekit/components-core';
4
+ import { computed, type HTMLAttributes, type ShallowRef } from 'vue';
5
+
6
+ export type UseFocusToggleProps = {
7
+ trackRef?: TrackReferenceOrPlaceholder;
8
+ props: HTMLAttributes;
9
+ };
10
+
11
+ export type UseFocusToggleReturnType = {
12
+ elementProps: ShallowRef<HTMLAttributes>;
13
+ inFocus: ShallowRef<boolean>;
14
+ };
15
+
16
+ export function useFocusToggle({ trackRef, props }: UseFocusToggleProps): UseFocusToggleReturnType {
17
+ const trackReference = useEnsureTrackRef(trackRef);
18
+ const layoutContext = useMaybeLayoutContext();
19
+
20
+ const className = 'lk-focus-toggle-button';
21
+
22
+ const inFocus = computed<boolean>(() => {
23
+ return isTrackReferencePinned(trackReference.value, layoutContext?.value?.pin.state);
24
+ });
25
+
26
+ const elementProps = computed<HTMLAttributes>(() => {
27
+ return {
28
+ ...props,
29
+ class: className,
30
+ 'data-lk-toggle-focused': inFocus.value,
31
+ };
32
+ });
33
+
34
+ return {
35
+ elementProps,
36
+ inFocus,
37
+ };
38
+ }
@@ -0,0 +1,44 @@
1
+ import {
2
+ GRID_LAYOUTS,
3
+ selectGridLayout,
4
+ type GridLayoutDefinition,
5
+ } from '@livekit/components-core';
6
+ import { useElementSize } from '@vueuse/core';
7
+ import { computed, watch, type Ref, type ShallowRef } from 'vue';
8
+
9
+ export type UseGridLayoutReturnType = {
10
+ layout: ShallowRef<GridLayoutDefinition | undefined>;
11
+ containerWidth: ShallowRef<number | undefined>;
12
+ containerHeight: ShallowRef<number | undefined>;
13
+ };
14
+
15
+ export function useGridLayout(
16
+ gridElement: Ref<HTMLDivElement>,
17
+ trackCount: number,
18
+ options: {
19
+ gridLayouts?: GridLayoutDefinition[];
20
+ } = {},
21
+ ): UseGridLayoutReturnType {
22
+ const { width, height } = useElementSize(gridElement);
23
+
24
+ const gridLayouts = computed<GridLayoutDefinition[]>(() => {
25
+ return options.gridLayouts ?? GRID_LAYOUTS;
26
+ });
27
+
28
+ const layout = computed(() => {
29
+ return selectGridLayout(gridLayouts.value, trackCount, width.value, height.value);
30
+ });
31
+
32
+ watch([gridElement, layout], () => {
33
+ if (gridElement.value && layout) {
34
+ gridElement.value.style.setProperty('--lk-col-count', layout.value?.columns.toString());
35
+ gridElement.value.style.setProperty('--lk-row-count', layout.value?.rows.toString());
36
+ }
37
+ });
38
+
39
+ return {
40
+ layout,
41
+ containerWidth: width,
42
+ containerHeight: height,
43
+ };
44
+ }
@@ -0,0 +1,34 @@
1
+ import { useEnsureParticipant } from '@/context/participant.context';
2
+ import { useEnsureRoomContext } from '@/context/room.context';
3
+ import { encryptionStatusObservable } from '@livekit/components-core';
4
+ import type { LocalParticipant, Participant, Room } from 'livekit-client';
5
+ import { Observable } from 'rxjs';
6
+ import { ref, type ShallowRef } from 'vue';
7
+ import { useObservableState } from './private/useObservableState';
8
+
9
+ export type UseIsEncryptedOptions = {
10
+ room?: Room;
11
+ };
12
+
13
+ export type EncryptedObservable = Observable<boolean>;
14
+
15
+ export function useIsEncrypted(
16
+ participant?: Participant,
17
+ options: UseIsEncryptedOptions = {},
18
+ ): ShallowRef<boolean> {
19
+ const p = useEnsureParticipant(participant);
20
+ const room = useEnsureRoomContext(options.room);
21
+
22
+ const observer = ref<EncryptedObservable>(
23
+ encryptionStatusObservable(room.value, p.value) as unknown as EncryptedObservable,
24
+ );
25
+
26
+ const isEncrypted = useObservableState({
27
+ observable: observer.value as unknown as EncryptedObservable,
28
+ startWith: p.value.isLocal
29
+ ? (p.value as LocalParticipant).isE2EEEnabled
30
+ : !!p.value?.isEncrypted,
31
+ });
32
+
33
+ return isEncrypted;
34
+ }
@@ -0,0 +1,56 @@
1
+ import { useEnsureParticipant } from '@/context/participant.context';
2
+ import {
3
+ getTrackReferenceId,
4
+ mutedObserver,
5
+ type TrackReference,
6
+ type TrackReferenceOrPlaceholder,
7
+ type TrackReferencePlaceholder,
8
+ } from '@livekit/components-core';
9
+ import { useSubscription } from '@vueuse/rxjs';
10
+ import type { Participant, Track } from 'livekit-client';
11
+ import { computed, ref, watch, type ShallowRef } from 'vue';
12
+
13
+ export type UseIsMutedOptions = {
14
+ participant?: Participant;
15
+ };
16
+
17
+ export function useIsMuted(trackRef: TrackReferenceOrPlaceholder): ShallowRef<boolean>;
18
+ export function useIsMuted(
19
+ sourceOrTrackRef: TrackReferenceOrPlaceholder | Track.Source,
20
+ options: UseIsMutedOptions = {},
21
+ ): ShallowRef<boolean> {
22
+ const passedParticipant = computed<Participant | undefined>(() =>
23
+ typeof sourceOrTrackRef === 'string' ? options.participant : sourceOrTrackRef.participant,
24
+ );
25
+
26
+ const p = useEnsureParticipant(passedParticipant.value);
27
+
28
+ const trackRef = computed<TrackReference | TrackReferencePlaceholder>(() => {
29
+ const track =
30
+ typeof sourceOrTrackRef === 'string'
31
+ ? { participant: p.value, source: sourceOrTrackRef }
32
+ : sourceOrTrackRef;
33
+
34
+ return track;
35
+ });
36
+
37
+ const isMuted = ref(
38
+ !!(
39
+ trackRef.value.publication?.isMuted ||
40
+ p.value.getTrackPublication(trackRef.value.source)?.isMuted
41
+ ),
42
+ );
43
+
44
+ watch(
45
+ () => getTrackReferenceId(trackRef.value),
46
+ () => {
47
+ useSubscription(
48
+ mutedObserver(trackRef.value).subscribe((muted) => {
49
+ isMuted.value = muted;
50
+ }),
51
+ );
52
+ },
53
+ );
54
+
55
+ return isMuted;
56
+ }
@@ -0,0 +1,30 @@
1
+ import { useEnsureRoomContext } from '@/context/room.context';
2
+ import { recordingStatusObservable } from '@livekit/components-core';
3
+ import type { Room } from 'livekit-client';
4
+ import type { Observable } from 'rxjs';
5
+ import { ref, watch, type ShallowRef } from 'vue';
6
+ import { useObservableState } from './private/useObservableState';
7
+ import { useConnectionState } from './useConnectionState';
8
+
9
+ export type UseIsRecordingObservable = Observable<boolean>;
10
+
11
+ export function useIsRecording(room?: Room): ShallowRef<boolean> {
12
+ const r = useEnsureRoomContext(room);
13
+
14
+ const connectionState = useConnectionState(r.value);
15
+
16
+ const observable = ref<UseIsRecordingObservable>(
17
+ recordingStatusObservable(r.value) as unknown as UseIsRecordingObservable,
18
+ );
19
+
20
+ const isRecording = useObservableState({
21
+ observable: observable.value as unknown as UseIsRecordingObservable,
22
+ startWith: r.value.isRecording,
23
+ });
24
+
25
+ watch([connectionState, r], () => {
26
+ observable.value = recordingStatusObservable(r.value) as unknown as UseIsRecordingObservable;
27
+ });
28
+
29
+ return isRecording;
30
+ }
@@ -0,0 +1,23 @@
1
+ import { useEnsureParticipant } from '@/context/participant.context';
2
+ import { createIsSpeakingObserver } from '@livekit/components-core';
3
+ import type { Participant } from 'livekit-client';
4
+ import type { Observable } from 'rxjs';
5
+ import { computed, type ShallowRef } from 'vue';
6
+ import { useObservableState } from './private/useObservableState';
7
+
8
+ export type IsSpeakingObservable = Observable<boolean>;
9
+
10
+ export function useIsSpeaking(participant?: Participant): ShallowRef<boolean> {
11
+ const p = useEnsureParticipant(participant);
12
+
13
+ const observable = computed<IsSpeakingObservable>(
14
+ () => createIsSpeakingObserver(p.value) as unknown as IsSpeakingObservable,
15
+ );
16
+
17
+ const isSpeaking = useObservableState({
18
+ observable: observable.value as unknown as IsSpeakingObservable,
19
+ startWith: p.value.isSpeaking,
20
+ });
21
+
22
+ return isSpeaking;
23
+ }
@@ -0,0 +1,219 @@
1
+ import { useRoomContext } from '@/context/room.context';
2
+ import type { LiveKitRoomProps } from '@/types/livekit_room.types';
3
+ import { roomOptionsStringifyReplacer } from '@/utils/room.utils';
4
+ import { DisconnectReason, MediaDeviceFailure, Room, RoomEvent } from 'livekit-client';
5
+ import {
6
+ computed,
7
+ onBeforeUnmount,
8
+ onMounted,
9
+ onWatcherCleanup,
10
+ ref,
11
+ toRefs,
12
+ watch,
13
+ type HTMLAttributes,
14
+ type Ref,
15
+ type ShallowRef,
16
+ } from 'vue';
17
+
18
+ export type UseLiveKitRoomReturn = {
19
+ room: ShallowRef<Room | undefined>;
20
+ elementProps: ShallowRef<HTMLAttributes>;
21
+ };
22
+
23
+ const defaultRoomProps: Partial<LiveKitRoomProps> = {
24
+ connect: true,
25
+ audio: false,
26
+ video: false,
27
+ };
28
+
29
+ export function useLiveKitRoom(props: LiveKitRoomProps): UseLiveKitRoomReturn {
30
+ const {
31
+ token,
32
+ serverUrl,
33
+ options,
34
+ room: passedRoom,
35
+ connectOptions,
36
+ connect,
37
+ audio,
38
+ video,
39
+ screen,
40
+ onConnected,
41
+ onDisconnected,
42
+ onError,
43
+ onMediaDeviceFailure,
44
+ onEncryptionError,
45
+ simulateParticipants,
46
+ htmlProps,
47
+ } = toRefs({ ...defaultRoomProps, ...props });
48
+
49
+ const shouldConnect = ref(connect?.value ?? false);
50
+ const room = ref<Room | undefined>(passedRoom?.value ?? useRoomContext()?.value);
51
+
52
+ const elementProps = computed<HTMLAttributes>(() => {
53
+ return {
54
+ ...htmlProps?.value,
55
+ class: 'lk-room-container',
56
+ };
57
+ });
58
+
59
+ function onSignalConnected() {
60
+ const localP = room.value?.localParticipant;
61
+
62
+ console.debug('trying to publish local tracks');
63
+ Promise.all([
64
+ localP?.setMicrophoneEnabled(
65
+ !!audio?.value,
66
+ typeof audio?.value !== 'boolean' ? audio?.value : undefined,
67
+ ),
68
+ localP?.setCameraEnabled(
69
+ !!video?.value,
70
+ typeof video?.value !== 'boolean' ? video?.value : undefined,
71
+ ),
72
+ localP?.setScreenShareEnabled(
73
+ !!screen?.value,
74
+ typeof screen?.value !== 'boolean' ? screen?.value : undefined,
75
+ ),
76
+ ]).catch((e) => {
77
+ console.warn(e);
78
+ onError?.value?.(e as Error);
79
+ });
80
+ }
81
+
82
+ function handleMediaDeviceError(e: Error) {
83
+ const mediaDeviceFailure = MediaDeviceFailure.getFailure(e);
84
+ onMediaDeviceFailure?.value?.(mediaDeviceFailure);
85
+ }
86
+ function handleEncryptionError(e: Error) {
87
+ onEncryptionError?.value?.(e);
88
+ }
89
+
90
+ function handleDisconnected(reason?: DisconnectReason) {
91
+ onDisconnected?.value?.(reason);
92
+ }
93
+
94
+ function handleConnected() {
95
+ onConnected?.value?.();
96
+ }
97
+
98
+ watch(
99
+ [passedRoom, options, roomOptionsStringifyReplacer],
100
+ () => {
101
+ room.value = passedRoom?.value ?? new Room(options?.value);
102
+ },
103
+ {
104
+ deep: true,
105
+ immediate: true,
106
+ },
107
+ );
108
+
109
+ watch(
110
+ [
111
+ room,
112
+ audio,
113
+ video,
114
+ screen,
115
+ onError,
116
+ onEncryptionError,
117
+ onMediaDeviceFailure,
118
+ onConnected,
119
+ onDisconnected,
120
+ ],
121
+ () => {
122
+ if (!room.value) {
123
+ return;
124
+ }
125
+
126
+ room.value
127
+ .on(RoomEvent.SignalConnected, onSignalConnected)
128
+ .on(RoomEvent.MediaDevicesError, handleMediaDeviceError)
129
+ .on(RoomEvent.EncryptionError, handleEncryptionError)
130
+ .on(RoomEvent.Disconnected, handleDisconnected)
131
+ .on(RoomEvent.Connected, handleConnected);
132
+
133
+ onWatcherCleanup(() => {
134
+ if (!room.value) {
135
+ return;
136
+ }
137
+
138
+ room.value
139
+ .off(RoomEvent.SignalConnected, onSignalConnected)
140
+ .off(RoomEvent.MediaDevicesError, handleMediaDeviceError)
141
+ .off(RoomEvent.EncryptionError, handleEncryptionError)
142
+ .off(RoomEvent.Disconnected, handleDisconnected)
143
+ .off(RoomEvent.Connected, handleConnected);
144
+ });
145
+ },
146
+ {
147
+ deep: true,
148
+ },
149
+ );
150
+
151
+ watch(
152
+ [connect, token, connectOptions, room, onError, serverUrl, simulateParticipants],
153
+ () => {
154
+ if (!room.value) return;
155
+
156
+ if (simulateParticipants?.value) {
157
+ room.value.simulateParticipants({
158
+ participants: {
159
+ count: simulateParticipants.value,
160
+ },
161
+ publish: {
162
+ audio: true,
163
+ useRealTracks: true,
164
+ },
165
+ });
166
+ return;
167
+ }
168
+
169
+ if (connect?.value) {
170
+ shouldConnect.value = true;
171
+
172
+ console.debug('connecting');
173
+
174
+ if (!token.value) {
175
+ console.debug('no token yet');
176
+ return;
177
+ }
178
+
179
+ if (!serverUrl.value) {
180
+ console.warn('no livekit url provided');
181
+ onError?.value?.(Error('no livekit url provided'));
182
+ return;
183
+ }
184
+
185
+ room.value.connect(serverUrl.value, token.value, connectOptions?.value).catch((e) => {
186
+ console.warn(e);
187
+ if (shouldConnect.value === true) {
188
+ onError?.value?.(e as Error);
189
+ }
190
+ });
191
+ } else {
192
+ console.debug('disconnecting because connect is false');
193
+ shouldConnect.value = false;
194
+ room.value.disconnect();
195
+ }
196
+ },
197
+ { deep: true },
198
+ );
199
+
200
+ onMounted(() => {
201
+ if (options?.value && passedRoom) {
202
+ console.warn(
203
+ 'when using a manually created room, the options object will be ignored. set the desired options directly when creating the room instead.',
204
+ );
205
+ }
206
+ });
207
+
208
+ onBeforeUnmount(() => {
209
+ if (room.value) {
210
+ console.info('disconnecting before unmounting');
211
+ room.value.disconnect();
212
+ }
213
+ });
214
+
215
+ return {
216
+ room: room as Ref<Room | undefined>,
217
+ elementProps,
218
+ };
219
+ }