chunk.esm.js 8.29 KB
Newer Older
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
import { createContext, createElement, useContext, Fragment, Component, useEffect, useMemo, useRef, useState } from 'react';
import _get from 'lodash/fp/get';
import _omit from 'lodash/fp/omit';
import equal from 'fast-deep-equal';
import _merge from 'lodash/fp/merge';
import sort from 'array-sort';
import _unionBy from 'lodash/fp/unionBy';
import _flattenDepth from 'lodash/fp/flattenDepth';
import _pipe from 'lodash/fp/pipe';
import { ulid } from 'ulid';
import match from 'match-sorter';
import _throttle from 'lodash/fp/throttle';

const DefaultNotFound = () => createElement(Fragment, null, "Not found");

const DefaultLoading = () => createElement(Fragment, null, "Loading");

const DefaultPage = ({
  children
}) => createElement(Fragment, null, children);

const DefaultPlayground = ({
  component,
  code
}) => createElement(Fragment, null, component, code);

const defaultComponents = {
  loading: DefaultLoading,
  playground: DefaultPlayground,
  notFound: DefaultNotFound,
  page: DefaultPage
};
const ctx = createContext({});
const ComponentsProvider = ({
  components: themeComponents = {},
  children
}) => createElement(ctx.Provider, {
  value: Object.assign({}, defaultComponents, themeComponents)
}, children);
const useComponents = () => {
  return useContext(ctx);
};

const isFn = value => typeof value === 'function';
function flatArrFromObject(arr, prop) {
  const reducer = (arr, obj) => {
    const value = _get(prop)(obj);

    return value ? arr.concat([value]) : arr;
  };

  return Array.from(new Set(arr.reduce(reducer, [])));
}
function compare(a, b, reverse) {
  if (a < b) return reverse ? 1 : -1;
  if (a > b) return reverse ? -1 : 1;
  return 0;
}

function create(initial) {
  var _a;

  const ctx = createContext(initial);
  const listeners = new Set();

  const dispatch = fn => {
    listeners.forEach(listener => listener(fn));
  };

  return {
    context: ctx,
    set: fn => dispatch(fn),
    Provider: (_a = class Provider extends Component {
      constructor() {
        super(...arguments);
        this.state = this.props.initial || initial || {};
      }

      static getDerivedStateFromProps(props, state) {
        if (!equal(props.initial, state)) return props.initial;
        return null;
      }

      componentDidMount() {
        listeners.add(fn => this.setState(fn));
      }

      componentWillUnmount() {
        listeners.clear();
      }

      render() {
        return createElement(ctx.Provider, {
          value: this.state
        }, this.props.children);
      }

    }, _a.displayName = 'DoczStateProvider', _a)
  };
}

const doczState = create({});

const useConfig = () => {
  const state = useContext(doczState.context);
  const {
    linkComponent,
    transform,
    config,
    themeConfig = {}
  } = state;

  const newConfig = _merge(themeConfig, config ? config.themeConfig : {});

  const transformed = transform ? transform(newConfig) : newConfig;
  return Object.assign({}, config, {
    linkComponent,
    themeConfig: transformed
  });
};

const updateState = ev => {
  const {
    type,
    payload
  } = JSON.parse(ev.data);
  const prop = type.startsWith('state.') && type.split('.')[1];

  if (prop) {
    doczState.set(state => Object.assign({}, state, {
      [prop]: payload
    }));
  }
};

const useDataServer = url => {
  useEffect(() => {
    if (!url) return;
    const socket = new WebSocket(url);
    socket.onmessage = updateState;
    return () => socket.close();
  }, []);
};

const useDocs = () => {
  const {
    entries = []
  } = useContext(doczState.context);
  const arr = entries.map(({
    value
  }) => value);
  return sort(arr, (a, b) => compare(a.name, b.name));
};

const noMenu = entry => !entry.menu;

const fromMenu = menu => entry => entry.menu === menu;

const entryAsMenu = entry => ({
  name: entry.name,
  route: entry.route,
  parent: entry.parent
});

const entriesOfMenu = (menu, entries) => entries.filter(fromMenu(menu)).map(entryAsMenu);

const parseMenu = entries => name => ({
  name,
  menu: entriesOfMenu(name, entries)
});

