Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2: React.lazy load HyloEditorMobile for code-splitting to improve load time in HyloApp #1322

Open
wants to merge 6 commits into
base: HyloApp-544-add-group-explore-and-about
Choose a base branch
from
6 changes: 2 additions & 4 deletions src/components/HyloEditor/HyloEditor.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { useRef, useImperativeHandle, useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useEditor, EditorContent, Extension, BubbleMenu } from '@tiptap/react'
import Highlight from '@tiptap/extension-highlight'
import Placeholder from '@tiptap/extension-placeholder'
Expand Down Expand Up @@ -31,7 +30,6 @@ export const HyloEditor = React.forwardRef(function HyloEditor ({
showMenu = false,
suggestionsThemeName = 'suggestions'
}, ref) {
const dispatch = useDispatch()
const editorRef = useRef(null)
const [selectedLink, setSelectedLink] = useState()
const editor = useEditor({
Expand Down Expand Up @@ -113,9 +111,9 @@ export const HyloEditor = React.forwardRef(function HyloEditor ({
}
}),

PeopleMentions({ onSelection: onAddMention, maxSuggestions, groupIds, suggestionsThemeName, dispatch }),
PeopleMentions({ onSelection: onAddMention, maxSuggestions, groupIds, suggestionsThemeName }),

TopicMentions({ onSelection: onAddTopic, maxSuggestions, groupIds, suggestionsThemeName, dispatch }),
TopicMentions({ onSelection: onAddTopic, maxSuggestions, groupIds, suggestionsThemeName }),

Highlight
],
Expand Down
10 changes: 6 additions & 4 deletions src/components/HyloEditor/extensions/PeopleMentions.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import Mention from '@tiptap/extension-mention'
import { PluginKey } from 'prosemirror-state'
import { queryHyloAPI } from 'util/graphql'
import asyncDebounce from 'util/asyncDebounce'
import suggestions from './suggestions'
import findMentions from 'store/actions/findMentions'

export const PeopleMentions = ({ dispatch, groupIds, maxSuggestions, onSelection, suggestionsThemeName }) =>
export const PeopleMentions = ({ groupIds, maxSuggestions, onSelection, suggestionsThemeName }) =>
// Mentions (https://github.com/ueberdosis/tiptap/issues/2219#issuecomment-984662243)
Mention
.extend({
Expand Down Expand Up @@ -44,15 +45,16 @@ export const PeopleMentions = ({ dispatch, groupIds, maxSuggestions, onSelection
items: asyncDebounce(200, async ({ query, editor }) => {
editor.extensionStorage.topic.loading = true

const matchedPeople = await dispatch(findMentions({
const findMentionsGraphql = findMentions({
autocomplete: query,
groupIds: editor.extensionStorage.mention.groupIds,
maxItems: maxSuggestions
}))
}).graphql
const matchedPeople = await queryHyloAPI(findMentionsGraphql)

editor.extensionStorage.topic.loading = false

return matchedPeople?.payload.getData().items
return matchedPeople?.data.people.items
.map(person => ({
id: person.id,
label: person.name,
Expand Down
12 changes: 7 additions & 5 deletions src/components/HyloEditor/extensions/TopicMentions.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import Mention from '@tiptap/extension-mention'
import { PluginKey } from 'prosemirror-state'
import { uniqBy } from 'lodash/fp'
import { queryHyloAPI } from 'util/graphql'
import asyncDebounce from 'util/asyncDebounce'
import suggestions from './suggestions'
import findTopics from 'store/actions/findTopics'

export const TopicMentions = ({ dispatch, groupIds, maxSuggestions, onSelection, suggestionsThemeName }) =>
export const TopicMentions = ({ groupIds, maxSuggestions, onSelection, suggestionsThemeName }) =>
Mention
.extend({
name: 'topic',
Expand Down Expand Up @@ -44,15 +45,16 @@ export const TopicMentions = ({ dispatch, groupIds, maxSuggestions, onSelection,
// Can be fixed if it is a bad UX.
editor.extensionStorage.topic.loading = true

// TODO: Integrate `getTopicsBySearchTerm` selector to reduce queries and speed results
const matchedTopics = await dispatch(findTopics({
const findTopicsGraphql = findTopics({
autocomplete: query,
groupIds: editor.extensionStorage.topic.groupIds,
maxItems: maxSuggestions
}))
}).graphql
const matchedTopics = await queryHyloAPI(findTopicsGraphql)

editor.extensionStorage.topic.loading = false

const results = matchedTopics?.payload.getData().items
const results = matchedTopics?.data.groupTopics.items
.map(t => ({
id: t.topic.name,
label: `#${t.topic.name}`,
Expand Down
43 changes: 37 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,42 @@
import React from 'react'
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom'
import { rootDomId } from 'client/util'
import App from './router'
import Loading from 'components/Loading'
import './client/websockets'
import './css/global/index.scss'

ReactDOM.render(
<App />,
document.getElementById(rootDomId)
)
const App = React.lazy(() => import('./router'))
const HyloEditorMobile = React.lazy(() => import('components/HyloEditor/HyloEditorMobile'))
const Feature = React.lazy(() => import('components/PostCard/Feature'))

const renderRoot = () => {
switch (window.location.pathname) {
case '/hyloApp/editor': {
return (
<Suspense fallback={() => null}>
<HyloEditorMobile />
</Suspense>
)
}

case '/hyloApp/videoPlayer': {
const querystringParams = new URLSearchParams(window.location.search)

return (
<Suspense fallback={() => null}>
<Feature url={querystringParams.get('url')} />
</Suspense>
)
}

default: {
return (
<Suspense fallback={() => <Loading type='fullscreen' />}>
<App />
</Suspense>
)
}
}
}

ReactDOM.render(renderRoot(), document.getElementById(rootDomId))
7 changes: 1 addition & 6 deletions src/router/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import React from 'react'
import { ConnectedRouter } from 'connected-react-router'
import { Switch, Route } from 'react-router'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { Provider } from 'react-redux'
import { LayoutFlagsProvider } from 'contexts/LayoutFlagsContext'
import isWebView from 'util/webView'
import createStore, { history } from '../store'
import RootRouter from 'routes/RootRouter'
import HyloAppRouter from 'routes/HyloAppRouter'

const store = createStore()

Expand All @@ -24,10 +22,7 @@ export default function App () {
<DndProvider backend={HTML5Backend}>
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route path='/hyloApp' component={HyloAppRouter} />
<RootRouter />
</Switch>
<RootRouter />
</ConnectedRouter>
</Provider>
</DndProvider>
Expand Down
16 changes: 0 additions & 16 deletions src/routes/HyloAppRouter/HyloAppRouter.js

This file was deleted.

3 changes: 0 additions & 3 deletions src/routes/HyloAppRouter/index.js

This file was deleted.

36 changes: 36 additions & 0 deletions src/util/graphql.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import fetch from 'isomorphic-fetch'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh are we still specifically importing fetch? I think I used it 'raw' in a reactions PR... which might be a gap on older browsers (has fetch crossed the line into availability??)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh, this file can run on both front and backends....

import gql from 'graphql-tag'
import { print } from 'graphql/language/printer'

export const HYLO_GRAPHQL_ENDPOINT_PATH = '/noo/graphql'

export function stringToGraphql (graphqlString) {
return (typeof graphqlString === 'string' || graphqlString instanceof String)
? gql(graphqlString)
Expand All @@ -13,3 +16,36 @@ export function graphqlToString (unknownGraphql) {
? print(unknownGraphql)
: unknownGraphql
}

export function getHyloAPIEndpointURL () {
return typeof window === 'undefined'
? `${process.env.API_HOST}${HYLO_GRAPHQL_ENDPOINT_PATH}`
: `${window.location.origin}${HYLO_GRAPHQL_ENDPOINT_PATH}`
}

// For directly querying our API outside of the Redux store.
// Currently only used in the WebView HyloEditor
export async function queryHyloAPI ({ query: unknownGraphql, variables }) {
const params = { query: graphqlToString(unknownGraphql), variables }
const response = await fetch(getHyloAPIEndpointURL(), {
body: JSON.stringify(params),
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST'
})

if (response.status === 200) {
return response.json()
} else {
const { status, statusText, url } = response
const body = await response.text()
const error = new Error(body)

error.response = { status, statusText, url, body }

throw error
}
}