Code Monkey home page Code Monkey logo

util's Introduction

rc-util

Common Utils For React Component.

NPM version npm download build status Codecov bundle size dumi

Install

rc-util

API

createChainedFunction

(...functions): Function

Create a function which will call all the functions with it's arguments from left to right.

import createChainedFunction from 'rc-util/lib/createChainedFunction';

deprecated

(prop: string, instead: string, component: string): void

Log an error message to warn developers that prop is deprecated.

import deprecated from 'rc-util/lib/deprecated';

getContainerRenderMixin

(config: Object): Object

To generate a mixin which will render specific component into specific container automatically.

import getContainerRenderMixin from 'rc-util/lib/getContainerRenderMixin';

Fields in config and their meanings.

Field Type Description Default
autoMount boolean Whether to render component into container automatically true
autoDestroy boolean Whether to remove container automatically while the component is unmounted true
isVisible (instance): boolean A function to get current visibility of the component -
isForceRender (instance): boolean A function to determine whether to render popup even it's not visible -
getComponent (instance, extra): ReactNode A function to get the component which will be rendered into container -
getContainer (instance): HTMLElement A function to get the container

Portal

Render children to the specific container;

import Portal from 'rc-util/lib/Portal';

Props:

Prop Type Description Default
children ReactChildren Content render to the container -
getContainer (): HTMLElement A function to get the container -

getScrollBarSize

(fresh?: boolean): number

Get the width of scrollbar.

import getScrollBarSize from 'rc-util/lib/getScrollBarSize';

guid

(): string

To generate a global unique id across current application.

import guid from 'rc-util/lib/guid';

pickAttrs

(props: Object): Object

Pick valid HTML attributes and events from props.

import pickAttrs from 'rc-util/lib/pickAttrs';

warn

(msg: string): void

A shallow wrapper of console.warn.

import warn from 'rc-util/lib/warn';

warning

(valid: boolean, msg: string): void

A shallow wrapper of warning, but only warning once for the same message.

import warning, { noteOnce } from 'rc-util/lib/warning';

warning(false, '[antd Component] test hello world');

// Low level note
noteOnce(false, '[antd Component] test hello world');

Children

A collection of functions to operate React elements' children.

Children/mapSelf

(children): children

Return a shallow copy of children.

import mapSelf from 'rc-util/lib/Children/mapSelf';

Children/toArray

(children: ReactNode[]): ReactNode[]

Convert children into an array.

import toArray from 'rc-util/lib/Children/toArray';

Dom

A collection of functions to operate DOM elements.

Dom/addEventlistener

(target: ReactNode, eventType: string, listener: Function): { remove: Function }

A shallow wrapper of add-dom-event-listener.

import addEventlistener from 'rc-util/lib/Dom/addEventlistener';

Dom/canUseDom

(): boolean

Check if DOM is available.

import canUseDom from 'rc-util/lib/Dom/canUseDom';

Dom/class

A collection of functions to operate DOM nodes' class name.

  • hasClass(node: HTMLElement, className: string): boolean
  • addClass(node: HTMLElement, className: string): void
  • removeClass(node: HTMLElement, className: string): void
import cssClass from 'rc-util/lib/Dom/class;

Dom/contains

(root: HTMLElement, node: HTMLElement): boolean

Check if node is equal to root or in the subtree of root.

import contains from 'rc-util/lib/Dom/contains';

Dom/css

A collection of functions to get or set css styles.

  • get(node: HTMLElement, name?: string): any
  • set(node: HTMLElement, name?: string, value: any) | set(node, object)
  • getOuterWidth(el: HTMLElement): number
  • getOuterHeight(el: HTMLElement): number
  • getDocSize(): { width: number, height: number }
  • getClientSize(): { width: number, height: number }
  • getScroll(): { scrollLeft: number, scrollTop: number }
  • getOffset(node: HTMLElement): { left: number, top: number }
import css from 'rc-util/lib/Dom/css';

Dom/focus

