Skip to content

Commit

Permalink
make typescript strict error checker and eslint happy
Browse files Browse the repository at this point in the history
  • Loading branch information
justjanne committed Oct 17, 2022
1 parent b507b12 commit d247b24
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 54 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
8 changes: 5 additions & 3 deletions src/models/event-timeline-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ limitations under the License.
* @module models/event-timeline-set
*/

import { Optional } from "matrix-events-sdk";

import { EventTimeline, IAddEventOptions } from "./event-timeline";
import { MatrixEvent } from "./event";
import { logger } from '../logger';
Expand Down Expand Up @@ -290,8 +292,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: Optional<string>): EventTimeline | null {
if (eventId === null || eventId === undefined) { return null; }
const res = this._eventIdToTimeline.get(eventId);
return (res === undefined) ? null : res;
}
Expand Down Expand Up @@ -352,7 +354,7 @@ export class EventTimelineSet extends TypedEventEmitter<EmittedEvents, EventTime
events: MatrixEvent[],
toStartOfTimeline: boolean,
timeline: EventTimeline,
paginationToken: string,
paginationToken: Optional<string>,
): void {
if (!timeline) {
throw new Error(
Expand Down
10 changes: 5 additions & 5 deletions src/models/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,8 @@ export class MatrixEvent extends TypedEventEmitter<EmittedEvents, MatrixEventHan
* @experimental
* A reference to the thread this event belongs to
*/
private thread: Thread = null;
private threadId: string;
private thread: Thread | null = null;
private threadId: string | null;

/* Set an approximate timestamp for the event relative the local clock.
* This will inherently be approximate because it doesn't take into account
Expand Down Expand Up @@ -1548,7 +1548,7 @@ export class MatrixEvent extends TypedEventEmitter<EmittedEvents, MatrixEventHan
this.reEmitter.stopReEmitting(this.thread, [ThreadEvent.Update]);
}
this.thread = thread;
this.setThreadId(thread?.id);
this.setThreadId(thread?.id ?? null);
if (thread) {
this.reEmitter.reEmit(thread, [ThreadEvent.Update]);
}
Expand All @@ -1558,10 +1558,10 @@ export class MatrixEvent extends TypedEventEmitter<EmittedEvents, MatrixEventHan
* @experimental
*/
public getThread(): Thread | undefined {
return this.thread;
return this.thread ?? undefined;
}

public setThreadId(threadId: string): void {
public setThreadId(threadId: string | null): void {
this.threadId = threadId;
}
}
Expand Down
52 changes: 28 additions & 24 deletions src/models/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export class Room extends ReadReceipt<EmittedEvents, RoomEventHandlerMap> {
* @experimental
*/
public threads = new Map<string, Thread>();
public lastThread: Thread;
public lastThread: Thread | null = null;

/**
* A mapping of eventId to all visibility changes to apply
Expand Down Expand Up @@ -1016,7 +1016,8 @@ export class Room extends ReadReceipt<EmittedEvents, RoomEventHandlerMap> {
public resetLiveTimeline(backPaginationToken?: string | null, forwardPaginationToken?: string | null): void {
for (let i = 0; i < this.timelineSets.length; i++) {
this.timelineSets[i].resetLiveTimeline(
backPaginationToken, forwardPaginationToken,
backPaginationToken ?? undefined,
forwardPaginationToken ?? undefined,
);
}

Expand Down Expand Up @@ -1860,9 +1861,7 @@ export class Room extends ReadReceipt<EmittedEvents, 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 @@ -1989,9 +1988,11 @@ export class Room extends ReadReceipt<EmittedEvents, 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 @@ -2000,18 +2001,20 @@ export class Room extends ReadReceipt<EmittedEvents, 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 @@ -2052,15 +2055,16 @@ export class Room extends ReadReceipt<EmittedEvents, 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
40 changes: 32 additions & 8 deletions src/models/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ export class Thread extends ReadReceipt<EmittedEvents, EventHandlerMap> {
public readonly room: Room;
public readonly client: MatrixClient;

public initialEventsFetched = !Thread.hasServerSideSupport;

constructor(
public readonly id: string,
public rootEvent: MatrixEvent | undefined,
Expand Down Expand Up @@ -232,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 @@ -242,14 +247,15 @@ export class Thread extends ReadReceipt<EmittedEvents, EventHandlerMap> {

this.client.decryptEventIfNeeded(event, {});
} else if (!toStartOfTimeline &&
event.localTimestamp > this.lastReply()?.localTimestamp
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 @@ -265,12 +271,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 @@ -283,13 +291,29 @@ 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);
await this.processEvent(this.lastEvent);
}

if (!this.initialEventsFetched) {
this.initialEventsFetched = true;
// fetch initial event to allow proper pagination
try {
// if the thread has regular events, this will just load the last reply.
// if the thread is newly created, this will load the root event.
await this.client.paginateEventTimeline(this.liveTimeline, { backwards: true, limit: 1 });
// just to make sure that, if we've created a timeline window for this thread before the thread itself
// existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.
this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);
} catch (e) {
logger.error("Failed to load start of newly created thread: ", e);
this.initialEventsFetched = false;
}
}

this.emit(ThreadEvent.Update, this);
}

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 d247b24

Please sign in to comment.