Improve code-splitting of highlight.js and maplibre-gs libs (#12349)

* 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>
This commit is contained in:
Michael Telatynski 2024-03-20 13:39:20 +00:00 committed by GitHub
parent 79c50db009
commit 4a05de485e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 185 additions and 63 deletions

View file

@ -20,7 +20,7 @@ import { Beacon, BeaconEvent, LocationAssetType } from "matrix-js-sdk/src/matrix
import MatrixClientContext from "../../../contexts/MatrixClientContext"; import MatrixClientContext from "../../../contexts/MatrixClientContext";
import { useEventEmitterState } from "../../../hooks/useEventEmitter"; import { useEventEmitterState } from "../../../hooks/useEventEmitter";
import SmartMarker from "../location/SmartMarker"; import { SmartMarker } from "../location";
interface Props { interface Props {
map: maplibregl.Map; map: maplibregl.Map;

View file

@ -36,7 +36,7 @@ import MapFallback from "../location/MapFallback";
import { MapError } from "../location/MapError"; import { MapError } from "../location/MapError";
import { LocationShareError } from "../../../utils/location"; import { LocationShareError } from "../../../utils/location";
interface IProps { export interface IProps {
roomId: Room["roomId"]; roomId: Room["roomId"];
matrixClient: MatrixClient; matrixClient: MatrixClient;
// open the map centered on this beacon's location // open the map centered on this beacon's location

View file

@ -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>
);
}

View file

@ -16,22 +16,23 @@ limitations under the License.
*/ */
import React from "react"; import React from "react";
import hljs from "highlight.js";
interface IProps { import { useAsyncMemo } from "../../../hooks/useAsyncMemo";
interface Props {
language?: string; language?: string;
children: string; children: string;
} }
export default class SyntaxHighlight extends React.PureComponent<IProps> { export default function SyntaxHighlight({ children, language }: Props): JSX.Element {
public render(): React.ReactNode { const highlighted = useAsyncMemo(async () => {
const { children: content, language } = this.props; const { default: highlight } = await import("highlight.js");
const highlighted = language ? hljs.highlight(content, { language }) : hljs.highlightAuto(content); return language ? highlight.highlight(children, { language }) : highlight.highlightAuto(children);
}, [language, children]);
return ( return (
<pre className={`mx_SyntaxHighlight hljs language-${highlighted.language}`}> <pre className={`mx_SyntaxHighlight hljs language-${highlighted?.language}`}>
<code dangerouslySetInnerHTML={{ __html: highlighted.value }} /> {highlighted ? <code dangerouslySetInnerHTML={{ __html: highlighted.value }} /> : children}
</pre> </pre>
); );
}
} }

View file

@ -24,7 +24,7 @@ import { aboveLeftOf, useContextMenu, MenuProps } from "../../structures/Context
import { OverflowMenuContext } from "../rooms/MessageComposerButtons"; import { OverflowMenuContext } from "../rooms/MessageComposerButtons";
import LocationShareMenu from "./LocationShareMenu"; import LocationShareMenu from "./LocationShareMenu";
interface IProps { export interface IProps {
roomId: string; roomId: string;
sender: RoomMember; sender: RoomMember;
menuPosition?: MenuProps; menuPosition?: MenuProps;

View file

@ -139,7 +139,7 @@ const onGeolocateError = (e: GeolocationPositionError): void => {
}); });
}; };
interface MapProps { export interface MapProps {
id: string; id: string;
interactive?: boolean; interactive?: boolean;
/** /**

View file

@ -18,7 +18,8 @@ import React, { ReactNode, useCallback, useEffect, useState } from "react";
import * as maplibregl from "maplibre-gl"; import * as maplibregl from "maplibre-gl";
import { RoomMember } from "matrix-js-sdk/src/matrix"; 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"; import Marker from "./Marker";
const useMapMarker = ( const useMapMarker = (
@ -66,7 +67,7 @@ const useMapMarker = (
}; };
}; };
interface SmartMarkerProps { export interface SmartMarkerProps {
map: maplibregl.Map; map: maplibregl.Map;
geoUri: string; geoUri: string;
id?: string; id?: string;

View file

@ -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>
);
}

View file

@ -38,12 +38,11 @@ import { isSelfLocation, LocationShareError } from "../../../utils/location";
import { BeaconDisplayStatus, getBeaconDisplayStatus } from "../beacon/displayStatus"; import { BeaconDisplayStatus, getBeaconDisplayStatus } from "../beacon/displayStatus";
import BeaconStatus from "../beacon/BeaconStatus"; import BeaconStatus from "../beacon/BeaconStatus";
import OwnBeaconStatus from "../beacon/OwnBeaconStatus"; import OwnBeaconStatus from "../beacon/OwnBeaconStatus";
import Map from "../location/Map"; import { Map, SmartMarker } from "../location";
import { MapError } from "../location/MapError"; import { MapError } from "../location/MapError";
import MapFallback from "../location/MapFallback"; import MapFallback from "../location/MapFallback";
import SmartMarker from "../location/SmartMarker";
import { GetRelationsForEvent } from "../rooms/EventTile"; import { GetRelationsForEvent } from "../rooms/EventTile";
import BeaconViewDialog from "../beacon/BeaconViewDialog"; import { BeaconViewDialog } from "../beacon";
import { IBodyProps } from "./IBodyProps"; import { IBodyProps } from "./IBodyProps";
const useBeaconState = ( const useBeaconState = (

View file

@ -29,9 +29,7 @@ import {
import MatrixClientContext from "../../../contexts/MatrixClientContext"; import MatrixClientContext from "../../../contexts/MatrixClientContext";
import TooltipTarget from "../elements/TooltipTarget"; import TooltipTarget from "../elements/TooltipTarget";
import { Alignment } from "../elements/Tooltip"; import { Alignment } from "../elements/Tooltip";
import LocationViewDialog from "../location/LocationViewDialog"; import { SmartMarker, Map, LocationViewDialog } from "../location";
import Map from "../location/Map";
import SmartMarker from "../location/SmartMarker";
import { IBodyProps } from "./IBodyProps"; import { IBodyProps } from "./IBodyProps";
import { createReconnectedListener } from "../../../utils/connection"; import { createReconnectedListener } from "../../../utils/connection";

View file

@ -16,7 +16,6 @@ limitations under the License.
import React, { createRef, SyntheticEvent, MouseEvent } from "react"; import React, { createRef, SyntheticEvent, MouseEvent } from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import highlight from "highlight.js";
import { MsgType } from "matrix-js-sdk/src/matrix"; import { MsgType } from "matrix-js-sdk/src/matrix";
import { TooltipProvider } from "@vector-im/compound-web"; import { TooltipProvider } from "@vector-im/compound-web";
@ -238,7 +237,9 @@ export default class TextualBody extends React.Component<IBodyProps, IState> {
pre.append(document.createElement("span")); 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) { if (code.textContent && code.textContent.length > MAX_HIGHLIGHT_LENGTH) {
console.log( console.log(
"Code block is bigger than highlight limit (" + "Code block is bigger than highlight limit (" +

View file

@ -24,7 +24,7 @@ import { CollapsibleButton } from "./CollapsibleButton";
import { MenuProps } from "../../structures/ContextMenu"; import { MenuProps } from "../../structures/ContextMenu";
import dis from "../../../dispatcher/dispatcher"; import dis from "../../../dispatcher/dispatcher";
import ErrorDialog from "../dialogs/ErrorDialog"; import ErrorDialog from "../dialogs/ErrorDialog";
import LocationButton from "../location/LocationButton"; import { LocationButton } from "../location";
import Modal from "../../../Modal"; import Modal from "../../../Modal";
import PollCreateDialog from "../elements/PollCreateDialog"; import PollCreateDialog from "../elements/PollCreateDialog";
import { MatrixClientPeg } from "../../../MatrixClientPeg"; import { MatrixClientPeg } from "../../../MatrixClientPeg";

View file

@ -18,6 +18,6 @@ export * from "./findMapStyleUrl";
export * from "./isSelfLocation"; export * from "./isSelfLocation";
export * from "./locationEventGeoUri"; export * from "./locationEventGeoUri";
export * from "./LocationShareErrors"; export * from "./LocationShareErrors";
export * from "./map"; export * from "./links";
export * from "./parseGeoUri"; export * from "./parseGeoUri";
export * from "./positionFailureMessage"; export * from "./positionFailureMessage";

View file

@ -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;
};

View file

@ -15,11 +15,10 @@ limitations under the License.
*/ */
import * as maplibregl from "maplibre-gl"; 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 { logger } from "matrix-js-sdk/src/logger";
import { _t } from "../../languageHandler"; import { _t } from "../../languageHandler";
import { parseGeoUri } from "./parseGeoUri";
import { findMapStyleUrl } from "./findMapStyleUrl"; import { findMapStyleUrl } from "./findMapStyleUrl";
import { LocationShareError } from "./LocationShareErrors"; import { LocationShareError } from "./LocationShareErrors";
@ -75,31 +74,3 @@ export const createMarker = (coords: GeolocationCoordinates, element: HTMLElemen
}).setLngLat({ lon: coords.longitude, lat: coords.latitude }); }).setLngLat({ lon: coords.longitude, lat: coords.latitude });
return marker; 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;
};