A collection of functions to operate focus status of DOM node.

  • saveLastFocusNode(): void
  • clearLastFocusNode(): void
  • backLastFocusNode(): void
  • getFocusNodeList(node: HTMLElement): HTMLElement[] get a list of focusable nodes from the subtree of node.
  • limitTabRange(node: HTMLElement, e: Event): void
import focus from 'rc-util/lib/Dom/focus';

Dom/support

{ animation: boolean | Object, transition: boolean | Object }

A flag to tell whether current environment supports animationend or transitionend.

import support from 'rc-util/lib/Dom/support';

KeyCode

Enum

Enum of KeyCode, please check the definition of it.

import KeyCode from 'rc-util/lib/KeyCode';

KeyCode.isTextModifyingKeyEvent

(e: Event): boolean

Whether text and modified key is entered at the same time.

KeyCode.isCharacterKey

(keyCode: KeyCode): boolean

Whether character is entered.

ScrollLocker

ScrollLocker<{lock: (options: {container: HTMLElement}) => void, unLock: () => void}>

improve shake when page scroll bar hidden.

ScrollLocker change body style, and add a class ant-scrolling-effect when called, so if you page look abnormal, please check this;

import ScrollLocker from 'rc-util/lib/Dom/scrollLocker';

const scrollLocker = new ScrollLocker();

// lock
scrollLocker.lock()

// unLock
scrollLocker.unLock()

License

MIT

util's People

Contributors

3imed-jaberi avatar afc163 avatar benjycui avatar chenshuai2144 avatar crazyair avatar dependabot-preview[bot] avatar dependabot[bot] avatar ihmpavel avatar jljsj33 avatar junlinzhu-tommy avatar kuitos avatar lgtm-com[bot] avatar li-jia-nan avatar madccc avatar mdedetrich avatar miracles1919 avatar paranoidjk avatar pengqingyao avatar petetnt avatar pingan1927 avatar rzyanhao avatar shaodahong avatar strml avatar tmkx avatar vagusx avatar wxh16144 avatar yesmeck avatar yiminghe avatar yoyo837 avatar zombiej avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

util's Issues

4.9.0 版本引发报错,获取不到 addEventListener

我的项目依赖一个三方包,这个包依赖了 rc-util,里面是这样用的:

const addEventListener = require('rc-util/lib/Dom/addEventListener');
...
addEventListener(window, 'resize', this.resize);

rc-util 4.9.0 版本做了什么?4.88 还能正常运行,4.9.0 版本就报错 Uncaught (in promise) TypeError: addEventListener is not a function

我没法改这个三方包,还请看看 rc-util 4.9.0 是否改出问题了。

package.json 缺失 peerDependencies 字段

Skypack 是一个分发 ESM 模块的 CDN,我正在通过 Skypack 使用 react 和 antd 开发应用程序,但在加载 antd 模块的过程中出现了错误。

由于 rc-util 的代码中依赖了 react-dom 而没有在 package.json 中通过 peerDependencies 字段声明,Skypack 无法判断出此时如何加载 react-dom.

希望维护者可以补全 peerDependencies 字段,修复这个问题。

#138

useMergedState.ts

In triggerChange function, why not ignore setInnerValue when value present, i.e. controlled mode. I suppose innerValue does not take any effect in controlled mode though.

In addition, it should be nice to add some logic detecting the switch controlled and uncontrolled mode, throw an error/warning as native react dose facebook/react#5821.

Not sure if I am missing some points though, if the above idea make any sense. I am glad to implement the code

Warning: React does not recognize the `scrollLocker`

Warning: React does not recognize the scrollLocker prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase scrolllocker instead. If you accidentally passed it from a parent component, remove it from the DOM element.

at PortalWrapper

Cannot read property 'appendChild' of null

After install antd → [email protected] › rc-util@^4.0.4(4.8.6) (14:48:20)

Dropdown in Table throw this error:

index.js?b235:700 Uncaught TypeError: Cannot read property 'appendChild' of null
    at Object.getContainer

