react-is#isElement JavaScript Examples

The following examples show how to use react-is#isElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: styled-components.browser.esm.js    From VTour with MIT License 5 votes vote down vote up
function flatten(chunk, executionContext, styleSheet) {
  if (Array.isArray(chunk)) {
    var ruleSet = [];

    for (var i = 0, len = chunk.length, result; i < len; i += 1) {
      result = flatten(chunk[i], executionContext, styleSheet);
      if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
    }

    return ruleSet;
  }

  if (isFalsish(chunk)) {
    return '';
  }
  /* Handle other components */


  if (isStyledComponent(chunk)) {
    return "." + chunk.styledComponentId;
  }
  /* Either execute or defer the function */


  if (isFunction(chunk)) {
    if (isStatelessFunction(chunk) && executionContext) {
      var _result = chunk(executionContext);

      if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
        // eslint-disable-next-line no-console
        console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.");
      }

      return flatten(_result, executionContext, styleSheet);
    } else return chunk;
  }

  if (chunk instanceof Keyframes) {
    if (styleSheet) {
      chunk.inject(styleSheet);
      return chunk.getName();
    } else return chunk;
  }
  /* Handle objects */


  return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
}
Example #2
Source File: styled-components.esm.js    From VTour with MIT License 5 votes vote down vote up
function flatten(chunk, executionContext, styleSheet) {
  if (Array.isArray(chunk)) {
    var ruleSet = [];

    for (var i = 0, len = chunk.length, result; i < len; i += 1) {
      result = flatten(chunk[i], executionContext, styleSheet);
      if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
    }

    return ruleSet;
  }

  if (isFalsish(chunk)) {
    return '';
  }
  /* Handle other components */


  if (isStyledComponent(chunk)) {
    return "." + chunk.styledComponentId;
  }
  /* Either execute or defer the function */


  if (isFunction(chunk)) {
    if (isStatelessFunction(chunk) && executionContext) {
      var _result = chunk(executionContext);

      if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
        // eslint-disable-next-line no-console
        console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.");
      }

      return flatten(_result, executionContext, styleSheet);
    } else return chunk;
  }

  if (chunk instanceof Keyframes) {
    if (styleSheet) {
      chunk.inject(styleSheet);
      return chunk.getName();
    } else return chunk;
  }
  /* Handle objects */


  return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
}
Example #3
Source File: hydration.js    From ReactSourceCodeAnalyze with MIT License 5 votes vote down vote up
/**
 * Get a enhanced/artificial type string based on the object instance
 */