const menusFromEntries = entries => {
  const entriesWithoutMenu = entries.filter(noMenu).map(entryAsMenu);
  const menus = flatArrFromObject(entries, 'menu').map(parseMenu(entries));
  return _unionBy('name', menus, entriesWithoutMenu);
};

const parseItemStr = item => typeof item === 'string' ? {
  name: item
} : item;

const normalize = item => {
  const selected = parseItemStr(item);
  return Object.assign({}, selected, {
    id: selected.id || ulid(),
    parent: _get('parent', selected) || _get('parent', item),
    menu: Array.isArray(selected.menu) ? selected.menu.map(normalize) : selected.menu
  });
};

const clean = item => item.href || item.route ? _omit('menu', item) : item;

const normalizeAndClean = _pipe(normalize, clean);

const mergeMenus = (entriesMenu, configMenu) => {
  const first = entriesMenu.map(normalizeAndClean);
  const second = configMenu.map(normalizeAndClean);

  const merged = _unionBy('name', first, second);

  return merged.map(item => {
    if (!item.menu) return item;
    const found = second.find(i => i.name === item.name);
    const foundMenu = found && found.menu;
    return Object.assign({}, item, {
      menu: foundMenu ? mergeMenus(item.menu, foundMenu) : item.menu || found.menu
    });
  });
};

const UNKNOWN_POS = Infinity;

const findPos = (item, orderedList = []) => {
  const name = typeof item !== 'string' ? _get('name', item) : item;
  const pos = orderedList.findIndex(item => item === name);
  return pos !== -1 ? pos : UNKNOWN_POS;
};

const compareWithMenu = (to = []) => (a, b) => {
  const list = to.map(i => i.name || i);
  return compare(findPos(a, list), findPos(b, list));
};

const sortByName = (a, b) => {
  return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
};

const sortMenus = (first, second = []) => {
  const sorted = sort(first, compareWithMenu(second), sortByName);
  return sorted.map(item => {
    if (!item.menu) return item;
    const found = second.find(menu => menu.name === item.name);
    const foundMenu = found && found.menu;
    return Object.assign({}, item, {
      menu: foundMenu ? sortMenus(item.menu, foundMenu) : sort(item.menu, sortByName)
    });
  });
};

const search = (val, menu) => {
  const items = menu.map(item => [item].concat(item.menu || []));

  const flattened = _flattenDepth(2, items);

  const flattenedDeduplicated = [...new Set(flattened)];
  return match(flattenedDeduplicated, val, {
    keys: ['name']
  });
};

const filterMenus = (items, filter) => {
  if (!filter) return items;
  return items.filter(filter).map(item => {
    if (!item.menu) return item;
    return Object.assign({}, item, {
      menu: item.menu.filter(filter)
    });
  });
};

const useMenus = opts => {
  const {
    query = ''
  } = opts || {};
  const {
    entries,
    config
  } = useContext(doczState.context);
  if (!entries) return null;
  const arr = entries.map(({
    value
  }) => value);
  const entriesMenu = menusFromEntries(arr);
  const sorted = useMemo(() => {
    const merged = mergeMenus(entriesMenu, config.menu);
    const result = sortMenus(merged, config.menu);
    return filterMenus(result, opts && opts.filter);
  }, [entries, config]);
  return query && query.length > 0 ? search(query, sorted) : sorted;
};

const usePrevious = (value, defaultValue) => {
  const ref = useRef(defaultValue);
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

const isClient = typeof window === 'object';

const getSize = (initialWidth, initialHeight) => ({
  innerHeight: isClient ? window.innerHeight : initialHeight,
  innerWidth: isClient ? window.innerWidth : initialWidth,
  outerHeight: isClient ? window.outerHeight : initialHeight,
  outerWidth: isClient ? window.outerWidth : initialWidth
});

const useWindowSize = (throttleMs = 300, initialWidth = Infinity, initialHeight = Infinity) => {
  const [windowSize, setWindowSize] = useState(getSize(initialHeight, initialHeight));

  const tSetWindowResize = _throttle(throttleMs, () => setWindowSize(getSize(initialHeight, initialHeight)));

  useEffect(() => {
    window.addEventListener('resize', tSetWindowResize);
    return () => void window.removeEventListener('resize', tSetWindowResize);
  }, []);
  return windowSize;
};

export { isFn as a, useComponents as b, doczState as c, useConfig as d, useDataServer as e, useDocs as f, useMenus as g, usePrevious as h, useWindowSize as i, ComponentsProvider as j };