The above error occurred in the <Portal> component:
    in Portal (created by Trigger)
    in Trigger (created by Dropdown)
    in Dropdown (created by Context.Consumer)

Missing peer dependency with npm3 install

rc-util v3.2.0

1a719d1

image

react-addons-pure-render-mixin peer-depends react@^15.1.0.

When I install rc-menu, a UNMET PEER DEPENDENCY error occured.

image

So, would you please remove react-addons-pure-render-mixin or add react into dependencies?

getScrollBarSize.tsx 中的方法getTargetScrollBarSize在Firefox 52.9及其以前版本中报错“NS_ERROR_NOT_AVAILABLE”

2021.5.20的更新中加入的片段

环境:
windows xp 32位
firefox 52.9 esr 32位

Ref:

const { width, height } = getComputedStyle(target, '::-webkit-scrollbar');

function ensureSize(str: string) {
  const match = str.match(/^(.*)px$/);
  const value = Number(match?.[1]);
  return Number.isNaN(value) ? getScrollBarSize() : value;
}

export function getTargetScrollBarSize(target: HTMLElement) {
  if (typeof document === 'undefined' || !target) {
    return { width: 0, height: 0 };
  }

  const { width, height } = getComputedStyle(target, '::-webkit-scrollbar');  // 此行在Firefox中提示错误
  return {
    width: ensureSize(width),
    height: ensureSize(height),
  };
}

在firefox52.9(32位)及其以前版本(测试了51\47\46)会提示**"NS_ERROR_NOT_AVAILABLE"**的错误。
我想应该是getComputedStyle返回的CSSStyleDeclaration对象(浏览器中显示CSS2Properties)不可访问导致的。
如何修正这个问题?

>=v5.13.0下在低版本火狐浏览器下getTargetScrollBarSize方法报错

火狐23~40版本(已经测试过)下报错

[10:23:37.280] [Exception... "Out of Memory"  nsresult: "0x8007000e (NS_ERROR_OUT_OF_MEMORY)"  location: "JS frame :: debugger eval code :: WCA_evalWithDebugger :: line 1"  data: no]

使用 const { width, height } = getComputedStyle(target, '::-webkit-scrollbar'); 获取宽高时报错

Portal warning when dev

Repro Steps

git clone [email protected]:ant-design/ant-design-mobile.git
cd antd-mobile
npm install
npm start
~/github/ant-design-mobile(master*) » tnpm start                                                                                                                                                                                                 jiangkai@jiangkaideMacBook-Pro

> [email protected] start /Users/jiangkai/github/ant-design-mobile
> cross-env NODE_ENV=development concurrently "cross-env DEMO_ENV=react bisheng start -c ./site/bisheng.desktop.config.js" "cross-env DEMO_ENV=preact bisheng start -c ./site/bisheng.kitchen.config.js"

[1] ts-loader: Using [email protected] and /Users/jiangkai/github/ant-design-mobile/tsconfig.json
[0]
[0] webpack: bundle build is now finished.
[0]  DONE  Compiled successfully in 9142ms10:24:37
[0]
[0]  WAIT  Compiling...10:24:37
[0]
[1]
</github/ant-design-mobile/    |''pick 5970c12d7 docs:  fix site
</github/ant-design-mobile/    |''# This is a combination of 2 commits.
[1] webpack: bundle build is now finished.
[1]  WARNING  Compiled with 2 warnings10:24:38
[1]
[1]  warning  in ./node_modules/rc-util/es/Portal.js
[1]
[1] 54:15-27 "export 'createPortal' was not found in 'react-dom'
[1]
[1]  warning  in ./node_modules/bisheng-plugin-antd/node_modules/rc-dialog/es/DialogWrap.js
[1]
[1] 8:20-32 "export 'createPortal' was not found in 'react-dom'
[1]
[1]  WAIT  Compiling...10:24:38
[1]
[0]
[0] webpack: bundle build is now finished.
[0]  DONE  Compiled successfully in -10153ms10:24:38
[0]
[1]
[1] webpack: bundle build is now finished.
[1]  WARNING  Compiled with 2 warnings10:24:39
[1]
[1]  warning  in ./node_modules/rc-util/es/Portal.js
[1]
[1] 54:15-27 "export 'createPortal' was not found in 'react-dom'
[1]
[1]  warning  in ./node_modules/bisheng-plugin-antd/node_modules/rc-dialog/es/DialogWrap.js
[1]
[1] 8:20-32 "export 'createPortal' was not found in 'react-dom'
[1]
^C

