1 | import createSlug from 'slug';
|
2 | import { Wallboard as Board } from './components/Wallboard';
|
3 | import { Widget } from './components/Widget';
|
4 | import React from 'react';
|
5 | import invariant from 'invariant';
|
6 |
|
7 |
|
8 | function createWidgetFromReactElement(element, board) {
|
9 | const type = element.type;
|
10 | const widget = { ...type.defaultProps, ...element.props };
|
11 | const idx = board.children.indexOf(element);
|
12 |
|
13 | widget.id = `${board.slug}-${idx}`;
|
14 |
|
15 | if (widget.children) {
|
16 | widget.render = widget.children;
|
17 | delete widget.children;
|
18 | }
|
19 |
|
20 | return widget;
|
21 | }
|
22 |
|
23 | function createWidgetsFromReactChildren(children, board) {
|
24 | const widgets = [];
|
25 |
|
26 | React.Children.forEach(children, (element) => {
|
27 | if (React.isValidElement(element)) {
|
28 | widgets.push(createWidgetFromReactElement(element, board));
|
29 | }
|
30 | });
|
31 |
|
32 | return widgets;
|
33 | }
|
34 |
|
35 | function createBoardFromReactElement(element) {
|
36 | const type = element.type;
|
37 | const board = { ...type.defaultProps, ...element.props };
|
38 |
|
39 | board.slug = createSlug(board.name, { lower: true });
|
40 |
|
41 | if (board.children) {
|
42 | const widgets = createWidgetsFromReactChildren(board.children, board);
|
43 |
|
44 | if (widgets.length) {
|
45 | board.widgets = widgets;
|
46 | }
|
47 |
|
48 | delete board.children;
|
49 | }
|
50 |
|
51 | return board;
|
52 | }
|
53 |
|
54 | function createBoardsFromReactChildren(children) {
|
55 | const boards = [];
|
56 |
|
57 | React.Children.forEach(children, (element) => {
|
58 | if (React.isValidElement(element)) {
|
59 | boards.push(createBoardFromReactElement(element));
|
60 | }
|
61 | });
|
62 |
|
63 | return boards;
|
64 | }
|
65 |
|
66 | export function parseConfig(config) {
|
67 | const result = {};
|
68 |
|
69 | if (process.env.NODE_ENV !== 'production') {
|
70 | if (!React.isValidElement(config)) {
|
71 | invariant(false, 'Cyboard config need to be a react element of <Cyboard /> component.');
|
72 | }
|
73 | }
|
74 |
|
75 | const boards = createBoardsFromReactChildren(config.props.children);
|
76 |
|
77 | boards.forEach((board) => {
|
78 | result[board.slug] = board;
|
79 | });
|
80 |
|
81 | return result;
|
82 | }
|