@stoplight/elements-dev-portal 1.4.8 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { ModalProps } from '@stoplight/mosaic';
2
2
  import * as React from 'react';
3
3
  import { NodeSearchResult } from '../../types';
4
4
  export declare type SearchProps = {
5
+ isLoading?: boolean;
5
6
  search?: string;
6
7
  searchResults?: NodeSearchResult[];
7
8
  onSearch: (search: string) => void;
package/index.esm.js CHANGED
@@ -1,15 +1,13 @@
1
1
  import { Menu, FieldButton, Modal, Input, Box, Icon, ListBox, ListBoxItem, Flex, VStack, Heading } from '@stoplight/mosaic';
2
2
  import * as React from 'react';
3
- import React__default from 'react';
4
- import { withQueryClientProvider, withMosaicProvider, PersistenceContextProvider, MarkdownComponentsProvider, MockingProvider, Docs, withStyles, withPersistenceBoundary, NodeTypeIconDefs, NodeTypeColors, TableOfContents as TableOfContents$1, PoweredByLink, useRouter, findFirstNode, ReactRouterMarkdownLink, SidebarLayout } from '@stoplight/elements-core';
3
+ import React__default, { useRef, useEffect, useMemo, useCallback, useState } from 'react';
4
+ import { withPersistenceBoundary, withQueryClientProvider, withMosaicProvider, MarkdownComponentsProvider, MockingProvider, Docs, withStyles, NodeTypeIconDefs, NodeTypeColors, TableOfContents as TableOfContents$1, PoweredByLink, useRouter, findFirstNode, ReactRouterMarkdownLink, SidebarLayout } from '@stoplight/elements-core';
5
5
  import { resolve, dirname } from '@stoplight/path';
6
6
  import { NodeType } from '@stoplight/types';
7
- import { faSearch } from '@fortawesome/free-solid-svg-icons/faSearch';
8
- import { flow } from 'lodash';
7
+ import { faSpinner, faSearch, faCircleNotch, faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
8
+ import flow from 'lodash/flow.js';
9
9
  import { Route, useParams, useHistory, Redirect, Link } from 'react-router-dom';
10
- import { faCircleNotch, faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
11
10
  import { useQuery } from 'react-query';
12
- import { useDebounce } from 'use-debounce';
13
11
 
14
12
  const BranchSelector = ({ branchSlug, branches, onChange }) => {
15
13
  const currentBranch = branches.find(branch => (!branchSlug ? branch.is_default : branch.slug === branchSlug));
@@ -38,27 +36,26 @@ const PlatformContext = React.createContext({ platformUrl: 'https://stoplight.io
38
36
  const PlatformProvider = ({ platformUrl = 'https://stoplight.io', platformAuthToken, children, }) => {
39
37
  return React.createElement(PlatformContext.Provider, { value: { platformUrl, platformAuthToken } }, children);
40
38
  };
41
- const DevPortalProvider = withQueryClientProvider(withMosaicProvider(PlatformProvider));
39
+ const DevPortalProvider = withPersistenceBoundary(withQueryClientProvider(withMosaicProvider(PlatformProvider)));
42
40
 
43
41
  const NodeContent = ({ node, Link, hideTryIt, hideTryItPanel, hideMocking, hideExport, tryItCredentialsPolicy, tryItCorsProxy, }) => {
44
- return (React.createElement(PersistenceContextProvider, null,
45
- React.createElement(NodeLinkContext.Provider, { value: [node, Link] },
46
- React.createElement(MarkdownComponentsProvider, { value: { a: LinkComponent } },
47
- React.createElement(MockingProvider, { mockUrl: node.links.mock_url, hideMocking: hideMocking },
48
- React.createElement(Docs, { nodeType: node.type, nodeData: node.data, nodeTitle: node.title, layoutOptions: {
49
- hideTryIt: hideTryIt,
50
- hideTryItPanel: hideTryItPanel,
51
- hideExport: hideExport || node.links.export_url === undefined,
52
- }, useNodeForRefResolving: true, tryItCorsProxy: tryItCorsProxy, exportProps: [NodeType.HttpService, NodeType.Model].includes(node.type)
53
- ? {
54
- original: {
55
- href: node.links.export_url,
56
- },
57
- bundled: {
58
- href: getBundledUrl(node.links.export_url),
59
- },
60
- }
61
- : undefined, tryItCredentialsPolicy: tryItCredentialsPolicy }))))));
42
+ return (React.createElement(NodeLinkContext.Provider, { value: [node, Link] },
43
+ React.createElement(MarkdownComponentsProvider, { value: { a: LinkComponent } },
44
+ React.createElement(MockingProvider, { mockUrl: node.links.mock_url, hideMocking: hideMocking },
45
+ React.createElement(Docs, { nodeType: node.type, nodeData: node.data, nodeTitle: node.title, layoutOptions: {
46
+ hideTryIt: hideTryIt,
47
+ hideTryItPanel: hideTryItPanel,
48
+ hideExport: hideExport || node.links.export_url === undefined,
49
+ }, useNodeForRefResolving: true, tryItCorsProxy: tryItCorsProxy, exportProps: [NodeType.HttpService, NodeType.Model].includes(node.type)
50
+ ? {
51
+ original: {
52
+ href: node.links.export_url,
53
+ },
54
+ bundled: {
55
+ href: getBundledUrl(node.links.export_url),
56
+ },
57
+ }
58
+ : undefined, tryItCredentialsPolicy: tryItCredentialsPolicy })))));
62
59
  };
63
60
  const NodeLinkContext = React.createContext(undefined);
64
61
  const externalRegex = new RegExp('^(?:[a-z]+:)?//', 'i');
@@ -90,7 +87,7 @@ function getBundledUrl(url) {
90
87
  return bundledUrl.toString();
91
88
  }
92
89
 
93
- const SearchImpl = ({ search, searchResults, isOpen, onClose, onClick, onSearch }) => {
90
+ const SearchImpl = ({ isLoading, search, searchResults, isOpen, onClose, onClick, onSearch }) => {
94
91
  const listBoxRef = React.useRef(null);
95
92
  const onChange = React.useCallback(e => onSearch(e.currentTarget.value), [onSearch]);
96
93
  const onKeyDown = React.useCallback(e => {
@@ -107,7 +104,7 @@ const SearchImpl = ({ search, searchResults, isOpen, onClose, onClick, onSearch
107
104
  onClick(selectedResult);
108
105
  }
109
106
  }, [searchResults, onClick]);
110
- return (React.createElement(Modal, { renderHeader: () => (React.createElement(Input, { appearance: "minimal", borderB: true, size: "lg", icon: React.createElement(Box, { as: Icon, ml: 1, icon: faSearch }), autoFocus: true, placeholder: "Search...", value: search, onChange: onChange, onKeyDown: onKeyDown })), isOpen: !!isOpen, onClose: onClose }, searchResults && searchResults.length > 0 ? (React.createElement(ListBox, { ref: listBoxRef, "aria-label": "Search", overflowY: "auto", h: 80, m: -5, items: searchResults, selectionMode: "single", onSelectionChange: onSelectionChange }, (searchResult) => {
107
+ return (React.createElement(Modal, { renderHeader: () => (React.createElement(Input, { appearance: "minimal", borderB: true, size: "lg", icon: React.createElement(Box, { as: Icon, ml: 1, icon: isLoading ? faSpinner : faSearch, spin: isLoading }), autoFocus: true, placeholder: "Search...", value: search, onChange: onChange, onKeyDown: onKeyDown })), isOpen: !!isOpen, onClose: onClose }, searchResults && searchResults.length > 0 ? (React.createElement(ListBox, { ref: listBoxRef, "aria-label": "Search", overflowY: "auto", h: 80, m: -5, items: searchResults, selectionMode: "single", onSelectionChange: onSelectionChange }, (searchResult) => {
111
108
  var _a, _b;
112
109
  return (React.createElement(ListBoxItem, { key: `${searchResult.id}-${searchResult.project_id}`, textValue: searchResult.title },
113
110
  React.createElement(Box, { p: 3, borderB: true },
@@ -182,7 +179,7 @@ const UpgradeToStarter = () => (React__default.createElement(Flex, { as: "a", hr
182
179
  React__default.createElement(Icon, { icon: faExclamationTriangle, size: "4x" }),
183
180
  React__default.createElement(Box, { pt: 3 }, "Please upgrade your Stoplight Workspace to the Starter Plan to use Elements Dev Portal in production.")));
184
181
 
185
- const appVersion = '1.4.8';
182
+ const appVersion = '1.6.1';
186
183
 
187
184
  class ResponseError extends Error {
188
185
  constructor(message, responseCode) {
@@ -308,8 +305,8 @@ const StoplightProjectImpl = ({ projectId, hideTryIt, hideMocking, hideExport, c
308
305
  tableOfContents ? (React.createElement(TableOfContents, { activeId: (node === null || node === void 0 ? void 0 : node.id) || (nodeSlug === null || nodeSlug === void 0 ? void 0 : nodeSlug.split('-')[0]) || '', tableOfContents: tableOfContents, Link: Link, collapseTableOfContents: collapseTableOfContents, onLinkClick: handleTocClick })) : null) }, elem));
309
306
  };
310
307
  const StoplightProjectRouter = (_a) => {
311
- var { platformUrl, basePath = '/', router } = _a, props = __rest(_a, ["platformUrl", "basePath", "router"]);
312
- const { Router, routerProps } = useRouter(router !== null && router !== void 0 ? router : 'history', basePath);
308
+ var { platformUrl, basePath = '/', staticRouterPath = '', router = 'history' } = _a, props = __rest(_a, ["platformUrl", "basePath", "staticRouterPath", "router"]);
309
+ const { Router, routerProps } = useRouter(router, basePath, staticRouterPath);
313
310
  return (React.createElement(DevPortalProvider, { platformUrl: platformUrl },
314
311
  React.createElement(Router, Object.assign({}, routerProps, { key: basePath }),
315
312
  React.createElement(Route, { path: "/branches/:branchSlug/:nodeSlug", exact: true },
@@ -319,7 +316,7 @@ const StoplightProjectRouter = (_a) => {
319
316
  React.createElement(Route, { path: "/", exact: true },
320
317
  React.createElement(StoplightProjectImpl, Object.assign({}, props))))));
321
318
  };
322
- const StoplightProject = flow(withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider)(StoplightProjectRouter);
319
+ const StoplightProject = withStyles(StoplightProjectRouter);
323
320
 
324
321
  const getNodes = ({ workspaceId, branchSlug, projectIds, search, platformUrl = 'https://stoplight.io', platformAuthToken, }) => __awaiter(void 0, void 0, void 0, function* () {
325
322
  const queryParams = [];
@@ -362,10 +359,237 @@ const getWorkspace = ({ projectIds, platformUrl = 'https://stoplight.io', platfo
362
359
  return data;
363
360
  });
364
361
 
362
+ /**
363
+ * Creates a debounced function that delays invoking `func` until after `wait`
364
+ * milliseconds have elapsed since the last time the debounced function was
365
+ * invoked, or until the next browser frame is drawn. The debounced function
366
+ * comes with a `cancel` method to cancel delayed `func` invocations and a
367
+ * `flush` method to immediately invoke them. Provide `options` to indicate
368
+ * whether `func` should be invoked on the leading and/or trailing edge of the
369
+ * `wait` timeout. The `func` is invoked with the last arguments provided to the
370
+ * debounced function. Subsequent calls to the debounced function return the
371
+ * result of the last `func` invocation.
372
+ *
373
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
374
+ * invoked on the trailing edge of the timeout only if the debounced function
375
+ * is invoked more than once during the `wait` timeout.
376
+ *
377
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
378
+ * until the next tick, similar to `setTimeout` with a timeout of `0`.
379
+ *
380
+ * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
381
+ * invocation will be deferred until the next frame is drawn (typically about
382
+ * 16ms).
383
+ *
384
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
385
+ * for details over the differences between `debounce` and `throttle`.
386
+ *
387
+ * @category Function
388
+ * @param {Function} func The function to debounce.
389
+ * @param {number} [wait=0]
390
+ * The number of milliseconds to delay; if omitted, `requestAnimationFrame` is
391
+ * used (if available, otherwise it will be setTimeout(...,0)).
392
+ * @param {Object} [options={}] The options object.
393
+ * Specify invoking on the leading edge of the timeout.
394
+ * @param {boolean} [options.leading=false]
395
+ * The maximum time `func` is allowed to be delayed before it's invoked.
396
+ * @param {number} [options.maxWait]
397
+ * Specify invoking on the trailing edge of the timeout.
398
+ * @param {boolean} [options.trailing=true]
399
+ * @returns {Function} Returns the new debounced function.
400
+ * @example
401
+ *
402
+ * // Avoid costly calculations while the window size is in flux.
403
+ * const resizeHandler = useDebouncedCallback(calculateLayout, 150);
404
+ * window.addEventListener('resize', resizeHandler)
405
+ *
406
+ * // Invoke `sendMail` when clicked, debouncing subsequent calls.
407
+ * const clickHandler = useDebouncedCallback(sendMail, 300, {
408
+ * leading: true,
409
+ * trailing: false,
410
+ * })
411
+ * <button onClick={clickHandler}>click me</button>
412
+ *
413
+ * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
414
+ * const debounced = useDebouncedCallback(batchLog, 250, { 'maxWait': 1000 })
415
+ * const source = new EventSource('/stream')
416
+ * source.addEventListener('message', debounced)
417
+ *
418
+ * // Cancel the trailing debounced invocation.
419
+ * window.addEventListener('popstate', debounced.cancel)
420
+ *
421
+ * // Check for pending invocations.
422
+ * const status = debounced.pending() ? "Pending..." : "Ready"
423
+ */
424
+ function useDebouncedCallback(func, wait, options) {
425
+ var _this = this;
426
+ var lastCallTime = useRef(null);
427
+ var lastInvokeTime = useRef(0);
428
+ var timerId = useRef(null);
429
+ var lastArgs = useRef([]);
430
+ var lastThis = useRef();
431
+ var result = useRef();
432
+ var funcRef = useRef(func);
433
+ var mounted = useRef(true);
434
+ funcRef.current = func;
435
+ // Bypass `requestAnimationFrame` by explicitly setting `wait=0`.
436
+ var useRAF = !wait && wait !== 0 && typeof window !== 'undefined';
437
+ if (typeof func !== 'function') {
438
+ throw new TypeError('Expected a function');
439
+ }
440
+ wait = +wait || 0;
441
+ options = options || {};
442
+ var leading = !!options.leading;
443
+ var trailing = 'trailing' in options ? !!options.trailing : true; // `true` by default
444
+ var maxing = 'maxWait' in options;
445
+ var maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : null;
446
+ useEffect(function () {
447
+ mounted.current = true;
448
+ return function () {
449
+ mounted.current = false;
450
+ };
451
+ }, []);
452
+ // You may have a question, why we have so many code under the useMemo definition.
453
+ //
454
+ // This was made as we want to escape from useCallback hell and
455
+ // not to initialize a number of functions each time useDebouncedCallback is called.
456
+ //
457
+ // It means that we have less garbage for our GC calls which improves performance.
458
+ // Also, it makes this library smaller.
459
+ //
460
+ // And the last reason, that the code without lots of useCallback with deps is easier to read.
461
+ // You have only one place for that.
462
+ var debounced = useMemo(function () {
463
+ var invokeFunc = function (time) {
464
+ var args = lastArgs.current;
465
+ var thisArg = lastThis.current;
466
+ lastArgs.current = lastThis.current = null;
467
+ lastInvokeTime.current = time;
468
+ return (result.current = funcRef.current.apply(thisArg, args));
469
+ };
470
+ var startTimer = function (pendingFunc, wait) {
471
+ if (useRAF)
472
+ cancelAnimationFrame(timerId.current);
473
+ timerId.current = useRAF ? requestAnimationFrame(pendingFunc) : setTimeout(pendingFunc, wait);
474
+ };
475
+ var shouldInvoke = function (time) {
476
+ if (!mounted.current)
477
+ return false;
478
+ var timeSinceLastCall = time - lastCallTime.current;
479
+ var timeSinceLastInvoke = time - lastInvokeTime.current;
480
+ // Either this is the first call, activity has stopped and we're at the
481
+ // trailing edge, the system time has gone backwards and we're treating
482
+ // it as the trailing edge, or we've hit the `maxWait` limit.
483
+ return (!lastCallTime.current ||
484
+ timeSinceLastCall >= wait ||
485
+ timeSinceLastCall < 0 ||
486
+ (maxing && timeSinceLastInvoke >= maxWait));
487
+ };
488
+ var trailingEdge = function (time) {
489
+ timerId.current = null;
490
+ // Only invoke if we have `lastArgs` which means `func` has been
491
+ // debounced at least once.
492
+ if (trailing && lastArgs.current) {
493
+ return invokeFunc(time);
494
+ }
495
+ lastArgs.current = lastThis.current = null;
496
+ return result.current;
497
+ };
498
+ var timerExpired = function () {
499
+ var time = Date.now();
500
+ if (shouldInvoke(time)) {
501
+ return trailingEdge(time);
502
+ }
503
+ // https://github.com/xnimorz/use-debounce/issues/97
504
+ if (!mounted.current) {
505
+ return;
506
+ }
507
+ // Remaining wait calculation
508
+ var timeSinceLastCall = time - lastCallTime.current;
509
+ var timeSinceLastInvoke = time - lastInvokeTime.current;
510
+ var timeWaiting = wait - timeSinceLastCall;
511
+ var remainingWait = maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
512
+ // Restart the timer
513
+ startTimer(timerExpired, remainingWait);
514
+ };
515
+ var func = function () {
516
+ var args = [];
517
+ for (var _i = 0; _i < arguments.length; _i++) {
518
+ args[_i] = arguments[_i];
519
+ }
520
+ var time = Date.now();
521
+ var isInvoking = shouldInvoke(time);
522
+ lastArgs.current = args;
523
+ lastThis.current = _this;
524
+ lastCallTime.current = time;
525
+ if (isInvoking) {
526
+ if (!timerId.current && mounted.current) {
527
+ // Reset any `maxWait` timer.
528
+ lastInvokeTime.current = lastCallTime.current;
529
+ // Start the timer for the trailing edge.
530
+ startTimer(timerExpired, wait);
531
+ // Invoke the leading edge.
532
+ return leading ? invokeFunc(lastCallTime.current) : result.current;
533
+ }
534
+ if (maxing) {
535
+ // Handle invocations in a tight loop.
536
+ startTimer(timerExpired, wait);
537
+ return invokeFunc(lastCallTime.current);
538
+ }
539
+ }
540
+ if (!timerId.current) {
541
+ startTimer(timerExpired, wait);
542
+ }
543
+ return result.current;
544
+ };
545
+ func.cancel = function () {
546
+ if (timerId.current) {
547
+ useRAF ? cancelAnimationFrame(timerId.current) : clearTimeout(timerId.current);
548
+ }
549
+ lastInvokeTime.current = 0;
550
+ lastArgs.current = lastCallTime.current = lastThis.current = timerId.current = null;
551
+ };
552
+ func.isPending = function () {
553
+ return !!timerId.current;
554
+ };
555
+ func.flush = function () {
556
+ return !timerId.current ? result.current : trailingEdge(Date.now());
557
+ };
558
+ return func;
559
+ }, [leading, maxing, wait, maxWait, trailing, useRAF]);
560
+ return debounced;
561
+ }
562
+
563
+ function valueEquality(left, right) {
564
+ return left === right;
565
+ }
566
+ function adjustFunctionValueOfSetState(value) {
567
+ return typeof value === 'function' ? function () { return value; } : value;
568
+ }
569
+ function useStateIgnoreCallback(initialState) {
570
+ var _a = useState(adjustFunctionValueOfSetState(initialState)), state = _a[0], setState = _a[1];
571
+ var setStateIgnoreCallback = useCallback(function (value) { return setState(adjustFunctionValueOfSetState(value)); }, []);
572
+ return [state, setStateIgnoreCallback];
573
+ }
574
+ function useDebounce(value, delay, options) {
575
+ var eq = (options && options.equalityFn) || valueEquality;
576
+ var _a = useStateIgnoreCallback(value), state = _a[0], dispatch = _a[1];
577
+ var debounced = useDebouncedCallback(useCallback(function (value) { return dispatch(value); }, [dispatch]), delay, options);
578
+ var previousValue = useRef(value);
579
+ useEffect(function () {
580
+ // We need to use this condition otherwise we will run debounce timer for the first render (including maxWait option)
581
+ if (!eq(previousValue.current, value)) {
582
+ debounced(value);
583
+ previousValue.current = value;
584
+ }
585
+ }, [value, debounced, eq]);
586
+ return [state, { cancel: debounced.cancel, isPending: debounced.isPending, flush: debounced.flush }];
587
+ }
588
+
365
589
  function useGetNodes({ search, workspaceId, branchSlug, projectIds, pause, }) {
366
590
  const { platformUrl, platformAuthToken } = React.useContext(PlatformContext);
367
591
  const [debounceSearch] = useDebounce(search, 500);
368
- return useQuery(['workspaceNodes', workspaceId, branchSlug, projectIds, debounceSearch, platformUrl, platformAuthToken], () => getNodes({ workspaceId, branchSlug, projectIds, search: debounceSearch, platformUrl, platformAuthToken }), { enabled: !pause });
592
+ return useQuery(['workspaceNodes', platformUrl, platformAuthToken, workspaceId, branchSlug, projectIds, debounceSearch], () => getNodes({ workspaceId, branchSlug, projectIds, search: debounceSearch, platformUrl, platformAuthToken }), { enabled: !pause, keepPreviousData: true });
369
593
  }
370
594
 
371
595
  function useGetWorkspace({ projectIds }) {