switchScrollingEffect.js 中的isBodyOverflowing方法,在下面一种场景中有点欠缺:

switchScrollingEffect.js 中的isBodyOverflowing方法,在下面一种场景中有点欠缺:

  在全局的body的样式上增加了overflow-y:scroll,至于为什么要加,原因是想解决左侧菜单栏切换,右侧对应的内容有无溢出不会出现页面抖动的问题。
  例如:https://preview.pro.ant.design/dashboard/analysis
  从分析页面到异常页403,右侧内容就会因为滚动条的原因抖动。

  如果把这个样式设置到html 上,虽然没上述问题,但是在结合弹框Modal 使用时,就会出现弹框的遮罩层遮不住滚动条,也有点不合适。

  在上面这种场景下,isBodyOverflowing期望是被返回true 的。

Originally posted by @yangdongMC in #65 (comment)

Share experience: When rc-util 5.3.0 release,I compile failed

Problem Description

When your project contains both antd4 and old rc-component,there is compile error.
image

Keyword

Module not found: Error: Can't resolve 'rc-util/es/Dom/isVisible

Why Error

rc-util 5 and rc-util 4 are both used by antd4 and old rc-component

Solution

add "rc-util": "^5.3.1" to package.json

TypeError: Cannot read property 'getParent' of undefined

