Skip to content

Commit

Permalink
make typescript-strict checker a bit happier
Browse files Browse the repository at this point in the history
  • Loading branch information
justjanne committed Oct 17, 2022
1 parent 21f777c commit a230981
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 51 deletions.
27 changes: 15 additions & 12 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5243,6 +5243,10 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
throw new Error("could not get thread timeline: no client support");
}

if (!timelineSet.room) {
throw new Error("could not get thread timeline: not a room timeline");
}

if (!timelineSet.thread) {
throw new Error("could not get thread timeline: not a thread timeline");
}
Expand Down Expand Up @@ -5277,14 +5281,14 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
}

const thread = timelineSet.thread;
const resOlder = await this.fetchRelations(
const resOlder: IRelationsResponse = await this.fetchRelations(
timelineSet.room.roomId,
thread.id,
THREAD_RELATION_TYPE.name,
null,
{ dir: Direction.Backward, from: res.start },
);
const resNewer = await this.fetchRelations(
const resNewer: IRelationsResponse = await this.fetchRelations(
timelineSet.room.roomId,
thread.id,
THREAD_RELATION_TYPE.name,
Expand Down Expand Up @@ -5339,10 +5343,10 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
null,
{ dir: Direction.Backward, from: res.start },
);
const eventsNewer = [];
const eventsNewer: IEvent[] = [];
let nextBatch: Optional<string> = res.end;
while (nextBatch) {
const resNewer = await this.fetchRelations(
const resNewer: IRelationsResponse = await this.fetchRelations(
timelineSet.room.roomId,
thread.id,
THREAD_RELATION_TYPE.name,
Expand Down Expand Up @@ -5532,7 +5536,6 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
// create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,
// so the timelineFilter doesn't get written into it below
filter = {
...filter,
...Filter.LAZY_LOADING_MESSAGES_FILTER,
};
}
Expand Down Expand Up @@ -5579,7 +5582,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
const isNotifTimeline = (eventTimeline.getTimelineSet() === this.notifTimelineSet);
const room = this.getRoom(eventTimeline.getRoomId());
const isThreadListTimeline = eventTimeline.getTimelineSet().isThreadTimeline;
const isThreadTimeline = (eventTimeline.getTimelineSet().thread);
const thread = eventTimeline.getTimelineSet().thread;

// TODO: we should implement a backoff (as per scrollback()) to deal more
// nicely with HTTP errors.
Expand Down Expand Up @@ -5690,18 +5693,18 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
eventTimeline.paginationRequests[dir] = null;
});
eventTimeline.paginationRequests[dir] = promise;
} else if (isThreadTimeline) {
} else if (thread) {
const room = this.getRoom(eventTimeline.getRoomId());
if (!room) {
throw new Error("Unknown room " + eventTimeline.getRoomId());
}

promise = this.fetchRelations(
eventTimeline.getRoomId(),
eventTimeline.getTimelineSet().thread?.id,
thread.id,
THREAD_RELATION_TYPE.name,
null,
{ dir, limit: opts.limit, from: token },
{ dir, limit: opts.limit, from: token ?? undefined },
).then(async (res) => {
const mapper = this.getEventMapper();
const matrixEvents = res.chunk.map(mapper);
Expand Down Expand Up @@ -6933,12 +6936,12 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
eventType?: EventType | string | null,
opts: IRelationsRequestOpts = { dir: Direction.Backward },
): Promise<{
originalEvent: MatrixEvent;
originalEvent: MatrixEvent | null;
events: MatrixEvent[];
nextBatch?: string;
prevBatch?: string;
}> {
const fetchedEventType = this.getEncryptedIfNeededEventType(roomId, eventType);
const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null;
const result = await this.fetchRelations(
roomId,
eventId,
Expand All @@ -6962,7 +6965,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
events = events.filter(e => e.getSender() === originalEvent.getSender());
}
return {
originalEvent,
originalEvent: originalEvent ?? null,
events,
nextBatch: result.next_batch,
prevBatch: result.prev_batch,
Expand Down
4 changes: 2 additions & 2 deletions src/models/event-timeline-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,8 +297,8 @@ export class EventTimelineSet extends TypedEventEmitter<EmittedEvents, EventTime
* @return {?module:models/event-timeline~EventTimeline} timeline containing
* the given event, or null if unknown
*/
public getTimelineForEvent(eventId: string | null): EventTimeline | null {
if (eventId === null) { return null; }
public getTimelineForEvent(eventId?: string): EventTimeline | null {
if (eventId === null || eventId === undefined) { return null; }
const res = this._eventIdToTimeline.get(eventId);
return (res === undefined) ? null : res;
}
Expand Down
4 changes: 2 additions & 2 deletions src/models/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1543,7 +1543,7 @@ export class MatrixEvent extends TypedEventEmitter<MatrixEventEmittedEvents, Mat
/**
* @experimental
*/
public setThread(thread: Thread | null): void {
public setThread(thread?: Thread): void {
if (this.thread) {
this.reEmitter.stopReEmitting(this.thread, [ThreadEvent.Update]);
}
Expand All @@ -1561,7 +1561,7 @@ export class MatrixEvent extends TypedEventEmitter<MatrixEventEmittedEvents, Mat
return this.thread;
}

public setThreadId(threadId: string): void {
public setThreadId(threadId?: string): void {
this.threadId = threadId;
}
}
Expand Down
47 changes: 25 additions & 22 deletions src/models/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1828,9 +1828,7 @@ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
}

private onThreadNewReply(thread: Thread): void {
if (thread.length && thread.rootEvent) {
this.updateThreadRootEvents(thread, false);
}
this.updateThreadRootEvents(thread, false);
}

private onThreadDelete(thread: Thread): void {
Expand Down Expand Up @@ -1957,9 +1955,11 @@ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
}

private updateThreadRootEvents = (thread: Thread, toStartOfTimeline: boolean) => {
this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline);
if (thread.hasCurrentUserParticipated) {
this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline);
if (thread.length) {
this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline);
if (thread.hasCurrentUserParticipated) {
this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline);
}
}
};

Expand All @@ -1968,18 +1968,20 @@ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
thread: Thread,
toStartOfTimeline: boolean,
) => {
if (Thread.hasServerSideSupport) {
timelineSet.addLiveEvent(thread.rootEvent, {
duplicateStrategy: DuplicateStrategy.Replace,
fromCache: false,
roomState: this.currentState,
});
} else {
timelineSet.addEventToTimeline(
thread.rootEvent,
timelineSet.getLiveTimeline(),
{ toStartOfTimeline },
);
if (timelineSet && thread.rootEvent) {
if (Thread.hasServerSideSupport) {
timelineSet.addLiveEvent(thread.rootEvent, {
duplicateStrategy: DuplicateStrategy.Replace,
fromCache: false,
roomState: this.currentState,
});
} else {
timelineSet.addEventToTimeline(
thread.rootEvent,
timelineSet.getLiveTimeline(),
{ toStartOfTimeline },
);
}
}
};

Expand Down Expand Up @@ -2020,15 +2022,16 @@ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
RoomEvent.Timeline,
RoomEvent.TimelineReset,
]);
const isNewer = this.lastThread?.rootEvent
&& rootEvent?.localTimestamp
&& this.lastThread.rootEvent?.localTimestamp < rootEvent?.localTimestamp;

if (!this.lastThread || this.lastThread.rootEvent?.localTimestamp < rootEvent?.localTimestamp) {
if (!this.lastThread || isNewer) {
this.lastThread = thread;
}

if (this.threadsReady) {
if (thread.length && thread.rootEvent) {
this.updateThreadRootEvents(thread, toStartOfTimeline);
}
this.updateThreadRootEvents(thread, toStartOfTimeline);
}

this.emit(ThreadEvent.New, thread, toStartOfTimeline);
Expand Down
24 changes: 13 additions & 11 deletions src/models/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ export class Thread extends ReadReceipt<EmittedEvents, EventHandlerMap> {
public async addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit = true): Promise<void> {
this.setEventMetadata(event);

const lastReply = this.lastReply();
const isNewestReply = !lastReply || event.localTimestamp > lastReply?.localTimestamp;

// Add all incoming events to the thread's timeline set when there's no server support
if (!Thread.hasServerSideSupport) {
// all the relevant membership info to hydrate events with a sender
Expand All @@ -243,16 +246,13 @@ export class Thread extends ReadReceipt<EmittedEvents, EventHandlerMap> {
this.addEventToTimeline(event, toStartOfTimeline);

this.client.decryptEventIfNeeded(event, {});
} else if (!toStartOfTimeline &&
this.initialEventsFetched &&
event.localTimestamp > this.lastReply()?.localTimestamp
) {
} else if (!toStartOfTimeline && this.initialEventsFetched && isNewestReply) {
await this.fetchEditsWhereNeeded(event);
this.addEventToTimeline(event, false);
} else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {
// Apply annotations and replace relations to the relations of the timeline only
this.timelineSet.relations.aggregateParentEvent(event);
this.timelineSet.relations.aggregateChildEvent(event, this.timelineSet);
this.timelineSet.relations?.aggregateParentEvent(event);
this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);
return;
}

Expand All @@ -268,12 +268,14 @@ export class Thread extends ReadReceipt<EmittedEvents, EventHandlerMap> {
}
}

public async processEvent(event: MatrixEvent): Promise<void> {
this.setEventMetadata(event);
await this.fetchEditsWhereNeeded(event);
public async processEvent(event: Optional<MatrixEvent>): Promise<void> {
if (event) {
this.setEventMetadata(event);
await this.fetchEditsWhereNeeded(event);
}
}

private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship {
private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship | undefined {
return rootEvent?.getServerAggregatedRelation<IThreadBundledRelationship>(THREAD_RELATION_TYPE.name);
}

Expand All @@ -286,7 +288,7 @@ export class Thread extends ReadReceipt<EmittedEvents, EventHandlerMap> {

if (Thread.hasServerSideSupport && bundledRelationship) {
this.replyCount = bundledRelationship.count;
this._currentUserParticipated = bundledRelationship.current_user_participated;
this._currentUserParticipated = bundledRelationship.current_user_participated ?? false;

const mapper = this.client.getEventMapper();
this.lastEvent = mapper(bundledRelationship.latest_event);
Expand Down
9 changes: 7 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ limitations under the License.

import unhomoglyph from "unhomoglyph";
import promiseRetry from "p-retry";
import { Optional } from "matrix-events-sdk";

import type * as NodeCrypto from "crypto";
import { MatrixEvent } from "./models/event";
Expand Down Expand Up @@ -123,13 +124,17 @@ export function decodeParams(query: string): Record<string, string | string[]> {
* variables with. E.g. { "$bar": "baz" }.
* @return {string} The result of replacing all template variables e.g. '/foo/baz'.
*/
export function encodeUri(pathTemplate: string, variables: Record<string, string>): string {
export function encodeUri(pathTemplate: string, variables: Record<string, Optional<string>>): string {
for (const key in variables) {
if (!variables.hasOwnProperty(key)) {
continue;
}
const value = variables[key];
if (value === undefined || value === null) {
continue;
}
pathTemplate = pathTemplate.replace(
key, encodeURIComponent(variables[key]),
key, encodeURIComponent(value),
);
}
return pathTemplate;
Expand Down

0 comments on commit a230981

Please sign in to comment.