# dt2react

> one dom helper lib for react

Latest version **2.3.1** (published 2024-05-10) · MIT license · 0 weekly downloads

## Install

```sh
npm install dt2react
pnpm add dt2react
yarn add dt2react
bun add dt2react
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.3.1 |
| Published | 2024-05-10 |
| First published | 2016-12-30 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 230.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | ilex.h |
| Maintainers | ilex.h |
| Keywords | dom, react tool |

## Links

- npm: https://www.npmjs.com/package/dt2react
- Repository: https://github.com/ilex0208/dt2react
- Homepage: https://github.com/ilex0208/dt2react#readme
- Issues: https://github.com/ilex0208/dt2react/issues
- npm.io page: https://npm.io/package/dt2react

## Dependencies (1)

- [immutability-helper](https://npm.io/package/immutability-helper.md) ^2.6.4

## Alternatives

- [babylon](https://npm.io/package/babylon.md) — 5.1M weekly downloads
- [csscolorparser](https://npm.io/package/csscolorparser.md) — 3.7M weekly downloads
- [expr-eval-fork](https://npm.io/package/expr-eval-fork.md) — 1.5M weekly downloads
- [@leeoniya/ufuzzy](https://npm.io/package/@leeoniya/ufuzzy.md) — 247.7K weekly downloads
- [xml-parser](https://npm.io/package/xml-parser.md) — 78.4K weekly downloads

## Recent versions

- 2.3.1 (latest) — 2024-05-10
- 2.3.0 — 2024-03-05
- 2.2.5 — 2024-01-23
- 2.2.4 — 2024-01-23
- 2.2.3 — 2024-01-22
- 2.2.2 — 2024-01-02
- 2.2.1 — 2023-10-23
- 2.2.0 — 2023-04-12
- 2.1.3 — 2023-02-07
- 2.1.2 — 2022-12-13
- 2.1.1 — 2022-11-14
- 2.1.0 — 2022-11-03
- 2.0.10 — 2022-06-02
- 2.0.9 — 2021-12-01
- 2.0.8 — 2021-12-01
- … 44 more at https://npm.io/package/dt2react/versions

## README

# dt2react

## descr

ONE DOM helper library for react

## Install

```bash
npm install dt2react;
```

## Example

```js
const { addClass } = dt2react;
```

## Documnets

### align

### animation

* cancelAnimationFramePolyfill
* nativeRequestAnimationFrame
* requestAnimationFramePolyfill
* cssAnimation
* throttleAnamition { throttleAnamition, throttleAnamitionDecorator }

### class

* addClass
* classList
* classList2
* hasClass
* removeClass
* toggleClass

```js
hasClass(node, className)
addClass(node, className)
removeClass(node, className)
```

### events

```js
on()
off()
onFocus()
```

### position

```js
getOffsetPosition(domEle): { top: number, left: number};
getWindowSize(): { width: number, height: number};
```

### react

* [Align](#Align)
* [childrenToArray](#childrenToArray)
* [mapSelf](#mapSelf)
* [immutableUpdate](#immutableUpdate)
* [enhancePortal](#enhancePortal)
* [Portal](#Portal)
* [reactEvents](#reactEvents)
* [getDefaultContainer](#getDefaultContainer)
* [PureRenderDeepMixin](#PureRenderDeepMixin)
* [PureRenderMixin](#PureRenderMixin)
* [ResizeDetector](#ResizeDetector)
* [RemoteViewer](#RemoteViewer)
* [ScriptViewer](#ScriptViewer)

#### Align

#### childrenToArray

#### mapSelf

#### immutableUpdate

  Make setState easily and immutably. more info [immutability-helper](https://github.com/kolodny/immutability-helper).

    - No need to call setState manually

    - No need to build syntactic sugar like `{x: {y: {$set: 1}}}`, just pass `x.y` and `1`

* example

```js
import { immutableUpdate as update } from 'dt2react';

class Todos extends Component {

  constructor() {
    super()
    this.update = update.bind(this)
    this.state = {
      text: '',
      items: []
    }
  }

