UNPKG

1.8 kBJavaScriptView Raw
1// @flow
2import type {
3 Ctor,
4 CreateRenderFnOptions,
5 CreateHOCOptions,
6 CreateHOC,
7 CreateHOCc,
8} from './annotations';
9
10import courier from './courier';
11import {createRenderFnc} from './createRenderFn';
12import Vue from 'vue';
13
14const defaultStrategy = (parent, child) => child;
15
16const normalizeProps = (props: Object | Array<string> | void) => {
17 if (!props){
18 return {};
19 }
20 if (Array.isArray(props)){
21 const obj = {};
22 props.forEach((key) => {
23 if (typeof key === 'string'){
24 obj[key] = {};
25 }
26 });
27 return obj;
28 }
29 return Object.assign({}, props);
30};
31
32export const createHOC: CreateHOC = (Component, options, renderOptions) => {
33 const hoc: Ctor = {
34 props: normalizeProps((typeof Component === 'function')
35 ? Component.options.props
36 : Component.props),
37 mixins: [],
38 name: `${Component.name || 'Anonymous'}HOC`,
39 render: createRenderFnc(renderOptions),
40 };
41 if (options){
42 Object.keys(options).forEach((key) => {
43 const child = options && options[key];
44 const parent = hoc[key];
45 const strategy: Function = Vue.config.optionMergeStrategies[key] || defaultStrategy;
46
47 if (key === 'props'){
48
49 // $FlowFixMe
50 hoc[key] = strategy(parent, normalizeProps(child));
51 }else{
52 hoc[key] = strategy(parent, child);
53 }
54 });
55 }
56
57 hoc.mixins && hoc.mixins.push({
58 created(){
59 this.$createElement = this.$parent.$createElement;
60 }
61 });
62
63 if (hoc.render && hoc.render.curried){
64 hoc.render = hoc.render(Component);
65 }
66
67 return hoc;
68};
69
70export const createHOCc: CreateHOCc = courier(3, (
71 options: CreateHOCOptions,
72 renderOptions: CreateRenderFnOptions,
73 Component: Ctor
74) => {
75 return createHOC(Component, options, renderOptions);
76});
77
78export default createHOC;