Hi
I got this error in when i click the Modal popup event .
I thick this problem come from the latest package of 'rc-util'.
if (!windowIsUndefined && this.getParent() === document.body) { // 离开时不会 render, 导到离开时数值不变,改用 func 。。 openCount = visible && openCount ? openCount - 1 : openCount; }
path: node_modules/rc-util/es/PortalWrapper.js

how you fixed this?
i got the same issue on Liver server and local.
any idea to fix this problem.

Environment

"antd": "^4.1.2",
"react": "^16.13.1",
System - Ubuntu 18.04.3 LTS
Browser - Version 79.0.3945.130 (Official Build) (64-bit)

Portal is not working properly in StrictMode

StrictMode will detect unexpected side effects, getContainer is in the function component body directly, and side effects happened.

containerRef points to the second DOM instance, and the first instance becomes wild, can't be removed longer.

image

As a simple example (just imagine that id is the DOM):

const Test = () => {
  const id = Math.random().toString(36).slice(2);
  console.log('render', id);

  useEffect(() => {
    console.log('mount', id);
    return () => console.log('unmount', id);
  }, []);

  return null;
};

outputs:

render mwn44o9shbe
render d2qan84ldw9
mount d2qan84ldw9
unmount d2qan84ldw9
mount d2qan84ldw9

this example shows that the "unmount DOM" is the second one (NOT the first), if you trigger Portal creation repeatedly, there will be a lot of unused DOM in the document body, which leads to memory leak.

hi~

I have a question...
What is es?

Missing type declaration for PortalWrapper

rc-util version 5.0.4 (dependency of antd version 4.11.2)

Problem

Missing type declaration triggering TypeScript error on build:

ERROR in [path to app]/node_modules/rc-image/lib/Image.d.ts(2,30):
TS7016: Could not find a declaration file for module 'rc-util/lib/PortalWrapper'. '[path to app]/node_modules/rc-image/node_modules/rc-util/lib/PortalWrapper.js' implicitly has an 'any' type.
  Try `npm install @types/rc-util` if it exists or add a new declaration (.d.ts) file containing `declare module 'rc-util/lib/PortalWrapper';`

Solution

Add PortalWrapper.d.ts.

[utils] Please make component "warnings" actually warnings

Component warnings are currently printed as errors:

util/src/warning.ts

Lines 4 to 9 in db8b843

export function warning(valid: boolean, message: string) {
// Support uglify
if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {
console.error(`Warning: ${message}`);
}
}

In development, they show up in the console like this:

Screen Shot 2022-09-20 at 10 26 35 AM

The stack traces are unnecessary. They flood our consoles and make deprecation messages themselves hard to spot.

And deprecation warnings are not errors, and they should not be displayed as such. Showing them as errors distracts developers from actually critical errors, causes unnecessary panics, makes Ant Design unpleasant to work with, and developers are more likely to ignore future deprecation notices (a cry-wolf effect).

Please use console.warn for your deprecation warnings.

Screen Shot 2022-09-20 at 10 38 32 AM

项目中使用 rc-util/es/warning 后,打包后的生产代码为什么会包含警告代码?

问题如题所述

复现案例

https://stackblitz.com/edit/vitejs-vite-zdg5hc?file=src%2FApp.tsx
请看案例中 dist/assets/index.57005310.js 文件中 7356-7467 代码行

期待行为:

正常来说生产代码不应该包含警告(console.log/console.warn/console.error)等不影响项目执行的代码

造成问题的原因:

// 源码实现如下(只是列出部分代码)
export function warning(valid, message) {
  if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {
    console.error(message)
  }
}

// 相比以上实现,下列实现则会在打包生产代码时移除相关代码
function noop() {}
export let warning = noop

if (process.env.NODE_ENV !== 'production') {
  warning = function () {
    if (!valid && console !== undefined) {
      console.error(message)
    }
  }
} 

另外,console !== undefined 可以移除,客户端和服务端不是都有 console 对象么?

rc-util warning

WARNING Compiled with 1 warnings 10:12:06

warning in ./node_modules/rc-util/es/React/render.js

export 'createRoot' (imported as 'ReactDOM') was not found in 'react-dom' (possible exports: __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, createPortal, findDOMNode, flushSync, hydrate, render, unmountComponentAtNode, unstable_batchedUpdates, unstable_createPortal, unstable_renderSubtreeIntoContainer, version)

Could not install version 5.15.0

Hello!

I cannot install version 5.15.0.
during installation i get v.5.14.0 as the latest:
npm install rc-util@latest
+ [email protected]
updated 1 package in 22.434s

When i try to install v5.15.0, i get error:
npm install [email protected]
npm ERR! code ETARGET
npm ERR! notarget No matching version found for [email protected].
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist

Uncaught TypeError: dispatcher.useId is not a function

react>=18 时:

react.development.js:1667 Uncaught TypeError: dispatcher.useId is not a function
at useId (react.development.js:1667:1)
at useId (useId.js:28:1)
at Dialog (index.js:50:21)
at renderWithHooks (react-dom.development.js:14803:1)

image

image

Cannot find module 'rc-util/lib/isMobile' from 'StepHandler.js'

after update to antd to 4.13.0, it looks like rc-util has been updated from "^5.7.0" to "^5.8.1" and now i'm getting this error

Cannot find module 'rc-util/lib/isMobile' from 'StepHandler.js'
      at Resolver.resolveModule (node_modules/jest-runtime/node_modules/jest-resolve/build/index.js:259:17)
      at Object.<anonymous> (node_modules/rc-input-number/lib/StepHandler.js:20:40)

please advice.

Build issues when using rollup commonjs plugin

The CommonJS plugin for Rollup doesn't seem to like destructured imports like:

import { isFragment } from 'react-is';

Using a named import or default import fixes this issue:

import * as ReactIs from 'react-is'; // or
import ReactIs from 'react-is';

When using tools like pika, we don't have direct control over the commonjs plugin so we can't configure named exports on react-is.

See relevant issues:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.