-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
366 lines (324 loc) · 10.6 KB
/
index.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
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
import { createElement, useEffect, useState } from 'react'
import { Dimensions, ViewStyle, TextStyle, View, StyleProp, Platform } from 'react-native'
import type {
Scale,
Value,
StyleSheet,
BreakpointKeys,
NativeStyle,
PlatformStyleProp,
MediaStyleProp,
OrientationStyleProp,
StyleSheetFlat,
StyleProps,
CurrentBreakpoints,
CustomBreakpoints,
StyleValue,
} from './types'
import { avoidZero } from './helper'
export { Styled } from './styled'
export { SelectBreakpoint } from './SelectBreakpoint'
export { CurrentBreakpoints as Breakpoints, CustomBreakpoints }
export const linearScale = (
value: number,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
breakpoint: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
orientation: 'portrait' | 'landscape',
) => {
if (value === 0) {
return 0
}
if (app.width <= app.scale.minimum) {
return avoidZero(Math.round(value - app.scale.factor * (value / 2)), value)
}
if (app.width >= app.scale.maximum) {
return Math.round(value + app.scale.factor * (value / 2))
}
const percentage = (app.width - app.scale.minimum) / (app.scale.maximum - app.scale.minimum)
return avoidZero(Math.round(value - (app.scale.factor / 2) * value + percentage * app.scale.factor * value), value)
}
const app = {
get orientation() {
const { width, height } = Dimensions.get('screen')
return height >= width ? 'portrait' : 'landscape'
},
get width() {
return Dimensions.get('window').width
},
_breakpoints: { small: 360, medium: 420, large: 999 } as unknown as CurrentBreakpoints,
_breakpoint: 'small',
_breakpointAdapted: false,
get breakpoints() {
return this._breakpoints
},
set breakpoints(value: CurrentBreakpoints) {
this._breakpoints = value
},
get breakpoint() {
return this._breakpoint
},
set breakpoint(value: string) {
this._breakpoint = value
},
scale: {
minimum: 320,
maximum: 520,
factor: 0.5,
} as Scale,
rerender: () => {
updateBreakpoint()
app.listener.forEach((listener) => listener())
app.rerenderComponents.forEach((update) => update())
},
rerenderComponents: [] as Function[],
// Calculates a scaled value.
value: linearScale,
// Updates the current breakpoint depending on window width.
updateBreakpoint: () => {
const breakpointKeys = Object.keys(app.breakpoints)
let match: string = breakpointKeys[breakpointKeys.length - 1]
Object.entries(app.breakpoints)
.reverse()
.map(([key, value]) => {
if (value >= app.width) {
match = key
}
})
return match
},
// Rerender listeners to update styled components.
listener: [] as (() => void)[],
}
app.breakpoint = app.updateBreakpoint()
// Rerender on orientation change.
Dimensions.addEventListener('change', () => {
updateBreakpoint()
app.rerender()
})
// Only the following numeric values listed are scaled, avoids scaling things like "flex: 1".
const sizeProperties: Partial<Record<keyof ViewStyle | keyof TextStyle, true>> = {
padding: true,
paddingTop: true,
paddingRight: true,
paddingBottom: true,
paddingLeft: true,
margin: true,
marginTop: true,
marginRight: true,
marginBottom: true,
marginLeft: true,
fontSize: true,
letterSpacing: true,
lineHeight: true,
width: true,
shadowRadius: true,
shadowOffset: true,
textShadowRadius: true,
height: true,
borderRadius: true,
borderWidth: true,
borderBottomWidth: true,
borderEndWidth: true,
borderLeftWidth: true,
borderRightWidth: true,
borderStartWidth: true,
borderTopWidth: true,
bottom: true,
left: true,
marginEnd: true,
marginHorizontal: true,
marginStart: true,
marginVertical: true,
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true,
paddingEnd: true,
paddingHorizontal: true,
paddingStart: true,
paddingVertical: true,
right: true,
start: true,
top: true,
borderBottomEndRadius: true,
borderBottomLeftRadius: true,
borderBottomRightRadius: true,
borderBottomStartRadius: true,
borderTopEndRadius: true,
borderTopLeftRadius: true,
borderTopRightRadius: true,
borderTopStartRadius: true,
// @ts-ignore Will be released with React Native 0.71 (already works in web).
gap: true,
rowGap: true,
columnGap: true,
}
export const getBreakpoints = () => app.breakpoints
export const setBreakpoint = (breakpoint: string) => {
app._breakpointAdapted = true
app.breakpoint = breakpoint
app.rerender()
}
export const getBreakpoint = () => app.breakpoint as keyof CurrentBreakpoints
export const getOrientation = () => app.orientation
export const getValue = (value: number) => app.value(value, app.breakpoint, app.orientation)
export const updateBreakpoint = () => {
if (!app._breakpointAdapted) {
app.breakpoint = app.updateBreakpoint()
}
}
export const registerListener = (listener: () => void) => app.listener.push(listener)
export const removeListener = (listener: () => void) => {
app.listener = app.listener.filter((item) => item !== listener)
}
export const useResponsive = () => {
const [count, setCount] = useState(0)
useEffect(() => {
const listener = () => setCount(count + 1)
registerListener(listener)
return () => removeListener(listener)
}, [count])
return { breakpoint: getBreakpoint(), setBreakpoint, orientation: app.orientation }
}
export const reset = () => {
app._breakpointAdapted = false
app.breakpoint = app.updateBreakpoint()
app.scale = {
minimum: 320,
maximum: 520,
factor: 0.5,
}
}
export const rerender = () => app.rerender()
export const Rerender = ({
children,
style = { flex: 1, width: '100%' },
}: {
children: () => JSX.Element | JSX.Element[]
style?: StyleProp<ViewStyle> | StyleProp<ViewStyle>[]
}) => {
const [count, setCount] = useState(0)
app.rerenderComponents.push(() => setCount(count + 1))
return createElement(View, { style, key: count, children: children() })
}
// Does the object contain a breakpoint key?
const hasBreakpointKey = <T extends keyof NativeStyle>(value: MediaStyleProp<T>) => {
return (Object.keys(app.breakpoints) as BreakpointKeys).some((key) => typeof value[key] !== 'undefined')
}
const hasPlatformKey = <T extends keyof NativeStyle>(value: PlatformStyleProp<T>) => {
return typeof value.ios !== 'undefined' || typeof value.android !== 'undefined'
}
const closestBreakpointValue = <T extends keyof NativeStyle>(value: MediaStyleProp<T>, property: T) => {
const breakpoints = Object.keys(app.breakpoints) as BreakpointKeys
const currentBreakpointIndex = breakpoints.findIndex((current: string) => current === app.breakpoint)
const applicableBreakpoints = breakpoints.splice(0, currentBreakpointIndex + 1).reverse()
for (let index = 0; index < applicableBreakpoints.length; index++) {
// @ts-ignore TODO this assumes nesting.
const current = value[applicableBreakpoints[index]]
if (typeof current !== 'undefined') {
if (Array.isArray(current) && current.length === 2 && property !== 'transform') {
return app.orientation === 'portrait' ? current[0] : current[1]
}
return current
}
}
}
export const responsiveProperty = (
property: keyof NativeStyle,
value: StyleValue<keyof NativeStyle>,
nestingFunction: (value: StyleProps<keyof NativeStyle>) => any,
): NativeStyle[keyof NativeStyle] => {
const valueType = typeof value
if (valueType === 'string') {
return value as NativeStyle[keyof NativeStyle]
}
if (valueType === 'number') {
// @ts-ignore
if (sizeProperties[property]) {
return app.value(value as number, app.breakpoint, app.orientation)
} else {
return value as NativeStyle[keyof NativeStyle]
}
}
const isArray = Array.isArray(value)
if (isArray && value.length === 2 && property !== 'transform') {
let orientationValue = (app.orientation === 'portrait' ? value[0] : value[1]) as StyleValue<keyof NativeStyle>
if (typeof orientationValue === 'object') {
orientationValue = closestBreakpointValue(
orientationValue as MediaStyleProp<keyof NativeStyle>,
property,
) as StyleValue<keyof NativeStyle>
}
return responsiveProperty(property, orientationValue as OrientationStyleProp<keyof NativeStyle>, nestingFunction)
}
if (!isArray && valueType === 'object' && hasBreakpointKey(value as MediaStyleProp<keyof NativeStyle>)) {
return closestBreakpointValue(
value as MediaStyleProp<keyof NativeStyle>,
property,
) as NativeStyle[keyof NativeStyle]
}
if (!isArray && valueType === 'object' && hasPlatformKey(value as PlatformStyleProp<keyof NativeStyle>)) {
const valueByPlatform = (value as any)[Platform.OS]
if (typeof valueByPlatform !== 'number') {
return responsiveProperty(property, valueByPlatform as OrientationStyleProp<keyof NativeStyle>, nestingFunction)
}
return app.value(valueByPlatform, app.breakpoint, app.orientation)
}
// Recursively scale nested values like shadowOffset.
if (typeof value === 'object' && property !== 'transform') {
return nestingFunction(value as StyleProps<keyof NativeStyle>)
}
return value as NativeStyle[keyof NativeStyle]
}
const createProxy = <T extends keyof NativeStyle>(target: StyleProps<T>) => {
// Copy target to avoid proxy modifying the original.
const initialTarget = { ...target }
return new Proxy(target, {
get(_, prop: keyof StyleProps<T>): any {
const value = initialTarget[prop]
return responsiveProperty(prop, value, createProxy)
},
})
}
export const createStyles = <K extends string, T extends Record<K, NativeStyle>>(sheet: StyleSheet<K, T>) => {
if (process.env.NODE_ENV !== 'production' && typeof sheet !== 'object') {
console.warn('Invalid input provided to createStyles() needs to be an object.')
}
Object.keys(sheet).forEach((key) => {
const styles = sheet[key as K]
if (process.env.NODE_ENV !== 'production' && typeof styles !== 'object') {
console.warn(`Invalid input provided to createStyles() property ${String(key)} to be an object.`)
}
sheet[key as K] = createProxy(styles) as any
})
return sheet as StyleSheetFlat<K, T>
}
export const configure = ({
breakpoints,
breakpoint,
scale,
value,
}: {
breakpoints?: CurrentBreakpoints
breakpoint?: string
scale?: { minimum?: number; maximum?: number; factor?: number }
value?: Value
}) => {
if (breakpoints) {
app.breakpoints = breakpoints
// @ts-ignore
if (!breakpoint && !app.breakpoints[app.breakpoint]) {
app.breakpoint = Object.keys(app.breakpoints)[0]
}
}
if (breakpoint) {
app.breakpoint = breakpoint
}
if (scale) {
Object.assign(app.scale, scale)
}
if (value) {
app.value = value
}
}