1 | import { promises as fs } from 'fs'
|
2 | import ensureFile from './ensure-file.js'
|
3 | import path from 'path'
|
4 |
|
5 | let makeUseIsMedia = media => `// This file is automatically generated by Views and will be overwritten
|
6 | // when the morpher runs. If you want to contribute to how it's generated, eg,
|
7 | // improving the algorithms inside, etc, see this:
|
8 | // https://github.com/viewstools/morph/blob/master/ensure-is-media.js
|
9 |
|
10 | import { useMedia } from 'use-media';
|
11 |
|
12 | let useIsMedia = () => ({
|
13 | ${media
|
14 | .map(({ name, minWidth, maxWidth }) => {
|
15 | let ret = [`"${name}": useMedia({ minWidth: ${minWidth}`]
|
16 | if (maxWidth) {
|
17 | ret.push(`, maxWidth: ${maxWidth}`)
|
18 | }
|
19 | ret.push('})')
|
20 | return ret.join('')
|
21 | })
|
22 | .join(',')}
|
23 | })
|
24 | export default useIsMedia`
|
25 |
|
26 | async function getMediaConfig(src) {
|
27 | let media = {
|
28 | mobile: {
|
29 | width: 414,
|
30 | },
|
31 | tablet: {
|
32 | width: 1024,
|
33 | },
|
34 | laptop: {
|
35 | width: 1280,
|
36 | },
|
37 | }
|
38 | try {
|
39 | media = JSON.parse(
|
40 | await fs.readFile(
|
41 | path.resolve(path.join(src, '..', 'app.viewstools')),
|
42 | 'utf8'
|
43 | )
|
44 | ).media
|
45 | delete media.base
|
46 | } catch (error) {}
|
47 |
|
48 | return Object.entries(media)
|
49 | .sort((a, b) => a[1].width - b[1].width)
|
50 | .map(([name, item], index, list) => ({
|
51 | name,
|
52 | minWidth: index === 0 ? 0 : list[index - 1][1].width + 1,
|
53 | maxWidth:
|
54 | index === 0
|
55 | ? item.width
|
56 | : index === list.length - 1
|
57 | ? null
|
58 | : item.width,
|
59 | }))
|
60 | }
|
61 |
|
62 | export default async function ensureIsMedia({ src }) {
|
63 | return ensureFile({
|
64 | file: path.join(src, 'Logic', 'useIsMedia.js'),
|
65 | content: makeUseIsMedia(await getMediaConfig(src)),
|
66 | })
|
67 | }
|