function getDataType(data: Object): PropType {
  if (data === null) {
    return 'null';
  } else if (data === undefined) {
    return 'undefined';
  }

  if (isElement(data)) {
    return 'react_element';
  }

  if (typeof HTMLElement !== 'undefined' && data instanceof HTMLElement) {
    return 'html_element';
  }

  const type = typeof data;
  switch (type) {
    case 'boolean':
      return 'boolean';
    case 'function':
      return 'function';
    case 'number':
      if (Number.isNaN(data)) {
        return 'nan';
      } else if (!Number.isFinite(data)) {
        return 'infinity';
      } else {
        return 'number';
      }
    case 'object':
      if (Array.isArray(data)) {
        return 'array';
      } else if (ArrayBuffer.isView(data)) {
        return data instanceof DataView ? 'data_view' : 'typed_array';
      } else if (data instanceof ArrayBuffer) {
        return 'array_buffer';
      } else if (typeof data[Symbol.iterator] === 'function') {
        return 'iterator';
      } else if (Object.prototype.toString.call(data) === '[object Date]') {
        return 'date';
      }
      return 'object';
    case 'string':
      return 'string';
    case 'symbol':
      return 'symbol';
    default:
      return 'unknown';
  }
}
Example #4
Source File: styled-components.browser.esm.js    From the-eye-knows-the-garbage with MIT License 5 votes vote down vote up
function flatten(chunk, executionContext, styleSheet) {
  if (Array.isArray(chunk)) {
    var ruleSet = [];

    for (var i = 0, len = chunk.length, result; i < len; i += 1) {
      result = flatten(chunk[i], executionContext, styleSheet);

      if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
    }

    return ruleSet;
  }

  if (isFalsish(chunk)) {
    return null;
  }

  /* Handle other components */
  if (isStyledComponent(chunk)) {
    return '.' + chunk.styledComponentId;
  }

  /* Either execute or defer the function */
  if (isFunction(chunk)) {
    if (isStatelessFunction(chunk) && executionContext) {
      var _result = chunk(executionContext);

      if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
        // eslint-disable-next-line no-console
        console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.');
      }

      return flatten(_result, executionContext, styleSheet);
    } else return chunk;
  }

  if (chunk instanceof Keyframes) {
    if (styleSheet) {
      chunk.inject(styleSheet);
      return chunk.getName();
    } else return chunk;
  }

  /* Handle objects */
  return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
}
Example #5
Source File: styled-components.esm.js    From the-eye-knows-the-garbage with MIT License 5 votes vote down vote up
function flatten(chunk, executionContext, styleSheet) {
  if (Array.isArray(chunk)) {
    var ruleSet = [];

    for (var i = 0, len = chunk.length, result; i < len; i += 1) {
      result = flatten(chunk[i], executionContext, styleSheet);

      if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
    }

    return ruleSet;
  }

  if (isFalsish(chunk)) {
    return null;
  }

  /* Handle other components */
  if (isStyledComponent(chunk)) {
    return '.' + chunk.styledComponentId;
  }

  /* Either execute or defer the function */
  if (isFunction(chunk)) {
    if (isStatelessFunction(chunk) && executionContext) {
      var _result = chunk(executionContext);

      if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
        // eslint-disable-next-line no-console
        console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.');
      }

      return flatten(_result, executionContext, styleSheet);
    } else return chunk;
  }

  if (chunk instanceof Keyframes) {
    if (styleSheet) {
      chunk.inject(styleSheet);
      return chunk.getName();
    } else return chunk;
  }

  /* Handle objects */
  return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
}
Example #6
Source File: ToastProvider.js    From tonic-ui with MIT License 4 votes vote down vote up
ToastProvider = ({
  children,
  placement: _placement = defaultPlacement,
  container,
}) => {
  const isHydrated = useHydrated();
  const [state, setState] = useState(() => (
    placements.reduce((acc, placement) => {
      acc[placement] = [];
      return acc;
    }, {})
  ));

  /**
   * Create properties for a new toast
   */
  const createToast = (message, options) => {
    const id = options?.id ?? uniqueId();
    const placement = ensureString(options?.placement ?? _placement);
    const duration = options?.duration;
    const onClose = () => close(id, placement);

    return {
      // A unique identifier that represents the toast message
      id,

      // The toast message to render
      message,

      // The placement of the toast
      placement,

      // The duration (in milliseconds) that the toast should remain on the screen. If set to null, toast will never dismiss.
      duration,

      // The function to close the toast
      onClose,
    };
  };

  /**
   * Close a toast record at its placement
   */
  const close = (id, placement) => {
    placement = placement ?? getToastPlacementByState(state, id);

    setState((prevState) => ({
      ...prevState,
      [placement]: ensureArray(prevState[placement]).filter((toast) => toast.id !== id),
    }));
  };

  /**
   * Close all toasts at once with the given placements, including the following:
   * • top
   * • top-left
   * • top-right
   * • bottom
   * • bottom-left
   * • bottom-right
   */
  const closeAll = (options) => {
    const placements = options?.placements
      ? ensureArray(options?.placements)
      : Object.keys(state);

    setState((prevState) => {
      const nextState = placements.reduce((acc, placement) => {
        acc[placement] = [];
        return acc;
      }, {});

      return {
        ...prevState,
        ...nextState,
      };
    });
  };

  /**
   * Find the first toast in the array that matches the provided id. Otherwise, `undefined` is returned if not found.
   * If no values satisfy the testing function, undefined is returned.
   */
  const find = (id) => {
    const placement = getToastPlacementByState(state, id);
    return ensureArray(state[placement]).find((toast) => toast.id === id);
  };

  /**
   * Find the first toast in the array that matches the provided id. Otherwise, -1 is returned if not found.
   */
  const findIndex = (id) => {
    const placement = getToastPlacementByState(state, id);
    return ensureArray(state[placement]).findIndex((toast) => toast.id === id);
  };

  /**
   * Create a toast at the specified placement and return the id
   */
  const notify = (message, options) => {
    const toast = createToast(message, options);
    const { placement, id } = toast;

    setState((prevState) => {
      const isTop = placement.includes('top');

      /**
       * For the toast is placemented at the top edges:
       *   toast #3 ← the most recent
       *   toast #2
       *   toast #1
       *
       * For the toast is placemented at the bottom edges:
       *   toast #1
       *   toast #2
       *   toast #3 ← the most recent
       */
      const prevToasts = ensureArray(prevState[placement]);
      const toasts = isTop
        ? [toast, ...prevToasts]
        : [...prevToasts, toast];

      return {
        ...prevState,
        [placement]: toasts,
      };
    });

    return id;
  };

  /**
   * Update a specific toast with new options based on the given id. Returns `true` if the toast exists, else `false`.
   */
  const update = (id, options) => {
    const placement = find(id)?.placement;
    const index = findIndex(id);

    if (!placement || index === -1) {
      return false;
    }

    setState((prevState) => {
      const nextState = { ...prevState };
      nextState[placement][index] = {
        ...nextState[placement][index],
        ...options,
      };
      return nextState;
    });

    return true;
  };

  const context = getMemoizedState({
    // Methods
    close,
    closeAll,
    find,
    findIndex,
    notify,
    update,

    // Properties
    placement: _placement,

    // State
    state,
  });

  const portalTarget = canUseDOM()
    ? (container ?? document.body)
    : null;

  if (!portalTarget) {
    return (
      <ToastContext.Provider value={context}>
        {runIfFn(children, context)}
      </ToastContext.Provider>
    );
  }

  return (
    <ToastContext.Provider value={context}>
      {runIfFn(children, context)}
      {isHydrated && createPortal((
        Object.keys(state).map((placement) => {
          const toasts = ensureArray(state[placement]);
          return (
            <ToastContainer
              key={placement}
              hasToasts={toasts.length > 0}
              placement={placement}
            >
              <TransitionGroup component={null}>
                {toasts.map((toast) => (
                  <ToastTransition
                    key={toast.id}
                    in={true}
                    collapsedHeight={0}
                    unmountOnExit
                  >
                    <ToastController
                      duration={toast.duration}
                      onClose={toast.onClose}
                    >
                      {(() => {
                        if (isElement(toast.message)) {
                          return toast.message;
                        }
                        if (isValidElementType(toast.message)) {
                          return (
                            <toast.message
                              id={toast.id}
                              onClose={toast.onClose}
                              placement={toast.placement}
                            />
                          );
                        }
                        return null;
                      })()}
                    </ToastController>
                  </ToastTransition>
                ))}
              </TransitionGroup>
            </ToastContainer>
          );
        })
      ), portalTarget)}
    </ToastContext.Provider>
  );
}