-
Notifications
You must be signed in to change notification settings - Fork 65
/
Media.tsx
542 lines (477 loc) · 16.4 KB
/
Media.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// tslint:disable:jsdoc-format
import React, { CSSProperties } from "react"
import { createResponsiveComponents } from "./DynamicResponsive"
import { MediaQueries } from "./MediaQueries"
import {
intersection,
propKey,
createClassName,
castBreakpointsToIntegers,
memoize,
} from "./Utils"
import { BreakpointConstraint } from "./Breakpoints"
/**
* A render prop that can be used to render a different container element than
* the default `div`.
*
* @see {@link MediaProps.children}.
*/
export type RenderProp = (
className: string,
renderChildren: boolean
) => React.ReactNode
// TODO: All of these props should be mutually exclusive. Using a union should
// probably be made possible by https://github.com/Microsoft/TypeScript/pull/27408.
export interface MediaBreakpointProps<BreakpointKey = string> {
/**
* Children will only be shown if the viewport matches the specified
* breakpoint. That is, a viewport width that’s higher than the configured
* breakpoint value, but lower than the value of the next breakpoint, if any
* larger breakpoints exist at all.
*
* @example
```tsx
// With breakpoints defined like these
{ xs: 0, sm: 768, md: 1024 }
// Matches a viewport that has a width between 0 and 768
<Media at="xs">ohai</Media>
// Matches a viewport that has a width between 768 and 1024
<Media at="sm">ohai</Media>
// Matches a viewport that has a width over 1024
<Media at="md">ohai</Media>
```
*
*/
at?: BreakpointKey
/**
* Children will only be shown if the viewport is smaller than the specified
* breakpoint.
*
* @example
```tsx
// With breakpoints defined like these
{ xs: 0, sm: 768, md: 1024 }
// Matches a viewport that has a width from 0 to 767
<Media lessThan="sm">ohai</Media>
// Matches a viewport that has a width from 0 to 1023
<Media lessThan="md">ohai</Media>
```
*
*/
lessThan?: BreakpointKey
/**
* Children will only be shown if the viewport is greater than the specified
* breakpoint.
*
* @example
```tsx
// With breakpoints defined like these
{ xs: 0, sm: 768, md: 1024 }
// Matches a viewport that has a width from 768 to infinity
<Media greaterThan="xs">ohai</Media>
// Matches a viewport that has a width from 1024 to infinity
<Media greaterThan="sm">ohai</Media>
```
*
*/
greaterThan?: BreakpointKey
/**
* Children will only be shown if the viewport is greater or equal to the
* specified breakpoint.
*
* @example
```tsx
// With breakpoints defined like these
{ xs: 0, sm: 768, md: 1024 }
// Matches a viewport that has a width from 0 to infinity
<Media greaterThanOrEqual="xs">ohai</Media>
// Matches a viewport that has a width from 768 to infinity
<Media greaterThanOrEqual="sm">ohai</Media>
// Matches a viewport that has a width from 1024 to infinity
<Media greaterThanOrEqual="md">ohai</Media>
```
*
*/
greaterThanOrEqual?: BreakpointKey
/**
* Children will only be shown if the viewport is between the specified
* breakpoints. That is, a viewport width that’s higher than or equal to the
* small breakpoint value, but lower than the value of the large breakpoint.
*
* @example
```tsx
// With breakpoints defined like these
{ xs: 0, sm: 768, md: 1024 }
// Matches a viewport that has a width from 0 to 767
<Media between={["xs", "sm"]}>ohai</Media>
// Matches a viewport that has a width from 0 to 1023
<Media between={["xs", "md"]}>ohai</Media>
```
*
*/
between?: [BreakpointKey, BreakpointKey]
}
export interface MediaProps<BreakpointKey, Interaction>
extends MediaBreakpointProps<BreakpointKey> {
/**
* Children will only be shown if the interaction query matches.
*
* @example
```tsx
// With interactions defined like these
{ hover: "(hover: hover)" }
// Matches an input device that is capable of hovering
<Media interaction="hover">ohai</Media>
```
*/
interaction?: Interaction
/**
* The component(s) that should conditionally be shown, depending on the media
* query matching.
*
* In case a different element is preferred, a render prop can be provided
* that receives the class-name it should use to have the media query styling
* applied.
*
* Additionally, the render prop receives a boolean that indicates wether or
* not its children should be rendered, which will be `false` if the media
* query is not included in the `onlyMatch` list. Use this flag if your
* component’s children may be expensive to render and you want to avoid any
* unnecessary work.
* (@see {@link MediaContextProviderProps.onlyMatch} for details)
*
* @example
*
```tsx
const Component = () => (
<Media greaterThan="xs">
{(className, renderChildren) => (
<span className={className}>
{renderChildren && "ohai"}
</span>
)}
</Media>
)
```
*
*/
children: React.ReactNode | RenderProp
/**
* Additional classNames to passed down and applied to Media container
*/
className?: string
/**
* Additional styles to passed down and applied to Media container
*/
style?: CSSProperties
}
export interface MediaContextProviderProps<M> {
/**
* This list of breakpoints and interactions can be used to limit the rendered
* output to these.
*
* For instance, when a server knows for some user-agents that certain
* breakpoints will never apply, omitting them altogether will lower the
* rendered byte size.
*/
onlyMatch?: M[]
/**
* Disables usage of browser MediaQuery API to only render at the current
* breakpoint.
*
* Use this with caution, as disabling this means React components for all
* breakpoints will be mounted client-side and all associated life-cycle hooks
* will be triggered, which could lead to unintended side-effects.
*/
disableDynamicMediaQueries?: boolean
}
export interface CreateMediaConfig {
/**
* The breakpoint definitions for your application. Width definitions should
* start at 0.
*
* @see {@link createMedia}
*/
breakpoints: { [key: string]: number | string }
/**
* The interaction definitions for your application.
*/
interactions?: { [key: string]: string }
}
export interface CreateMediaResults<BreakpointKey, Interactions> {
/**
* The React component that you use throughout your application.
*
* @see {@link MediaBreakpointProps}
*/
Media: React.ComponentType<MediaProps<BreakpointKey, Interactions>>
/**
* The React Context provider component that you use to constrain rendering of
* breakpoints to a set list and to enable client-side dynamic constraining.
*
* @see {@link MediaContextProviderProps}
*/
MediaContextProvider: React.ComponentType<
MediaContextProviderProps<BreakpointKey | Interactions>
>
/**
* Generates a set of CSS rules that you should include in your application’s
* styling to enable the hiding behaviour of your `Media` component uses.
*/
createMediaStyle(breakpointKeys?: BreakpointConstraint[]): string
/**
* A list of your application’s breakpoints sorted from small to large.
*/
SortedBreakpoints: BreakpointKey[]
/**
* Creates a list of your application’s breakpoints that support the given
* widths and everything in between.
*/
findBreakpointsForWidths(
fromWidth: number,
throughWidth: number
): BreakpointKey[] | undefined
/**
* Finds the breakpoint that matches the given width.
*/
findBreakpointAtWidth(width: number): BreakpointKey | undefined
/**
* Maps a list of values for various breakpoints to props that can be used
* with the `Media` component.
*
* The values map to corresponding indices in the sorted breakpoints array. If
* less values are specified than the number of breakpoints your application
* has, the last value will be applied to all subsequent breakpoints.
*/
valuesWithBreakpointProps<SizeValue>(
values: SizeValue[]
): Array<[SizeValue, MediaBreakpointProps<BreakpointKey>]>
}
/**
* This is used to generate a Media component, its context provider, and CSS
* rules based on your application’s breakpoints and interactions.
*
* Note that the interaction queries are entirely up to you to define and they
* should be written in such a way that they match when you want the element to
* be hidden.
*
* @example
*
```tsx
const MyAppMedia = createMedia({
breakpoints: {
xs: 0,
sm: 768,
md: 900
lg: 1024,
xl: 1192,
},
interactions: {
hover: `not all and (hover:hover)`
},
})
export const Media = MyAppMedia.Media
export const MediaContextProvider = MyAppMedia.MediaContextProvider
export const createMediaStyle = MyAppMedia.createMediaStyle
```
*
*/
export function createMedia<
MediaConfig extends CreateMediaConfig,
BreakpointKey extends keyof MediaConfig["breakpoints"],
Interaction extends keyof MediaConfig["interactions"]
>(config: MediaConfig): CreateMediaResults<BreakpointKey, Interaction> {
const breakpoints = castBreakpointsToIntegers(config.breakpoints)
const mediaQueries = new MediaQueries<BreakpointKey>(
breakpoints,
config.interactions || {}
)
const DynamicResponsive = createResponsiveComponents()
const MediaContext = React.createContext<
MediaContextProviderProps<BreakpointKey | Interaction>
>({})
MediaContext.displayName = "Media.Context"
const MediaParentContext = React.createContext<{
hasParentMedia: boolean
breakpointProps: MediaBreakpointProps<BreakpointKey>
}>({ hasParentMedia: false, breakpointProps: {} })
MediaContext.displayName = "MediaParent.Context"
const getMediaContextValue = memoize(onlyMatch => ({
onlyMatch,
}))
const MediaContextProvider: React.FunctionComponent<
MediaContextProviderProps<BreakpointKey | Interaction>
> = ({ disableDynamicMediaQueries, onlyMatch, children }) => {
if (disableDynamicMediaQueries) {
const MediaContextValue = getMediaContextValue(onlyMatch)
return (
<MediaContext.Provider value={MediaContextValue}>
{children}
</MediaContext.Provider>
)
} else {
return (
<DynamicResponsive.Provider
mediaQueries={mediaQueries.dynamicResponsiveMediaQueries}
initialMatchingMediaQueries={intersection(
mediaQueries.mediaQueryTypes,
onlyMatch
)}
>
<DynamicResponsive.Consumer>
{matches => {
const matchingMediaQueries = Object.keys(matches).filter(
key => matches[key]
)
const MediaContextValue = getMediaContextValue(
intersection(matchingMediaQueries, onlyMatch)
)
return (
<MediaContext.Provider value={MediaContextValue}>
{children}
</MediaContext.Provider>
)
}}
</DynamicResponsive.Consumer>
</DynamicResponsive.Provider>
)
}
}
const Media = class extends React.Component<
MediaProps<BreakpointKey, Interaction>
> {
constructor(props) {
super(props)
validateProps(props)
}
static defaultProps = {
className: "",
style: {},
}
static contextType = MediaParentContext
getMediaParentContextValue = memoize(
(breakpointProps: MediaBreakpointProps<BreakpointKey>) => ({
hasParentMedia: true,
breakpointProps,
})
)
render() {
const props = this.props
const {
children,
className: passedClassName,
style,
interaction,
...breakpointProps
} = props
const mediaParentContextValue = this.getMediaParentContextValue(
breakpointProps
)
return (
<MediaParentContext.Consumer>
{mediaParentContext => {
return (
<MediaParentContext.Provider value={mediaParentContextValue}>
<MediaContext.Consumer>
{({ onlyMatch } = {}) => {
let className: string | null
if (props.interaction) {
className = createClassName(
"interaction",
props.interaction
)
} else {
if (props.at) {
const largestBreakpoint =
mediaQueries.breakpoints.largestBreakpoint
if (props.at === largestBreakpoint) {
// TODO: We should look into making React’s __DEV__ available
// and have webpack completely compile these away.
let ownerName = null
try {
const owner = (this as any)._reactInternalFiber
._debugOwner.type
ownerName = owner.displayName || owner.name
} catch (err) {
// no-op
}
console.warn(
"[@artsy/fresnel] " +
"`at` is being used with the largest breakpoint. " +
"Consider using `<Media greaterThanOrEqual=" +
`"${largestBreakpoint}">\` to account for future ` +
`breakpoint definitions outside of this range.${
ownerName
? ` It is being used in the ${ownerName} component.`
: ""
}`
)
}
}
const type = propKey(breakpointProps)
const breakpoint = breakpointProps[type]!
className = createClassName(type, breakpoint)
}
const doesMatchParent =
!mediaParentContext.hasParentMedia ||
intersection(
mediaQueries.breakpoints.toVisibleAtBreakpointSet(
mediaParentContext.breakpointProps
),
mediaQueries.breakpoints.toVisibleAtBreakpointSet(
breakpointProps
)
).length > 0
const renderChildren =
doesMatchParent &&
(onlyMatch === undefined ||
mediaQueries.shouldRenderMediaQuery(
{ ...breakpointProps, interaction },
onlyMatch
))
if (props.children instanceof Function) {
return props.children(className, renderChildren)
} else {
return (
<div
className={`fresnel-container ${className} ${passedClassName}`}
style={style}
suppressHydrationWarning={!renderChildren}
>
{renderChildren ? props.children : null}
</div>
)
}
}}
</MediaContext.Consumer>
</MediaParentContext.Provider>
)
}}
</MediaParentContext.Consumer>
)
}
}
return {
Media,
MediaContextProvider,
createMediaStyle: mediaQueries.toStyle,
SortedBreakpoints: [...mediaQueries.breakpoints.sortedBreakpoints],
findBreakpointAtWidth: mediaQueries.breakpoints.findBreakpointAtWidth,
findBreakpointsForWidths: mediaQueries.breakpoints.findBreakpointsForWidths,
valuesWithBreakpointProps:
mediaQueries.breakpoints.valuesWithBreakpointProps,
}
}
const MutuallyExclusiveProps: string[] = MediaQueries.validKeys()
function validateProps(props) {
const selectedProps = Object.keys(props).filter(prop =>
MutuallyExclusiveProps.includes(prop)
)
if (selectedProps.length < 1) {
throw new Error(`1 of ${MutuallyExclusiveProps.join(", ")} is required.`)
} else if (selectedProps.length > 1) {
throw new Error(
`Only 1 of ${selectedProps.join(", ")} is allowed at a time.`
)
}
}