  render() {
    const { text, items } = this.state
    const update = this.update
    return (
      <div>
        <input type="text" value={text} onChange={e => update('set', 'text', e.target.value)} />
        <button onClick={() => update('push', 'items', { text })}>Add</button>
        <ul>
          {items.map((item, i) => {
            return (
              <li key={i}>
                {item.text}
                <button onClick={() => update('splice', 'items', i)}></button>
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
}
```

* api

  Bind component and execute setState automatically

```js
import { immutableUpdate as update } from 'dt2react';

class App extends Component {

  constructor() {
    super()
    this.update = update.bind(this)
    this.state = {
      name: 'John',
      relation: {
        family: 0,
        friend: 1
      },
      honor: ['1', '2', '3']
    }
  }

  someUsage() {
    this.update('set', 'name', 'Wall')
    this.update('set', 'relation.family', 1)
    this.update('set', ['relation', 'family'], 0)
    this.update('set', {
      name: 'Jamas',
      'relation.friend': 0
    })
    this.update('push', 'honor', '4') // ['1', '2', '3', '4']
    this.update('splice', 'honor', 0) // ['2', '3', '4']

    // All above actions just render once and all state has changed.
  }
}
```

* Silent usage

which would not execute setState automatically

```js
import { immutableUpdate as update } from 'dt2react';

const myData = { x: { y: 0 } }
const newData = update(myData, 'set', 'x.y', 1)
console.log(newData) // {x: {y: 1}}
```

#### enhancePortal

#### Portal

#### reactEvents

wrapper of `eventlistener`

```js
import addEventListener from 'dt2react/lib/events/eventlistener';

var handler = addEventListener(document.body, 'click', function(e){
  console.log(e.target); // works for ie
  console.log(e.nativeEvent); // native dom event
});
handler.remove(); // detach event listener
```

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

```js
import addEventlistener from 'dt2react/lib/react/reactEvents';
```

#### getDefaultContainer

> create default container

```js
const rootDiv = getDefaultContainer();

```

#### PureRenderMixin

```js
import PureRenderMixin from 'dt2react/lib/react/PureRenderMixin';

shouldComponentUpdate(nextProps, nextState) {
  return  PureRenderMixin.shouldComponentUpdate.call(this, nextProps, nextState);
}

// or

shouldComponentUpdate(...args) {
  return  PureRenderMixin.shouldComponentUpdate.apply(this, args);
}
```

#### PureRenderDeepMixin

> deep compare

```js
import PureRenderDeepMixin from 'dt2react/lib/react/PureRenderDeepMixin';

shouldComponentUpdate(nextProps, nextState) {
  return  PureRenderDeepMixin.shouldComponentUpdate.call(this, nextProps, nextState);
}

// or

shouldComponentUpdate(...args) {
  return  PureRenderDeepMixin.shouldComponentUpdate.apply(this, args);
}
```

#### ResizeDetector

```js
import withResize, { ResizeDetector } from 'dt2react/lib/react/withResize';

```

#### RemoteViewer

```js
import RemoteViewer, { getRemoteComponent, getRemoteModule } from 'dt2react/lib/react/RemoteViewer';

export const WebStudioExecutor = getRemoteComponent({
  scriptConfig: {
    key: 'amosasp',
    url: getMfUrl('amosasp_dist/remoteEntry.js')
  },
  scope: 'amosasp',
  module: './amos-webstudio',
  onDone: (d) => d.WebStudioExecutor
});
```

直接使用远程模块

```js
import { getRemoteModule } from 'dt2react/lib/react/RemoteViewer';

function getMfUrl(entry) {
  // 注意 __mf_prefix_url__ ，结尾不能写后缀 `/`
  // 如下方式，支持设置 `__mf_prefix_url__=''`
  if (window.__mf_prefix_url__ !== undefined || window.__mf_prefix_url__ !== null){
    return `${window.__mf_prefix_url__}/${entry}`;
  }
  return `/mf_lib/${entry}`;
}

export const mfRV = getRemoteModule({
  scriptConfig: {
    key: 'amosmf',
    url: getMfUrl('amosmf_dist/remoteEntry.js')
  },
  scope: 'amosmf',
  module: './handsontable',
  onDone: (d) => ({
    HotTable: d.HotTable,
    HotColumn: d.HotColumn
  }),
  debugConfig
});

// demo
class HTableDemo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      laoding: true,
      HotTable: null,
      HotColumn: null
    };

    this._asyncInit();
  }

  _asyncInit = () => {
    mfRV.loadMf(({ HotTable, HotColumn }) => {
      this.setState({
        laoding: false,
        HotTable,
        HotColumn
      });
    });
  }

  render() {
    const { laoding, HotTable, HotColumn } = this.state;
    if (laoding){
      return null;
    }
    return (
      <div className="demo-content">
        <HotTable rowHeaders height="50%" data={dataList} licenseKey="non-commercial-and-evaluation">
          <HotColumn title="时间" />
          <HotColumn title="值" />
          <HotColumn title="其它" />
        </HotTable>
        <h3>单独使用 HotTable </h3>
        <HotTable height="50%" data={dataList} licenseKey="non-commercial-and-evaluation" />
      </div>
    );
  }
}
```

#### ScriptViewer

```js
import ScriptViewer, { getScriptComponent } from 'dt2react/lib/react/ScriptViewer';
import { BaseMap } from 'amos-amap';

function MyMap(){
  return (
    <div style={{width: '100%', height: '400px'}}>
      <BaseMap zoom={5} center={{ longitude: 120, latitude: 30 }}/>
    </div>
  );
}

// 外部直接使用 MapViewer
const MapViewer = getScriptComponent({
  scriptConfig: [
    { key: 'amap', url: 'http://webapi.amap.com/maps?v=1.4.3&key=xxxxxxxx' }
  ],
  useBody: true,
  deferred: true,
  component: MyMap
});
```

### scroll

```js
calcScrollBarSize(fresh);// 获取当前浏览器滚动条宽度，推荐
getScrollbarWidth();
addPxToStyle(name, value);
domCss: { set, get };
getInnerHeight(el);
getInnerWidth(el);
getScroll(target, top);
prefixStyle(prop);
```


### style

```js
getStyle(node, property)
removeStyle(node, property)
addStyle(node, property, value)
```

### utils

* warning

* invariant

* shallowEqual

* arrayTreeFilter

* createChainFunc

* debounce

* deprecated

* devtoolsCheck
  `import { startCheck } from 'dt2react/lib/utils/devtoolsCheck'; startCheck({ redirect, afterOpen, delay })`。可用 `window.enableDevtoolCheck` 直接进行控制

* env `check is dev: set NODE_ENV=development or NODE_ENV=production`

* stringFormatter

* toCamelCase

* trim

* loadScripts

  直接用于react

  ```js
    componentDidMount() {
      const script = {
        key: 'amapscripts',
        url: 'http://webapi.amap.com/maps?v=1.4.3&key=xxx'
      };
      document.getElementById('app').style.display = 'none';
      tools.asyncLoadScript(script, () => {
        document.getElementById('app').style.display = 'block';
        render(<Container
          navs={navs}
          defaultNav="amapdemo"
          logo="amos amap"
        />, document.getElementById('app'));
      });

      // tools.asyncLoadScripts(scripts, cb) 加载多个 [{key, url}, {key, url}]
    }
  ```

  * loadcss

  ```js
  LoadCss.asyncLoadOne({
    key: 'amosframework',
    url: '/node_modules/amos-framework/dist/amosframework.css'
  });

  // 数组最前面的样式，优先级最低
  LoadCss.asyncLoadList([
    {
      key: 'amosframework',
      url: '/node_modules/amos-framework/dist/amosframework.css'
    }
  ]);
  ```

  * get `dt2react/lib/utils/get`

  ```js
  import get from 'dt2react/lib/utils/get';

  const object = { 'a': [{ 'b': { 'c': 3 } }] };
  get(object, 'a[0].b.c'); // 3
  get(object, ['a', '0', 'b', 'c']); // 3
  get(object, 'a.b.c', 'default'); // default
  ```

  * getCacheRequest `dt2react/lib/utils/cacheRequest`

  ```js
  import { getCacheRequest } from 'dt2react/lib/utils/cacheRequest';

  function getInfoAction(){
    return commonGet(url);
  }
  const cacheGetInfoAction = getCacheRequest(getInfoAction, url);
  // 使用时：
  cacheGetInfoAction().then(data => { ... });
  // 有参数的
  function getUserAction(userId){
    const _url = formatUrl(userInfoUrl, { userId });
    return commonGet(_url);
  }
  const tags = formatUrl(userInfoUrl, { userId: 333 });
  const cacheUserAction = getCacheRequest(getUserAction, tags);
  // 有参数，动态生成 actionTag
  const globalActionMapping = {};
  function cacheUserAction2(userId){
    const tags = formatUrl(userInfoUrl, { userId });
    if (!globalActionMapping[tags]){
      globalActionMapping[tags] = getCacheRequest(getUserAction, tags);
    }
    return globalActionMapping[tags](userId);
  }
  // 使用
  cacheUserAction2('112233').then(data => { ... });
  ```

------ utils end

### BrowserSupportCore

```js
/**
 * @return {bool} True if browser supports css animations.
 */
BrowserSupportCore.hasCSSAnimations();
/**
 * @return {bool} True if browser supports css transforms.
 */
BrowserSupportCore.hasCSSTransforms();
/**
 * @return {bool} True if browser supports css 3d transforms.
 */
BrowserSupportCore.hasCSS3DTransforms();
/**
 * @return {bool} True if browser supports css transitions.
 */
BrowserSupportCore.hasCSSTransitions();
```

### DOMMouseMoveTracker

### getVendorPrefixedName

```js
/**
 * @param {string} property Name of a css property to check for.
 * @return {?string} property name supported in the browser, or null if not
 * supported.
 */
getVendorPrefixedName(property);
```

### Query

```js
canUseDOM
activeElement()
contains(context, node)
getContainer(container, defaultContainer)
getHeight(node, client)

getOffset(node): { top, left, width, height }

getOffsetParent(node)
getPosition(node, offsetParent)
getScrollbarSize(recalc)
getWidth(node, client)
getWindow(node)
isOverflowing(container)
nodeName(node)
ownerDocument(componentOrElement)
ownerWindow(componentOrElement)
scrollLeft(node, val)
scrollTop(node, val)
```

### transition

## changelog

### v2.0.0

use es modules

### v1.1.6

modify `LoadScripts`, Optimize lib pkg

### v1.1.4

add `style/clientRect`

### v1.1.0

add `style/lineHeight`

## License

MIT

---
_Source: https://npm.io/package/dt2react · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
