Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Improve code-splitting of highlight.js and maplibre-gs libs (#12349)
Browse files Browse the repository at this point in the history
* Dynamic import anything that touches maplibre-gs

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Dynamic import anything that touches highlight.js

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Fix types

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Fix tests

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

---------

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
  • Loading branch information
t3chguy authored Mar 20, 2024
1 parent 79c50db commit 4a05de4
Show file tree
Hide file tree
Showing 17 changed files with 186 additions and 64 deletions.
2 changes: 1 addition & 1 deletion src/components/views/beacon/BeaconMarker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { Beacon, BeaconEvent, LocationAssetType } from "matrix-js-sdk/src/matrix

import MatrixClientContext from "../../../contexts/MatrixClientContext";
import { useEventEmitterState } from "../../../hooks/useEventEmitter";
import SmartMarker from "../location/SmartMarker";
import { SmartMarker } from "../location";

interface Props {
map: maplibregl.Map;
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/beacon/BeaconViewDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import MapFallback from "../location/MapFallback";
import { MapError } from "../location/MapError";
import { LocationShareError } from "../../../utils/location";

interface IProps {
export interface IProps {
roomId: Room["roomId"];
matrixClient: MatrixClient;
// open the map centered on this beacon's location
Expand Down
31 changes: 31 additions & 0 deletions src/components/views/beacon/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
Copyright 2024 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Exports beacon components which touch maplibre-gs wrapped in React Suspense to enable code splitting

import React, { ComponentProps, lazy, Suspense } from "react";

import Spinner from "../elements/Spinner";

const BeaconViewDialogComponent = lazy(() => import("./BeaconViewDialog"));

export function BeaconViewDialog(props: ComponentProps<typeof BeaconViewDialogComponent>): JSX.Element {
return (
<Suspense fallback={<Spinner />}>
<BeaconViewDialogComponent {...props} />
</Suspense>
);
}
27 changes: 14 additions & 13 deletions src/components/views/elements/SyntaxHighlight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,23 @@ limitations under the License.
*/

import React from "react";
import hljs from "highlight.js";

interface IProps {
import { useAsyncMemo } from "../../../hooks/useAsyncMemo";

interface Props {
language?: string;
children: string;
}

export default class SyntaxHighlight extends React.PureComponent<IProps> {
public render(): React.ReactNode {
const { children: content, language } = this.props;
const highlighted = language ? hljs.highlight(content, { language }) : hljs.highlightAuto(content);

return (
<pre className={`mx_SyntaxHighlight hljs language-${highlighted.language}`}>
<code dangerouslySetInnerHTML={{ __html: highlighted.value }} />
</pre>
);
}
export default function SyntaxHighlight({ children, language }: Props): JSX.Element {
const highlighted = useAsyncMemo(async () => {
const { default: highlight } = await import("highlight.js");
return language ? highlight.highlight(children, { language }) : highlight.highlightAuto(children);
}, [language, children]);

return (
<pre className={`mx_SyntaxHighlight hljs language-${highlighted?.language}`}>
{highlighted ? <code dangerouslySetInnerHTML={{ __html: highlighted.value }} /> : children}
</pre>
);
}
2 changes: 1 addition & 1 deletion src/components/views/location/LocationButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { aboveLeftOf, useContextMenu, MenuProps } from "../../structures/Context
import { OverflowMenuContext } from "../rooms/MessageComposerButtons";
import LocationShareMenu from "./LocationShareMenu";

interface IProps {
export interface IProps {
roomId: string;
sender: RoomMember;
menuPosition?: MenuProps;
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/location/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ const onGeolocateError = (e: GeolocationPositionError): void => {
});
};

interface MapProps {
export interface MapProps {
id: string;
interactive?: boolean;
/**
Expand Down
5 changes: 3 additions & 2 deletions src/components/views/location/SmartMarker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import React, { ReactNode, useCallback, useEffect, useState } from "react";
import * as maplibregl from "maplibre-gl";
import { RoomMember } from "matrix-js-sdk/src/matrix";

import { createMarker, parseGeoUri } from "../../../utils/location";
import { parseGeoUri } from "../../../utils/location";
import { createMarker } from "../../../utils/location/map";
import Marker from "./Marker";

const useMapMarker = (
Expand Down Expand Up @@ -66,7 +67,7 @@ const useMapMarker = (
};
};

interface SmartMarkerProps {
export interface SmartMarkerProps {
map: maplibregl.Map;
geoUri: string;
id?: string;
Expand Down
71 changes: 71 additions & 0 deletions src/components/views/location/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
Copyright 2024 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Exports location components which touch maplibre-gs wrapped in React Suspense to enable code splitting

import React, { ComponentProps, lazy, Suspense } from "react";

import Spinner from "../elements/Spinner";

const MapComponent = lazy(() => import("./Map"));

export function Map(props: ComponentProps<typeof MapComponent>): JSX.Element {
return (
<Suspense fallback={<Spinner />}>
<MapComponent {...props} />
</Suspense>
);
}

const LocationPickerComponent = lazy(() => import("./LocationPicker"));

export function LocationPicker(props: ComponentProps<typeof LocationPickerComponent>): JSX.Element {
return (
<Suspense fallback={<Spinner />}>
<LocationPickerComponent {...props} />
</Suspense>
);
}

const SmartMarkerComponent = lazy(() => import("./SmartMarker"));

export function SmartMarker(props: ComponentProps<typeof SmartMarkerComponent>): JSX.Element {
return (
<Suspense fallback={<Spinner />}>
<SmartMarkerComponent {...props} />
</Suspense>
);
}

const LocationButtonComponent = lazy(() => import("./LocationButton"));

export function LocationButton(props: ComponentProps<typeof LocationButtonComponent>): JSX.Element {
return (
<Suspense fallback={<Spinner />}>
<LocationButtonComponent {...props} />
</Suspense>
);
}

const LocationViewDialogComponent = lazy(() => import("./LocationViewDialog"));

export function LocationViewDialog(props: ComponentProps<typeof LocationViewDialogComponent>): JSX.Element {
return (
<Suspense fallback={<Spinner />}>
<LocationViewDialogComponent {...props} />
</Suspense>
);
}
5 changes: 2 additions & 3 deletions src/components/views/messages/MBeaconBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,11 @@ import { isSelfLocation, LocationShareError } from "../../../utils/location";
import { BeaconDisplayStatus, getBeaconDisplayStatus } from "../beacon/displayStatus";
import BeaconStatus from "../beacon/BeaconStatus";
import OwnBeaconStatus from "../beacon/OwnBeaconStatus";
import Map from "../location/Map";
import { Map, SmartMarker } from "../location";
import { MapError } from "../location/MapError";
import MapFallback from "../location/MapFallback";
import SmartMarker from "../location/SmartMarker";
import { GetRelationsForEvent } from "../rooms/EventTile";
import BeaconViewDialog from "../beacon/BeaconViewDialog";
import { BeaconViewDialog } from "../beacon";
import { IBodyProps } from "./IBodyProps";

const useBeaconState = (
Expand Down
4 changes: 1 addition & 3 deletions src/components/views/messages/MLocationBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ import {
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import TooltipTarget from "../elements/TooltipTarget";
import { Alignment } from "../elements/Tooltip";
import LocationViewDialog from "../location/LocationViewDialog";
import Map from "../location/Map";
import SmartMarker from "../location/SmartMarker";
import { SmartMarker, Map, LocationViewDialog } from "../location";
import { IBodyProps } from "./IBodyProps";
import { createReconnectedListener } from "../../../utils/connection";

Expand Down
5 changes: 3 additions & 2 deletions src/components/views/messages/TextualBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ limitations under the License.

import React, { createRef, SyntheticEvent, MouseEvent } from "react";
import ReactDOM from "react-dom";
import highlight from "highlight.js";
import { MsgType } from "matrix-js-sdk/src/matrix";
import { TooltipProvider } from "@vector-im/compound-web";

Expand Down Expand Up @@ -238,7 +237,9 @@ export default class TextualBody extends React.Component<IBodyProps, IState> {
pre.append(document.createElement("span"));
}

private highlightCode(code: HTMLElement): void {
private async highlightCode(code: HTMLElement): Promise<void> {
const { default: highlight } = await import("highlight.js");

if (code.textContent && code.textContent.length > MAX_HIGHLIGHT_LENGTH) {
console.log(
"Code block is bigger than highlight limit (" +
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/rooms/MessageComposerButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { CollapsibleButton } from "./CollapsibleButton";
import { MenuProps } from "../../structures/ContextMenu";
import dis from "../../../dispatcher/dispatcher";
import ErrorDialog from "../dialogs/ErrorDialog";
import LocationButton from "../location/LocationButton";
import { LocationButton } from "../location";
import Modal from "../../../Modal";
import PollCreateDialog from "../elements/PollCreateDialog";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
Expand Down
2 changes: 1 addition & 1 deletion src/utils/location/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ export * from "./findMapStyleUrl";
export * from "./isSelfLocation";
export * from "./locationEventGeoUri";
export * from "./LocationShareErrors";
export * from "./map";
export * from "./links";
export * from "./parseGeoUri";
export * from "./positionFailureMessage";
47 changes: 47 additions & 0 deletions src/utils/location/links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { MatrixEvent, M_LOCATION } from "matrix-js-sdk/src/matrix";

import { parseGeoUri } from "./parseGeoUri";

export const makeMapSiteLink = (coords: GeolocationCoordinates): string => {
return (
"https://www.openstreetmap.org/" +
`?mlat=${coords.latitude}` +
`&mlon=${coords.longitude}` +
`#map=16/${coords.latitude}/${coords.longitude}`
);
};

export const createMapSiteLinkFromEvent = (event: MatrixEvent): string | null => {
const content = event.getContent();
const mLocation = content[M_LOCATION.name];
if (mLocation !== undefined) {
const uri = mLocation["uri"];
if (uri !== undefined) {
const geoCoords = parseGeoUri(uri);
return geoCoords ? makeMapSiteLink(geoCoords) : null;
}
} else {
const geoUri = content["geo_uri"];
if (geoUri) {
const geoCoords = parseGeoUri(geoUri);
return geoCoords ? makeMapSiteLink(geoCoords) : null;
}
}
return null;
};
31 changes: 1 addition & 30 deletions src/utils/location/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ limitations under the License.
*/

import * as maplibregl from "maplibre-gl";
import { MatrixClient, MatrixEvent, M_LOCATION } from "matrix-js-sdk/src/matrix";
import { MatrixClient } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";

import { _t } from "../../languageHandler";
import { parseGeoUri } from "./parseGeoUri";
import { findMapStyleUrl } from "./findMapStyleUrl";
import { LocationShareError } from "./LocationShareErrors";

Expand Down Expand Up @@ -75,31 +74,3 @@ export const createMarker = (coords: GeolocationCoordinates, element: HTMLElemen
}).setLngLat({ lon: coords.longitude, lat: coords.latitude });
return marker;
};

export const makeMapSiteLink = (coords: GeolocationCoordinates): string => {
return (
"https://www.openstreetmap.org/" +
`?mlat=${coords.latitude}` +
`&mlon=${coords.longitude}` +
`#map=16/${coords.latitude}/${coords.longitude}`
);
};

export const createMapSiteLinkFromEvent = (event: MatrixEvent): string | null => {
const content = event.getContent();
const mLocation = content[M_LOCATION.name];
if (mLocation !== undefined) {
const uri = mLocation["uri"];
if (uri !== undefined) {
const geoCoords = parseGeoUri(uri);
return geoCoords ? makeMapSiteLink(geoCoords) : null;
}
} else {
const geoUri = content["geo_uri"];
if (geoUri) {
const geoCoords = parseGeoUri(geoUri);
return geoCoords ? makeMapSiteLink(geoCoords) : null;
}
}
return null;
};
2 changes: 1 addition & 1 deletion src/utils/location/useMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ limitations under the License.
*/

import { useEffect, useState } from "react";
import { Map as MapLibreMap } from "maplibre-gl";

import type { Map as MapLibreMap } from "maplibre-gl";
import { createMap } from "./map";
import { useMatrixClientContext } from "../../contexts/MatrixClientContext";

Expand Down
10 changes: 6 additions & 4 deletions test/components/views/elements/SyntaxHighlight-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,24 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { render } from "@testing-library/react";
import { render, waitFor } from "@testing-library/react";
import hljs, { type HighlightOptions } from "highlight.js";
import React from "react";

import SyntaxHighlight from "../../../../src/components/views/elements/SyntaxHighlight";

describe("<SyntaxHighlight />", () => {
it("renders", () => {
it("renders", async () => {
const { container } = render(<SyntaxHighlight>console.log("Hello, World!");</SyntaxHighlight>);
await waitFor(() => expect(container.querySelector(".language-arcade")).toBeTruthy());
expect(container).toMatchSnapshot();
});

it.each(["json", "javascript", "css"])("uses the provided language", (lang) => {
it.each(["json", "javascript", "css"])("uses the provided language", async (lang) => {
const mock = jest.spyOn(hljs, "highlight");

render(<SyntaxHighlight language={lang}>// Hello, World</SyntaxHighlight>);
const { container } = render(<SyntaxHighlight language={lang}>// Hello, World</SyntaxHighlight>);
await waitFor(() => expect(container.querySelector(`.language-${lang}`)).toBeTruthy());

const [_lang, opts] = mock.mock.lastCall!;
expect((opts as HighlightOptions)["language"]).toBe(lang);
Expand Down

0 comments on commit 4a05de4

Please sign in to comment.