View file

@ -15,8 +15,8 @@ limitations under the License.
*/ */
import { useEffect, useState } from "react"; 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 { createMap } from "./map";
import { useMatrixClientContext } from "../../contexts/MatrixClientContext"; import { useMatrixClientContext } from "../../contexts/MatrixClientContext";

View file

@ -15,22 +15,24 @@ See the License for the specific language governing permissions and
limitations under the License. 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 hljs, { type HighlightOptions } from "highlight.js";
import React from "react"; import React from "react";
import SyntaxHighlight from "../../../../src/components/views/elements/SyntaxHighlight"; import SyntaxHighlight from "../../../../src/components/views/elements/SyntaxHighlight";
describe("<SyntaxHighlight />", () => { describe("<SyntaxHighlight />", () => {
it("renders", () => { it("renders", async () => {
const { container } = render(<SyntaxHighlight>console.log("Hello, World!");</SyntaxHighlight>); const { container } = render(<SyntaxHighlight>console.log("Hello, World!");</SyntaxHighlight>);
await waitFor(() => expect(container.querySelector(".language-arcade")).toBeTruthy());
expect(container).toMatchSnapshot(); 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"); 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!; const [_lang, opts] = mock.mock.lastCall!;
expect((opts as HighlightOptions)["language"]).toBe(lang); expect((opts as HighlightOptions)["language"]).toBe(lang);