@stoplight/elements-dev-portal 1.4.6 → 1.5.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
- import { Menu, FieldButton, Provider, Modal, Input, Box, Icon, ListBox, ListBoxItem, Flex, VStack, Heading } from '@stoplight/mosaic';
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, PersistenceContextProvider, MarkdownComponentsProvider, MockingProvider, Docs, withStyles, withPersistenceBoundary, withMosaicProvider, NodeTypeIconDefs, NodeTypeColors, TableOfContents as TableOfContents$1, PoweredByLink, useRouter, findFirstNode, SidebarLayout } from '@stoplight/elements-core';
3
+ import React__default, { useRef, useEffect, useMemo, useCallback, useState } 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';
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 { pipe } from 'lodash/fp';
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));
@@ -36,10 +34,9 @@ const BranchSelector = ({ branchSlug, branches, onChange }) => {
36
34
 
37
35
  const PlatformContext = React.createContext({ platformUrl: 'https://stoplight.io' });
38
36
  const PlatformProvider = ({ platformUrl = 'https://stoplight.io', platformAuthToken, children, }) => {
39
- return (React.createElement(PlatformContext.Provider, { value: { platformUrl, platformAuthToken } },
40
- React.createElement(Provider, null, children)));
37
+ return React.createElement(PlatformContext.Provider, { value: { platformUrl, platformAuthToken } }, children);
41
38
  };
42
- const DevPortalProvider = withQueryClientProvider(PlatformProvider);
39
+ const DevPortalProvider = withQueryClientProvider(withMosaicProvider(PlatformProvider));
43
40
 
44
41
  const NodeContent = ({ node, Link, hideTryIt, hideTryItPanel, hideMocking, hideExport, tryItCredentialsPolicy, tryItCorsProxy, }) => {
45
42
  return (React.createElement(PersistenceContextProvider, null,
@@ -76,7 +73,7 @@ const LinkComponent = ({ children, href }) => {
76
73
  const decodedResolvedUriWithoutAnchor = decodeURIComponent(resolvedUriWithoutAnchor);
77
74
  const edge = node.outbound_edges.find(edge => edge.uri === decodedUrl || edge.uri === decodedResolvedUriWithoutAnchor);
78
75
  if (edge) {
79
- return (React.createElement(Link, { to: edge.slug, hash: hash }, children));
76
+ return React.createElement(Link, { to: `${edge.slug}${hash && `#${hash}`}` }, children);
80
77
  }
81
78
  }
82
79
  return React.createElement("a", { href: href }, children);
@@ -91,7 +88,7 @@ function getBundledUrl(url) {
91
88
  return bundledUrl.toString();
92
89
  }
93
90
 
94
- const SearchImpl = ({ search, searchResults, isOpen, onClose, onClick, onSearch }) => {
91
+ const SearchImpl = ({ isLoading, search, searchResults, isOpen, onClose, onClick, onSearch }) => {
95
92
  const listBoxRef = React.useRef(null);
96
93
  const onChange = React.useCallback(e => onSearch(e.currentTarget.value), [onSearch]);
97
94
  const onKeyDown = React.useCallback(e => {
@@ -108,7 +105,7 @@ const SearchImpl = ({ search, searchResults, isOpen, onClose, onClick, onSearch
108
105
  onClick(selectedResult);
109
106
  }
110
107
  }, [searchResults, onClick]);
111
- 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) => {
108
+ 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) => {
112
109
  var _a, _b;
113
110
  return (React.createElement(ListBoxItem, { key: `${searchResult.id}-${searchResult.project_id}`, textValue: searchResult.title },
114
111
  React.createElement(Box, { p: 3, borderB: true },
@@ -119,7 +116,7 @@ const SearchImpl = ({ search, searchResults, isOpen, onClose, onClick, onSearch
119
116
  React.createElement(Box, { dangerouslySetInnerHTML: { __html: (_b = searchResult.highlighted.summary) !== null && _b !== void 0 ? _b : '' }, color: "muted", fontSize: "sm", mt: 1, ml: 6 }))));
120
117
  })) : (React.createElement(Flex, { w: "full", h: 80, align: "center", justify: "center", m: -5 }, "No search results"))));
121
118
  };
122
- const Search = pipe(withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider)(SearchImpl);
119
+ const Search = flow(withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider)(SearchImpl);
123
120
 
124
121
  /*! *****************************************************************************
125
122
  Copyright (c) Microsoft Corporation.
@@ -183,7 +180,7 @@ const UpgradeToStarter = () => (React__default.createElement(Flex, { as: "a", hr
183
180
  React__default.createElement(Icon, { icon: faExclamationTriangle, size: "4x" }),
184
181
  React__default.createElement(Box, { pt: 3 }, "Please upgrade your Stoplight Workspace to the Starter Plan to use Elements Dev Portal in production.")));
185
182
 
186
- const appVersion = '1.4.6';
183
+ const appVersion = '1.5.1';
187
184
 
188
185
  class ResponseError extends Error {
189
186
  constructor(message, responseCode) {
@@ -297,7 +294,7 @@ const StoplightProjectImpl = ({ projectId, hideTryIt, hideMocking, hideExport, c
297
294
  elem = React.createElement(NotFound, null);
298
295
  }
299
296
  else {
300
- elem = (React.createElement(NodeContent, { node: node, Link: Link, hideTryIt: hideTryIt, hideMocking: hideMocking, hideExport: hideExport, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy }));
297
+ elem = (React.createElement(NodeContent, { node: node, Link: ReactRouterMarkdownLink, hideTryIt: hideTryIt, hideMocking: hideMocking, hideExport: hideExport, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy }));
301
298
  }
302
299
  const handleTocClick = () => {
303
300
  if (container.current) {
@@ -320,7 +317,7 @@ const StoplightProjectRouter = (_a) => {
320
317
  React.createElement(Route, { path: "/", exact: true },
321
318
  React.createElement(StoplightProjectImpl, Object.assign({}, props))))));
322
319
  };
323
- const StoplightProject = pipe(withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider)(StoplightProjectRouter);
320
+ const StoplightProject = flow(withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider)(StoplightProjectRouter);
324
321
 
325
322
  const getNodes = ({ workspaceId, branchSlug, projectIds, search, platformUrl = 'https://stoplight.io', platformAuthToken, }) => __awaiter(void 0, void 0, void 0, function* () {
326
323
  const queryParams = [];
@@ -363,10 +360,237 @@ const getWorkspace = ({ projectIds, platformUrl = 'https://stoplight.io', platfo
363
360
  return data;
364
361
  });
365
362
 
363
+ /**
364
+ * Creates a debounced function that delays invoking `func` until after `wait`
365
+ * milliseconds have elapsed since the last time the debounced function was
366
+ * invoked, or until the next browser frame is drawn. The debounced function
367
+ * comes with a `cancel` method to cancel delayed `func` invocations and a
368
+ * `flush` method to immediately invoke them. Provide `options` to indicate
369
+ * whether `func` should be invoked on the leading and/or trailing edge of the
370
+ * `wait` timeout. The `func` is invoked with the last arguments provided to the
371
+ * debounced function. Subsequent calls to the debounced function return the
372
+ * result of the last `func` invocation.
373
+ *
374
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
375
+ * invoked on the trailing edge of the timeout only if the debounced function
376
+ * is invoked more than once during the `wait` timeout.
377
+ *
378
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
379
+ * until the next tick, similar to `setTimeout` with a timeout of `0`.
380
+ *
381
+ * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
382
+ * invocation will be deferred until the next frame is drawn (typically about
383
+ * 16ms).
384
+ *
385
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
386
+ * for details over the differences between `debounce` and `throttle`.
387
+ *
388
+ * @category Function
389
+ * @param {Function} func The function to debounce.
390
+ * @param {number} [wait=0]
391
+ * The number of milliseconds to delay; if omitted, `requestAnimationFrame` is
392
+ * used (if available, otherwise it will be setTimeout(...,0)).
393
+ * @param {Object} [options={}] The options object.
394
+ * Specify invoking on the leading edge of the timeout.
395
+ * @param {boolean} [options.leading=false]
396
+ * The maximum time `func` is allowed to be delayed before it's invoked.
397
+ * @param {number} [options.maxWait]
398
+ * Specify invoking on the trailing edge of the timeout.
399
+ * @param {boolean} [options.trailing=true]
400
+ * @returns {Function} Returns the new debounced function.
401
+ * @example
402
+ *
403
+ * // Avoid costly calculations while the window size is in flux.
404
+ * const resizeHandler = useDebouncedCallback(calculateLayout, 150);
405
+ * window.addEventListener('resize', resizeHandler)
406
+ *
407
+ * // Invoke `sendMail` when clicked, debouncing subsequent calls.
408
+ * const clickHandler = useDebouncedCallback(sendMail, 300, {
409
+ * leading: true,
410
+ * trailing: false,
411
+ * })
412
+ * <button onClick={clickHandler}>click me</button>
413
+ *
414
+ * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
415
+ * const debounced = useDebouncedCallback(batchLog, 250, { 'maxWait': 1000 })
416
+ * const source = new EventSource('/stream')
417
+ * source.addEventListener('message', debounced)
418
+ *
419
+ * // Cancel the trailing debounced invocation.
420
+ * window.addEventListener('popstate', debounced.cancel)
421
+ *
422
+ * // Check for pending invocations.
423
+ * const status = debounced.pending() ? "Pending..." : "Ready"
424
+ */
425
+ function useDebouncedCallback(func, wait, options) {
426
+ var _this = this;
427
+ var lastCallTime = useRef(null);
428
+ var lastInvokeTime = useRef(0);
429
+ var timerId = useRef(null);
430
+ var lastArgs = useRef([]);
431
+ var lastThis = useRef();
432
+ var result = useRef();
433
+ var funcRef = useRef(func);
434
+ var mounted = useRef(true);
435
+ funcRef.current = func;
436
+ // Bypass `requestAnimationFrame` by explicitly setting `wait=0`.
437
+ var useRAF = !wait && wait !== 0 && typeof window !== 'undefined';
438
+ if (typeof func !== 'function') {
439
+ throw new TypeError('Expected a function');
440
+ }
441
+ wait = +wait || 0;
442
+ options = options || {};
443
+ var leading = !!options.leading;
444
+ var trailing = 'trailing' in options ? !!options.trailing : true; // `true` by default
445
+ var maxing = 'maxWait' in options;
446
+ var maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : null;
447
+ useEffect(function () {
448
+ mounted.current = true;
449
+ return function () {
450
+ mounted.current = false;
451
+ };
452
+ }, []);
453
+ // You may have a question, why we have so many code under the useMemo definition.
454
+ //
455
+ // This was made as we want to escape from useCallback hell and
456
+ // not to initialize a number of functions each time useDebouncedCallback is called.
457
+ //
458
+ // It means that we have less garbage for our GC calls which improves performance.
459
+ // Also, it makes this library smaller.
460
+ //
461
+ // And the last reason, that the code without lots of useCallback with deps is easier to read.
462
+ // You have only one place for that.
463
+ var debounced = useMemo(function () {
464
+ var invokeFunc = function (time) {
465
+ var args = lastArgs.current;
466
+ var thisArg = lastThis.current;
467
+ lastArgs.current = lastThis.current = null;
468
+ lastInvokeTime.current = time;
469
+ return (result.current = funcRef.current.apply(thisArg, args));
470
+ };
471
+ var startTimer = function (pendingFunc, wait) {
472
+ if (useRAF)
473
+ cancelAnimationFrame(timerId.current);
474
+ timerId.current = useRAF ? requestAnimationFrame(pendingFunc) : setTimeout(pendingFunc, wait);
475
+ };
476
+ var shouldInvoke = function (time) {
477
+ if (!mounted.current)
478
+ return false;
479
+ var timeSinceLastCall = time - lastCallTime.current;
480
+ var timeSinceLastInvoke = time - lastInvokeTime.current;
481
+ // Either this is the first call, activity has stopped and we're at the
482
+ // trailing edge, the system time has gone backwards and we're treating
483
+ // it as the trailing edge, or we've hit the `maxWait` limit.
484
+ return (!lastCallTime.current ||
485
+ timeSinceLastCall >= wait ||
486
+ timeSinceLastCall < 0 ||
487
+ (maxing && timeSinceLastInvoke >= maxWait));
488
+ };
489
+ var trailingEdge = function (time) {
490
+ timerId.current = null;
491
+ // Only invoke if we have `lastArgs` which means `func` has been
492
+ // debounced at least once.
493
+ if (trailing && lastArgs.current) {
494
+ return invokeFunc(time);
495
+ }
496
+ lastArgs.current = lastThis.current = null;
497
+ return result.current;
498
+ };
499
+ var timerExpired = function () {
500
+ var time = Date.now();
501
+ if (shouldInvoke(time)) {
502
+ return trailingEdge(time);
503
+ }
504
+ // https://github.com/xnimorz/use-debounce/issues/97
505
+ if (!mounted.current) {
506
+ return;
507
+ }
508
+ // Remaining wait calculation
509
+ var timeSinceLastCall = time - lastCallTime.current;
510
+ var timeSinceLastInvoke = time - lastInvokeTime.current;
511
+ var timeWaiting = wait - timeSinceLastCall;
512
+ var remainingWait = maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
513
+ // Restart the timer
514
+ startTimer(timerExpired, remainingWait);
515
+ };
516
+ var func = function () {
517
+ var args = [];
518
+ for (var _i = 0; _i < arguments.length; _i++) {
519
+ args[_i] = arguments[_i];
520
+ }
521
+ var time = Date.now();
522
+ var isInvoking = shouldInvoke(time);
523
+ lastArgs.current = args;
524
+ lastThis.current = _this;
525
+ lastCallTime.current = time;
526
+ if (isInvoking) {
527
+ if (!timerId.current && mounted.current) {
528
+ // Reset any `maxWait` timer.
529
+ lastInvokeTime.current = lastCallTime.current;
530
+ // Start the timer for the trailing edge.
531
+ startTimer(timerExpired, wait);
532
+ // Invoke the leading edge.
533
+ return leading ? invokeFunc(lastCallTime.current) : result.current;
534
+ }
535
+ if (maxing) {
536
+ // Handle invocations in a tight loop.
537
+ startTimer(timerExpired, wait);
538
+ return invokeFunc(lastCallTime.current);
539
+ }
540
+ }
541
+ if (!timerId.current) {
542
+ startTimer(timerExpired, wait);
543
+ }
544
+ return result.current;
545
+ };
546
+ func.cancel = function () {
547
+ if (timerId.current) {
548
+ useRAF ? cancelAnimationFrame(timerId.current) : clearTimeout(timerId.current);
549
+ }
550
+ lastInvokeTime.current = 0;
551
+ lastArgs.current = lastCallTime.current = lastThis.current = timerId.current = null;
552
+ };
553
+ func.isPending = function () {
554
+ return !!timerId.current;
555
+ };
556
+ func.flush = function () {
557
+ return !timerId.current ? result.current : trailingEdge(Date.now());
558
+ };
559
+ return func;
560
+ }, [leading, maxing, wait, maxWait, trailing, useRAF]);
561
+ return debounced;
562
+ }
563
+
564
+ function valueEquality(left, right) {
565
+ return left === right;
566
+ }
567
+ function adjustFunctionValueOfSetState(value) {
568
+ return typeof value === 'function' ? function () { return value; } : value;
569
+ }
570
+ function useStateIgnoreCallback(initialState) {
571
+ var _a = useState(adjustFunctionValueOfSetState(initialState)), state = _a[0], setState = _a[1];
572
+ var setStateIgnoreCallback = useCallback(function (value) { return setState(adjustFunctionValueOfSetState(value)); }, []);
573
+ return [state, setStateIgnoreCallback];
574
+ }
575
+ function useDebounce(value, delay, options) {
576
+ var eq = (options && options.equalityFn) || valueEquality;
577
+ var _a = useStateIgnoreCallback(value), state = _a[0], dispatch = _a[1];
578
+ var debounced = useDebouncedCallback(useCallback(function (value) { return dispatch(value); }, [dispatch]), delay, options);
579
+ var previousValue = useRef(value);
580
+ useEffect(function () {
581
+ // We need to use this condition otherwise we will run debounce timer for the first render (including maxWait option)
582
+ if (!eq(previousValue.current, value)) {
583
+ debounced(value);
584
+ previousValue.current = value;
585
+ }
586
+ }, [value, debounced, eq]);
587
+ return [state, { cancel: debounced.cancel, isPending: debounced.isPending, flush: debounced.flush }];
588
+ }
589
+
366
590
  function useGetNodes({ search, workspaceId, branchSlug, projectIds, pause, }) {
367
591
  const { platformUrl, platformAuthToken } = React.useContext(PlatformContext);
368
592
  const [debounceSearch] = useDebounce(search, 500);
369
- return useQuery(['workspaceNodes', workspaceId, branchSlug, projectIds, debounceSearch, platformUrl, platformAuthToken], () => getNodes({ workspaceId, branchSlug, projectIds, search: debounceSearch, platformUrl, platformAuthToken }), { enabled: !pause });
593
+ return useQuery(['workspaceNodes', platformUrl, platformAuthToken, workspaceId, branchSlug, projectIds, debounceSearch], () => getNodes({ workspaceId, branchSlug, projectIds, search: debounceSearch, platformUrl, platformAuthToken }), { enabled: !pause, keepPreviousData: true });
370
594
  }
371
595
 
372
596
  function useGetWorkspace({ projectIds }) {