Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(interaction): share states #5419

Merged
merged 1 commit into from
Aug 17, 2023
Merged

fix(interaction): share states #5419

merged 1 commit into from
Aug 17, 2023

Conversation

pearmini
Copy link
Member

交互

解决有多个交互的时候,状态不共享的问题:比如 legend 和 slider 的状态不能同时保留。(fix: #5393)

开始使用

export function countriesBubbleMultiLegends(): G2Spec {
  return {
    type: 'point',
    padding: 'auto',
    data: {
      type: 'fetch',
      value: 'data/countries.json',
    },
    encode: {
      x: 'change in female rate',
      y: 'change in male rate',
      size: 'pop',
      color: 'continent',
      shape: 'point',
    },
    scale: {
      color: { range: ['#ffd500', '#82cab2', '#193442', '#d18768', '#7e827a'] },
      x: { nice: true },
      y: { nice: true },
      size: { range: [4, 30] },
    },
    style: { stroke: '#bbb', fillOpacity: 0.8 },
    slider: {
      x: { labelFormatter: (d) => d.toFixed(1) },
      y: { labelFormatter: (d) => d.toFixed(1) },
    },
  };
}

解决思路

一些交互的状态是保留在 DOM 上,比如 elementHighlight;一些交互的状态是通过 spec 体现:比如 slider 改变 x 和 y scale 的 domain。这里主要解决第二种交互。

首先用一个全局 store 存储每个交互或者组件对应的 state,该 state 是一个 reducer:是个函数,参数是当前的 options,返回新的 options。

const store = new Map();

同时提供方法更新每个交互的 reducer,以及根据所有的 reducer 重新渲染的方法 udpate。

function setState(key, reducer = x => x) {
  store.set(key, reducer);
}

function update() {
   // 合成一个函数
   const reducer = compose(Array.from(store.values()));
   // 基于原始 options,叠加状态 options
   const newOptions = reducer(options);
   // 根据新的 options 重新渲染。
   return await rerender(newOptions);
}

当触法更新交互状态的时候,首先调用 setState 方法,然后调用 update 方法。

setState(options => newOptions);
update();

@pearmini pearmini requested a review from hustcc August 17, 2023 05:51
@pearmini pearmini force-pushed the fix/multi-interaction branch from 152439a to adacc06 Compare August 17, 2023 05:59
@coveralls
Copy link

Pull Request Test Coverage Report for Build 5887315418

  • 73 of 73 (100.0%) changed or added relevant lines in 6 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage increased (+0.02%) to 89.462%

Totals Coverage Status
Change from base Build 5886439667: 0.02%
Covered Lines: 9667
Relevant Lines: 10466

💛 - Coveralls

@pearmini pearmini merged commit 328aeea into v5 Aug 17, 2023
@pearmini pearmini deleted the fix/multi-interaction branch August 17, 2023 07:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

交互状态没有共享
3 participants