/
Breakpoints.ts
339 lines (313 loc) · 11.2 KB
/
Breakpoints.ts
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
import { MediaBreakpointProps } from "./Media"
import { createRuleSet, createClassName } from "./Utils"
/**
* A union of possible breakpoint props.
*/
export type BreakpointConstraintKey = keyof MediaBreakpointProps
type ValueBreakpointPropsTuple<SizeValue, BreakpointKey> = [
SizeValue,
MediaBreakpointProps<BreakpointKey>
]
type Tuple = [string, string]
function breakpointKey(breakpoint: string | Tuple) {
return Array.isArray(breakpoint) ? breakpoint.join("-") : breakpoint
}
export enum BreakpointConstraint {
at = "at",
lessThan = "lessThan",
greaterThan = "greaterThan",
greaterThanOrEqual = "greaterThanOrEqual",
between = "between",
}
/**
* Encapsulates all breakpoint data needed by the Media component. The data is
* generated on initialization so no further runtime work is necessary.
*/
export class Breakpoints<BreakpointKey extends string> {
static validKeys() {
return [
BreakpointConstraint.at,
BreakpointConstraint.lessThan,
BreakpointConstraint.greaterThan,
BreakpointConstraint.greaterThanOrEqual,
BreakpointConstraint.between,
]
}
private _sortedBreakpoints: ReadonlyArray<string>
private _breakpoints: Record<string, number>
private _mediaQueries: Record<BreakpointConstraint, Map<string, string>>
constructor(breakpoints: { [key: string]: number }) {
this._breakpoints = breakpoints
this._sortedBreakpoints = Object.keys(breakpoints)
.map(breakpoint => [breakpoint, breakpoints[breakpoint]])
.sort((a, b) => (a[1] < b[1] ? -1 : 1))
.map(breakpointAndValue => breakpointAndValue[0] as string)
// List of all possible and valid `between` combinations
const betweenCombinations = this._sortedBreakpoints
.slice(0, -1)
.reduce(
(acc: Tuple[], b1, i) => [
...acc,
...this._sortedBreakpoints.slice(i + 1).map(b2 => [b1, b2] as Tuple),
],
[]
)
this._mediaQueries = {
[BreakpointConstraint.at]: this._createBreakpointQueries(
BreakpointConstraint.at,
this._sortedBreakpoints
),
[BreakpointConstraint.lessThan]: this._createBreakpointQueries(
BreakpointConstraint.lessThan,
this._sortedBreakpoints.slice(1)
),
[BreakpointConstraint.greaterThan]: this._createBreakpointQueries(
BreakpointConstraint.greaterThan,
this._sortedBreakpoints.slice(0, -1)
),
[BreakpointConstraint.greaterThanOrEqual]: this._createBreakpointQueries(
BreakpointConstraint.greaterThanOrEqual,
this._sortedBreakpoints
),
[BreakpointConstraint.between]: this._createBreakpointQueries(
BreakpointConstraint.between,
betweenCombinations
),
}
}
public get sortedBreakpoints() {
return this._sortedBreakpoints as BreakpointKey[]
}
public get dynamicResponsiveMediaQueries() {
return Array.from(
this._mediaQueries[BreakpointConstraint.at].entries()
).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
}
public get largestBreakpoint() {
return this._sortedBreakpoints[this._sortedBreakpoints.length - 1]
}
public findBreakpointsForWidths = (
fromWidth: number,
throughWidth: number
) => {
const fromBreakpoint = this.findBreakpointAtWidth(fromWidth)
if (!fromBreakpoint) {
return undefined
}
const throughBreakpoint = this.findBreakpointAtWidth(throughWidth)
if (!throughBreakpoint || fromBreakpoint === throughBreakpoint) {
return [fromBreakpoint] as BreakpointKey[]
} else {
return this._sortedBreakpoints.slice(
this._sortedBreakpoints.indexOf(fromBreakpoint),
this._sortedBreakpoints.indexOf(throughBreakpoint) + 1
) as BreakpointKey[]
}
}
public findBreakpointAtWidth = (width: number) => {
return this._sortedBreakpoints.find((breakpoint, i) => {
const nextBreakpoint = this._sortedBreakpoints[i + 1]
if (nextBreakpoint) {
return (
width >= this._breakpoints[breakpoint] &&
width < this._breakpoints[nextBreakpoint]
)
} else {
return width >= this._breakpoints[breakpoint]
}
}) as BreakpointKey | undefined
}
public toVisibleAtBreakpointSet(breakpointProps: MediaBreakpointProps) {
breakpointProps = this._normalizeProps(breakpointProps)
if (breakpointProps.lessThan) {
const breakpointIndex = this.sortedBreakpoints.findIndex(
bp => bp === breakpointProps.lessThan
)
return this.sortedBreakpoints.slice(0, breakpointIndex)
} else if (breakpointProps.greaterThan) {
const breakpointIndex = this.sortedBreakpoints.findIndex(
bp => bp === breakpointProps.greaterThan
)
return this.sortedBreakpoints.slice(breakpointIndex + 1)
} else if (breakpointProps.greaterThanOrEqual) {
const breakpointIndex = this.sortedBreakpoints.findIndex(
bp => bp === breakpointProps.greaterThanOrEqual
)
return this.sortedBreakpoints.slice(breakpointIndex)
} else if (breakpointProps.between) {
const between = breakpointProps.between
const fromBreakpointIndex = this.sortedBreakpoints.findIndex(
bp => bp === between[0]
)
const toBreakpointIndex = this.sortedBreakpoints.findIndex(
bp => bp === between[1]
)
return this.sortedBreakpoints.slice(
fromBreakpointIndex,
toBreakpointIndex
)
}
return []
}
public toRuleSets(keys = Breakpoints.validKeys()) {
const selectedMediaQueries = keys.reduce(
(mediaQueries, query) => {
mediaQueries[query] = this._mediaQueries[query]
return mediaQueries
},
{} as Record<BreakpointConstraint, Map<string, string>>
)
return Object.entries(selectedMediaQueries).reduce(
(acc: string[], [type, queries]) => {
queries.forEach((query, breakpoint) => {
// We need to invert the query, such that it matches when we want the
// element to be hidden.
acc.push(
createRuleSet(
createClassName(type, breakpoint),
`not all and ${query}`
)
)
})
return acc
},
[]
)
}
public shouldRenderMediaQuery(
breakpointProps: MediaBreakpointProps,
onlyRenderAt: string[]
): boolean {
breakpointProps = this._normalizeProps(breakpointProps)
if (breakpointProps.lessThan) {
const width = this._breakpoints[breakpointProps.lessThan]
const lowestAllowedWidth = Math.min(
...onlyRenderAt.map(breakpoint => this._breakpoints[breakpoint])
)
return lowestAllowedWidth < width
} else if (breakpointProps.greaterThan) {
const width = this._breakpoints[
this._findNextBreakpoint(breakpointProps.greaterThan)
]
const highestAllowedWidth = Math.max(
...onlyRenderAt.map(breakpoint => this._breakpoints[breakpoint])
)
return highestAllowedWidth >= width
} else if (breakpointProps.greaterThanOrEqual) {
const width = this._breakpoints[breakpointProps.greaterThanOrEqual]
const highestAllowedWidth = Math.max(
...onlyRenderAt.map(breakpoint => this._breakpoints[breakpoint])
)
return highestAllowedWidth >= width
} else if (breakpointProps.between) {
// TODO: This is the only useful breakpoint to negate, but we’ll
// we’ll see when/if we need it. We could then also decide
// to add `oustide`.
const fromWidth = this._breakpoints[breakpointProps.between[0]]
const toWidth = this._breakpoints[breakpointProps.between[1]]
const allowedWidths = onlyRenderAt.map(
breakpoint => this._breakpoints[breakpoint]
)
return !(
Math.max(...allowedWidths) < fromWidth ||
Math.min(...allowedWidths) >= toWidth
)
}
return false
}
public valuesWithBreakpointProps = <SizeValue>(
values: SizeValue[]
): Array<ValueBreakpointPropsTuple<SizeValue, BreakpointKey>> => {
type ValueBreakpoints = [SizeValue, string[]]
const max = values.length
const valueBreakpoints: ValueBreakpoints[] = []
let lastTuple: ValueBreakpoints
this._sortedBreakpoints.forEach((breakpoint, i) => {
const value = values[i]
if (i < max && (!lastTuple || lastTuple[0] !== value)) {
lastTuple = [value, [breakpoint]]
valueBreakpoints.push(lastTuple)
} else {
lastTuple[1].push(breakpoint)
}
})
return valueBreakpoints.map(([value, breakpoints], i) => {
const props: MediaBreakpointProps<any> = {}
if (i === valueBreakpoints.length - 1) {
props.greaterThanOrEqual = breakpoints[0]
} else if (breakpoints.length === 1) {
props.at = breakpoints[0]
} else {
// TODO: This is less than ideal, would be good to have a `through`
// prop, which unlike `between` is inclusive.
props.between = [breakpoints[0], valueBreakpoints[i + 1][1][0]]
}
return [value, props] as ValueBreakpointPropsTuple<
SizeValue,
BreakpointKey
>
})
}
private _normalizeProps(
breakpointProps: MediaBreakpointProps
): MediaBreakpointProps {
if (breakpointProps.at) {
const fromIndex = this._sortedBreakpoints.indexOf(breakpointProps.at)
const to = this._sortedBreakpoints[fromIndex + 1]
return to
? { between: [breakpointProps.at, to] }
: { greaterThanOrEqual: breakpointProps.at }
}
return breakpointProps
}
private _createBreakpointQuery(
breakpointProps: MediaBreakpointProps
): string {
breakpointProps = this._normalizeProps(breakpointProps)
if (breakpointProps.lessThan) {
const width = this._breakpoints[breakpointProps.lessThan]
return `(max-width:${width - 1}px)`
} else if (breakpointProps.greaterThan) {
const width = this._breakpoints[
this._findNextBreakpoint(breakpointProps.greaterThan)
]
return `(min-width:${width}px)`
} else if (breakpointProps.greaterThanOrEqual) {
const width = this._breakpoints[breakpointProps.greaterThanOrEqual]
return `(min-width:${width}px)`
} else if (breakpointProps.between) {
// TODO: This is the only useful breakpoint to negate, but we’ll
// we’ll see when/if we need it. We could then also decide
// to add `outside`.
const fromWidth = this._breakpoints[breakpointProps.between[0]]
const toWidth = this._breakpoints[breakpointProps.between[1]]
return `(min-width:${fromWidth}px) and (max-width:${toWidth - 1}px)`
}
throw new Error(
`Unexpected breakpoint props: ${JSON.stringify(breakpointProps)}`
)
}
private _createBreakpointQueries(
key: BreakpointConstraintKey,
forBreakpoints: ReadonlyArray<string | [string, string]>
) {
return forBreakpoints.reduce<Map<string, string>>((map, breakpoint) => {
map.set(
breakpointKey(breakpoint),
this._createBreakpointQuery({
[key]: breakpoint,
})
)
return map
}, new Map())
}
private _findNextBreakpoint(breakpoint: string) {
const nextBreakpoint = this._sortedBreakpoints[
this._sortedBreakpoints.indexOf(breakpoint) + 1
]
if (!nextBreakpoint) {
throw new Error(`There is no breakpoint larger than ${breakpoint}`)
}
return nextBreakpoint
}
}