-
Notifications
You must be signed in to change notification settings - Fork 118
/
Layout.tsx
310 lines (282 loc) · 10.4 KB
/
Layout.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import { Components, registerComponent, getSetting, withUpdate } from 'meteor/vulcan:core';
import React, { PureComponent } from 'react';
import Users from 'meteor/vulcan:users';
import { Helmet } from 'react-helmet';
import CssBaseline from '@material-ui/core/CssBaseline';
import classNames from 'classnames'
import Intercom from 'react-intercom';
import moment from 'moment-timezone';
import { withCookies } from 'react-cookie'
import LogRocket from 'logrocket'
import { Random } from 'meteor/random';
import { withStyles, withTheme, createStyles } from '@material-ui/core/styles';
import { withLocation } from '../lib/routeUtil';
import { AnalyticsContext } from '../lib/analyticsEvents.js'
import { UserContext } from './common/withUser';
import { TimezoneContext } from './common/withTimezone';
import { DialogManager } from './common/withDialog';
import { CommentBoxManager } from './common/withCommentBox';
import { TableOfContentsContext } from './posts/TableOfContents/TableOfContents';
import { PostsReadContext } from './common/withRecordPostView';
import { pBodyStyle } from '../themes/stylePiping';
const intercomAppId = getSetting('intercomAppId', 'wtb8z7sj');
const googleTagManagerId = getSetting('googleTagManager.apiKey')
// From https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
// Simple hash for randomly sampling users. NOT CRYPTOGRAPHIC.
const hashCode = function(str: string): number {
var hash = 0, i, chr;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
// These routes will have the standalone TabNavigationMenu (aka sidebar)
//
// Refer to routes.js for the route names. Or console log in the route you'd
// like to include
const standaloneNavMenuRouteNames: Record<string,string[]> = {
'LessWrong': [
'home', 'allPosts', 'questions', 'sequencesHome', 'CommunityHome', 'Shortform', 'Codex',
'HPMOR', 'Rationality', 'Sequences', 'collections', 'nominations', 'reviews'
],
'AlignmentForum': ['alignment.home', 'sequencesHome', 'allPosts', 'questions', 'Shortform'],
'EAForum': ['home', 'allPosts', 'questions', 'Community', 'Shortform'],
}
const styles = createStyles(theme => ({
main: {
margin: '50px auto 15px auto',
[theme.breakpoints.down('sm')]: {
marginTop: 0,
paddingLeft: theme.spacing.unit/2,
paddingRight: theme.spacing.unit/2,
},
},
'@global': {
p: pBodyStyle,
'.mapboxgl-popup': {
willChange: 'auto !important',
zIndex: theme.zIndexes.styledMapPopup
},
// Font fallback to ensure that all greek letters just directly render as Arial
'@font-face': {
fontFamily: "GreekFallback",
src: "local('Arial')",
unicodeRange: 'U+0370-03FF, U+1F00-1FFF' // Unicode range for greek characters
}
},
searchResultsArea: {
position: "absolute",
zIndex: theme.zIndexes.layout,
top: 0,
width: "100%",
},
}))
interface LayoutProps {
cookies: any,
currentUser: any,
updateUser: any,
location: any,
classes: any,
theme: any
messages: any,
children: any,
}
interface LayoutState {
timezone: string,
toc: any,
postsRead: Record<string,boolean>,
hideNavigationSidebar: boolean,
}
class Layout extends PureComponent<LayoutProps,LayoutState> {
searchResultsAreaRef: React.RefObject<HTMLDivElement>
constructor (props) {
super(props);
const { cookies, currentUser } = this.props;
const savedTimezone = cookies?.get('timezone');
this.state = {
timezone: savedTimezone,
toc: null,
postsRead: {},
hideNavigationSidebar: !!(currentUser?.hideNavigationSidebar),
};
this.searchResultsAreaRef = React.createRef<HTMLDivElement>();
}
setToC = (document, sectionData) => {
if (document) {
this.setState({
toc: {
document: document,
sections: sectionData && sectionData.sections
}
});
} else {
this.setState({
toc: null,
});
}
}
toggleStandaloneNavigation = () => {
const { updateUser, currentUser } = this.props
this.setState(prevState => {
if (currentUser) {
updateUser({
selector: { _id: currentUser._id},
data: {
hideNavigationSidebar: !prevState.hideNavigationSidebar
},
})
}
return {
hideNavigationSidebar: !prevState.hideNavigationSidebar
}
})
}
getUniqueClientId = () => {
const { currentUser, cookies } = this.props
if (currentUser) return currentUser._id
const cookieId = cookies.get('clientId')
if (cookieId) return cookieId
const newId = Random.id()
cookies.set('clientId', newId)
return newId
}
initializeLogRocket = () => {
const { currentUser } = this.props
const logRocketKey = getSetting('logRocket.apiKey')
if (logRocketKey) {
// If the user is logged in, always log their sessions
if (currentUser) {
LogRocket.init(logRocketKey)
return
}
// If the user is not logged in, only track 1/5 of the sessions
const clientId = this.getUniqueClientId()
const hash = hashCode(clientId)
if (hash % getSetting('logRocket.sampleDensity') === 0) {
LogRocket.init(logRocketKey)
}
}
}
componentDidMount() {
const { cookies } = this.props;
const newTimezone = moment.tz.guess();
if(this.state.timezone !== newTimezone) {
cookies.set('timezone', newTimezone);
this.setState({
timezone: newTimezone
});
}
this.initializeLogRocket()
}
render () {
const {currentUser, location, children, classes, theme, messages} = this.props;
const {hideNavigationSidebar} = this.state
const showIntercom = currentUser => {
if (currentUser && !currentUser.hideIntercom) {
return <div id="intercome-outer-frame">
<Components.ErrorBoundary>
<Intercom
appID={intercomAppId}
user_id={currentUser._id}
email={currentUser.email}
name={currentUser.displayName}/>
</Components.ErrorBoundary>
</div>
} else if (!currentUser) {
return <div id="intercome-outer-frame">
<Components.ErrorBoundary>
<Intercom appID={intercomAppId}/>
</Components.ErrorBoundary>
</div>
} else {
return null
}
}
// Check whether the current route is one which should have standalone
// navigation on the side. If there is no current route (ie, a 404 page),
// then it should.
// FIXME: This is using route names, but it would be better if this was
// a property on routes themselves.
const standaloneNavigation = !location.currentRoute ||
standaloneNavMenuRouteNames[getSetting('forumType')]
.includes(location.currentRoute.name)
return (
<AnalyticsContext path={location.pathname}>
<UserContext.Provider value={currentUser}>
<TimezoneContext.Provider value={this.state.timezone}>
<PostsReadContext.Provider value={{
postsRead: this.state.postsRead,
setPostRead: (postId, isRead) => this.setState({
postsRead: {...this.state.postsRead, [postId]: isRead}
})
}}>
<TableOfContentsContext.Provider value={this.setToC}>
<div className={classNames("wrapper", {'alignment-forum': getSetting('forumType') === 'AlignmentForum'}) } id="wrapper">
<DialogManager>
<CommentBoxManager>
<CssBaseline />
<Helmet>
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/icon?family=Material+Icons"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@7.0.0/themes/reset-min.css"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"/>
{ theme.typography.fontDownloads &&
theme.typography.fontDownloads.map(
(url)=><link rel="stylesheet" key={`font-${url}`} href={url}/>
)
}
<meta httpEquiv="Accept-CH" content="DPR, Viewport-Width, Width"/>
<link rel="stylesheet" href="https://use.typekit.net/jvr1gjm.css"/>
</Helmet>
<Components.AnalyticsClient/>
<Components.NavigationEventSender/>
{/* Sign up user for Intercom, if they do not yet have an account */}
{showIntercom(currentUser)}
<noscript className="noscript-warning"> This website requires javascript to properly function. Consider activating javascript to get access to all site functionality. </noscript>
{/* Google Tag Manager i-frame fallback */}
<noscript><iframe src={`https://www.googletagmanager.com/ns.html?id=${googleTagManagerId}`} height="0" width="0" style={{display:"none", visibility:"hidden"}}/></noscript>
<Components.Header
toc={this.state.toc}
searchResultsArea={this.searchResultsAreaRef}
standaloneNavigationPresent={standaloneNavigation}
toggleStandaloneNavigation={this.toggleStandaloneNavigation}
/>
{standaloneNavigation && <Components.NavigationStandalone
sidebarHidden={hideNavigationSidebar}
/>}
<div ref={this.searchResultsAreaRef} className={classes.searchResultsArea} />
<div className={classes.main}>
<Components.ErrorBoundary>
<Components.FlashMessages messages={messages} />
</Components.ErrorBoundary>
<Components.ErrorBoundary>
{children}
</Components.ErrorBoundary>
</div>
<Components.Footer />
</CommentBoxManager>
</DialogManager>
</div>
</TableOfContentsContext.Provider>
</PostsReadContext.Provider>
</TimezoneContext.Provider>
</UserContext.Provider>
</AnalyticsContext>
)
}
}
declare global {
interface ComponentTypes {
Layout: typeof Layout
}
}
const withUpdateOptions = {
collection: Users,
fragmentName: 'UsersCurrent',
}
registerComponent(
'Layout', Layout, withLocation, withCookies, [withUpdate, withUpdateOptions],
withStyles(styles, { name: "Layout" }), withTheme()
);