import { TypingSetEvent, TypingSetEventType } from './events.js'; import { Logger } from './logger.js'; import { InternalTypingOptions } from './room-options.js'; import { Subscription } from './subscription.js'; import { default as EventEmitter } from './utils/event-emitter.js'; import * as Ably from '@ably/pubsub-core'; /** * Represents a user in the set of currently typing users, with associated metadata. */ export interface TypingMember { /** The client ID of the typing user. */ clientId: string; /** The user claim attached to this user's typing event, if any. */ userClaim?: string; } /** * This interface is used to interact with typing in a chat room including subscribing to typing events and * fetching the current set of typing clients. * * Get an instance via {@link Room.typing}. */ export interface Typing { /** * Subscribes to typing events from users in the chat room. * * Receives updates whenever a user starts or stops typing, providing real-time * feedback about who is currently composing messages. The subscription emits * events containing the current set of typing users and details about what changed. * * **Note**: The room must be attached to receive typing events. * @param listener - Callback invoked when the typing state changes * @returns Subscription object with an unsubscribe method * @example * ```typescript * import * as Ably from '@ably/pubsub-device'; * import { ChatClient, TypingSetEvent } from '@ably/chat'; * * const chatClient: ChatClient; // existing ChatClient instance * * // Get a room with default options * const room = await chatClient.rooms.get('team-chat'); * * // Subscribe to typing events * const subscription = room.typing.subscribe((event: TypingSetEvent) => { * const { currentlyTyping, change } = event; * * // Display who is currently typing * if (currentlyTyping.size === 0) { * hideTypingIndicator(); * } else if (currentlyTyping.size === 1) { * const [typingUser] = Array.from(currentlyTyping); * showTypingIndicator(`${typingUser} is typing...`); * } else if (currentlyTyping.size === 2) { * const users = Array.from(currentlyTyping); * showTypingIndicator(`${users[0]} and ${users[1]} are typing...`); * } else { * showTypingIndicator(`${currentlyTyping.size} people are typing...`); * } * }); * * // Attach to the room to start receiving events * await room.attach(); * * // Later, unsubscribe when done * subscription.unsubscribe(); * ``` */ subscribe(listener: TypingListener): Subscription; /** * Gets the current set of users who are typing. * * Returns a Set containing the client IDs of all users currently typing in the room. * This provides a snapshot of the typing state at the time of the call. * @deprecated Use {@link Typing.currentTypers | currentTypers} instead, which includes metadata such as user claims. * @returns Set of client IDs currently typing * @example * ```typescript * import * as Ably from '@ably/pubsub-device'; * import { ChatClient } from '@ably/chat'; * * const chatClient: ChatClient; // existing ChatClient instance * * // Get a room with default options * const room = await chatClient.rooms.get('support-chat'); * * // Attach to the room to start receiving events * await room.attach(); * * // Fetch the current cached set of typing users * const typingUsers = room.typing.current; * * console.log(`${typingUsers.size} users are typing`); * * if (typingUsers.has('agent-001')) { * console.log('Support agent is typing a response...'); * } * ``` */ get current(): Set; /** * Gets the current set of users who are typing, with associated metadata. * * Returns an array of {@link TypingMember} objects containing the client IDs and * user claims of all users currently typing in the room. * @returns Array of {@link TypingMember} objects for users currently typing */ get currentTypers(): TypingMember[]; /** * Sends a typing started event to notify other users that the current user is typing. * * Events are throttled according to the `heartbeatThrottleMs` room option to prevent * excessive network traffic. If called within the throttle interval, the operation * becomes a no-op. Multiple rapid calls are serialized to maintain consistency. * * **Note**: * - The connection must be in the `connected` state. * - Calls to `keystroke()` and `stop()` are serialized and resolve in order. * - The most recent operation always determines the final typing state. * - The room must be attached to send typing events. * @returns Promise that resolves when the typing event has been sent, or rejects with: * - {@link ErrorCode.Disconnected} if not connected * - {@link ErrorCode.OperationSerializationFailed} if mutex acquisition fails * - {@link Ably.ErrorInfo} if the operation fails to send the event * @example * ```typescript * import * as Ably from '@ably/pubsub-device'; * import { ChatClient } from '@ably/chat'; * * const chatClient: ChatClient; // existing ChatClient instance * * // Get a room with default options and attach to it * const room = await chatClient.rooms.get('project-discussion'); * await room.attach(); * * try { * await room.typing.keystroke(); * } catch (error) { * console.error('Typing indicator error:', error); * } * ``` */ keystroke(): Promise; /** * Sends a typing stopped event to notify other users that the current user has stopped typing. * * If the user is not currently typing, this operation is a no-op. Multiple rapid calls * are serialized to maintain consistency, with the most recent operation determining * the final state. * * **Note**: * - The connection must be in the `connected` state. * - Calls to `keystroke()` and `stop()` are serialized and resolve in order. * - The room must be attached to send typing events. * @returns Promise that resolves when the stop event has been sent, or rejects with: * - {@link ErrorCode.Disconnected} if not connected * - {@link ErrorCode.OperationSerializationFailed} if mutex acquisition fails * - {@link Ably.ErrorInfo} if the operation fails to send the event * @example * ```typescript * import * as Ably from '@ably/pubsub-device'; * import { ChatClient } from '@ably/chat'; * * const chatClient: ChatClient; // existing ChatClient instance * * // Get a room with default options and attach to it * const room = await chatClient.rooms.get('customer-support'); * await room.attach(); * * // Start typing in the room * try { * await room.typing.keystroke(); * } catch (error) { * console.error('Typing indicator error:', error); * } * * // User sends a message, or deletes their draft, etc. * * // Stop typing in the room * try { * await room.typing.stop(); * } catch (error) { * console.error('Failed to stop typing:', error); * } * ``` */ stop(): Promise; } /** * A listener which listens for typing events. * @param event The typing event. */ export type TypingListener = (event: TypingSetEvent) => void; /** * Represents the typing events mapped to their respective event payloads. */ interface TypingEventsMap { [TypingSetEventType.SetChanged]: TypingSetEvent; } /** * @inheritDoc */ export declare class DefaultTyping extends EventEmitter implements Typing { private readonly _channel; private readonly _connection; private readonly _logger; private readonly _heartbeatThrottleMs; private readonly _timeoutMs; private _heartbeatTimerId; private readonly _currentlyTyping; private readonly _mutex; private readonly _unsubscribeTypingEvents; /** * Constructs a new `DefaultTyping` instance. * @param options The options for typing in the room. * @param connection The connection instance. * @param channel The channel for the room. * @param logger An instance of the Logger. */ constructor(options: InternalTypingOptions, connection: Ably.Connection, channel: Ably.RealtimeChannel, logger: Logger); /** * Clears all typing states. * This includes clearing all timeouts and the currently typing map. */ private _clearAllTypingStates; /** * Clears the heartbeat timer. */ private _clearHeartbeatTimer; /** * Clears the currently typing store and removes all timeouts for associated clients. */ private _clearCurrentlyTyping; /** * CHA-T16 * @inheritDoc */ get current(): Set; /** * @inheritDoc */ get currentTypers(): TypingMember[]; /** * @inheritDoc */ get channel(): Ably.RealtimeChannel; /** * Start the heartbeat timer. This will expire after the configured interval. */ private _startHeartbeatTimer; /** * @inheritDoc */ keystroke(): Promise; /** * @inheritDoc */ stop(): Promise; /** * @inheritDoc */ subscribe(listener: TypingListener): Subscription; /** * @inheritDoc */ dispose(): Promise; /** * Update the currently typing users. This method is called when a typing event is received. * It will also acquire a mutex to ensure that the currentlyTyping state is updated safely. * @param clientId The client ID of the user. * @param event The typing event. * @param userClaim The user claim from the typing event, if any. */ private _updateCurrentlyTyping; /** * Builds an array of TypingMember objects from the current typing state. * @returns Array of {@link TypingMember} objects for users currently typing */ private _buildCurrentTypers; /** * Starts a new inactivity timer for the client. * This timer will expire after the configured timeout, * which is the sum of the heartbeat interval and the inactivity timeout. * @param clientId The client ID for which to start the timer. * @returns The timeout ID for the new timer. */ private _startNewClientInactivityTimer; /** * Handles logic for TypingEventType.Started, including starting a new timeout or resetting an existing one. * @param clientId The client ID that started typing. * @param userClaim The user claim from the typing event, if any. */ private _handleTypingStart; /** * Handles logic for TypingEventType.Stopped, including clearing the timeout for the client. * @param clientId The client ID that stopped typing. * @param userClaim The user claim from the stop event, if any. */ private _handleTypingStop; /** * Subscribe to internal events. This listens to events and converts them into typing updates, with validation. * @param inbound The inbound message containing typing event data. */ private _internalSubscribeToEvents; get heartbeatThrottleMs(): number; get hasHeartbeatTimer(): boolean; } export {};