前端

实体加载器

如果您正在开发新功能或通常需要获取前端的某些应用程序数据,实体加载器将是您的朋友。它们抽象了 API 调用、处理加载和错误状态、缓存以前加载的对象、使缓存失效(在某些情况下),并让您轻松执行更新或创建新项目。

实体加载器的良好用途

  • 我需要获取特定的 X(用户、数据库等)并显示它。
  • 我需要获取 X(数据库、问题等)的列表并显示它。

当前可用实体

  • 问题、仪表盘、脉冲
  • 集合
  • 数据库、表、字段、细分、指标
  • 用户、组
  • 在此处查看完整的当前实体列表:https://github.com/metabase/metabase/tree/master/frontend/src/metabase/entities

有两种使用加载器的方法,一种是作为 React “渲染 prop” 组件,另一种是作为 React 组件类装饰器(“高阶组件”)。

对象加载

在此示例中,我们将为新页面加载特定数据库的信息。

import React from "react";
import Databases from "metabase/entities/databases";

@Databases.load({ id: 4 })
class MyNewPage extends React.Component {
  render() {
    const { database } = this.props;
    return (
      <div>
        <h1>{database.name}</h1>
      </div>
    );
  }
}

此示例使用类装饰器请求并显示 ID 为 4 的数据库。如果您想使用渲染 prop 组件,您的代码将如下所示。

import React from "react";
import Databases from "metabase/entities/databases";

class MyNewPage extends React.Component {
  render() {
    const { database } = this.props;
    return (
      <div>
        <Databases.Loader id={4}>
          {({ database }) => <h1>{database.name}</h1>}
        </Databases.Loader>
      </div>
    );
  }
}

现在您很可能不只是想显示一个静态项目,因此对于您可能需要的一些值是动态的情况,您可以使用函数来获取 prop 并返回您需要的值。如果您使用的是组件方法,您可以像往常一样为动态值传递 prop。

@Databases.load({
  id: (state, props) => props.params.databaseId
}))

列表加载

加载项目列表就像应用 loadList 装饰器一样简单

import React from "react";
import Users from "metabase/entities/users";

@Users.loadList()
class MyList extends React.Component {
  render() {
    const { users } = this.props;
    return <div>{users.map((u) => u.first_name)}</div>;
  }
}

与对象加载器的 id 参数类似,您还可以传递一个 query 对象(如果 API 支持)

@Users.loadList({
  query: (state, props) => ({ archived: props.showArchivedOnly })
})

控制加载和错误状态

默认情况下,EntityObjectEntityList 加载器都将通过在内部使用 LoadingAndErrorWrapper 来处理加载状态。如果出于某种原因您想自行处理加载,您可以通过设置 loadingAndErrorWrapper: false 来禁用此行为。

包装对象

如果您将 wrapped: true 传递给加载器,则对象或对象将用辅助类包装,这些辅助类允许您执行诸如 user.getName()user.delete()user.update({ name: "new name" ) 之类的操作。操作已自动绑定到 dispatch

如果对象很多,这可能会导致性能损失。

实体 objectSelectorsobjectActions 中定义的任何其他选择器和操作都将作为包装对象的方法出现。

高级用法

您还可以直接使用 Redux 操作和选择器,例如 dispatch(Users.actions.loadList())Users.selectors.getList(state)

样式指南

设置 Prettier

我们使用 Prettier 来格式化我们的 JavaScript 代码,并且它由 CI 强制执行。我们建议将您的编辑器设置为“保存时格式化”。您还可以使用 yarn prettier 格式化代码,并使用 yarn lint-prettier 验证其是否已正确格式化。

我们使用 ESLint 来强制执行其他规则。它集成到 Webpack 构建中,或者您可以手动运行 yarn lint-eslint 进行检查。

React 和 JSX 样式指南

我们大部分遵循 Airbnb React/JSX 样式指南。ESLint 和 Prettier 应该能处理 Airbnb 样式指南中的大部分规则。例外情况将在此文档中说明。

  • 优先使用 React 函数组件而非类组件
  • 避免在 containers 文件夹中创建新组件,因为此方法已被弃用。相反,将连接组件和视图组件都存储在 components 文件夹中,以实现更统一和高效的组织。如果连接组件的尺寸显著增加,并且您需要提取视图组件,请选择使用 View 后缀。
  • 对于控制组件,我们通常使用 valueonChange。具有选项的控件(例如 RadioSelect)通常接受一个 options 数组,其中包含 namevalue 属性的对象。
  • 命名为 FooModalFooPopover 的组件通常指的是模态框/弹出框的 *内容*,应该在 Modal/ModalWithTriggerPopover/PopoverWithTrigger 中使用
  • 命名为 FooWidget 的组件通常包含一个 PopoverWithTrigger 中的 FooPopover,以及某种触发元素,通常是 FooName

  • 如果需要在类中绑定方法(而不是在构造函数中 this.method = this.method.bind(this);),请使用箭头函数实例属性,但仅当该函数需要绑定时(例如,如果您将其作为 prop 传递给 React 组件)
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // NO:
    this.handleChange = this.handleChange.bind(this);
  }
  // YES:
  handleChange = (e) => {
    // ...
  };
  // no need to bind:
  componentDidMount() {}
  render() {
    return <input onChange={this.handleChange} />;
  }
}
  • 对于样式组件,我们目前混合使用 styled-components“原子”/“实用优先” CSS 类
  • 优先使用 grid-styledBoxFlex 组件,而不是原始的 div
  • 组件通常应将其 className 属性传递给组件的根元素。它可以与来自 classnames 包的 cx 函数合并。
  • 为了使组件更具可重用性,组件应该只对其根元素应用类或样式,这些类或样式会影响其自身内容的布局/样式,但 *不* 影响其自身在其父容器中的布局。例如,它可以包含内边距或 flex 类,但不应包含外边距或 flex-fullfullabsolutespread 等。这些应该由组件的消费者通过 classNamestyle 属性传递,消费者知道组件应该如何在其自身内部定位。
  • 避免在单个组件中将 JSX 分解为单独的方法调用。优先内联 JSX,以便更好地查看 render 方法返回的 JSX 与组件的 stateprops 之间的关系。通过内联 JSX,您还可以更好地了解哪些部分应该和不应该成为单独的组件。

// don't do this
render () {
  return (
    <div>
      {this.renderThing1()}
      {this.renderThing2()}
      {this.state.thing3Needed && this.renderThing3()}
    </div>
  );
}

// do this
render () {
  return (
    <div>
      <button onClick={this.toggleThing3Needed}>toggle</button>
      <Thing2 randomProp={this.props.foo} />
      {this.state.thing3Needed && <Thing3 randomProp2={this.state.bar} />}
    </div>
  );
}

JavaScript 约定

  • import 语句应按类型排序,通常是:
    1. 外部库(react 通常排在首位,还有 ttagsunderscoreclassnames 等)
    2. Metabase 的顶级 React 组件和容器(metabase/components/*metabase/containers/* 等)
    3. Metabase 的 React 组件和容器特定于应用程序的此部分(metabase/*/components/* 等)
    4. Metabase 的 libentitiesservices、Redux 文件等
  • 优先使用 const 而非 let(永远不要使用 var)。仅当您有特定原因需要重新分配标识符时才使用 let(注意:这现在由 ESLint 强制执行)
  • 内联函数优先使用 箭头函数,特别是当您需要引用父作用域中的 this 时(几乎永远不应该需要 const self = this; 等),但通常即使不需要也应如此(例如 array.map(x => x * 2))。
  • 顶层函数,包括 React 函数组件,优先使用 function 声明。但返回值的单行函数除外。
// YES:
function MyComponent(props) {
  return <div>...</div>;
}
// NO:
const MyComponent = (props) => {
  return <div>...</div>;
};
// YES:
const double = (n) => n * 2;
// ALSO OK:
function double(n) {
  return n * 2;
}
  • 优先使用原生 Array 方法,而不是 underscore 的方法。我们对所有 ES6 功能都进行了 polyfill。对于原生未实现的功能,请使用 Underscore。
  • 优先使用 async/await,而不是直接使用 promise.then(...) 等。
  • 您可以使用赋值解构或参数解构,但避免深度嵌套解构,因为它们可能难以阅读,并且 prettier 有时会用额外的空白符格式化它们。
    • 避免从“实体”类对象中解构属性,例如不要执行 const { display_name } = column;
    • 不要直接解构 this,例如使用 const { foo } = this.props; const { bar } = this.state; 而不是 const { props: { foo }, state: { bar } } = this;
  • 避免嵌套三元表达式,因为它们通常会导致代码难以阅读。如果您的代码中存在依赖于字符串值的逻辑分支,则优先使用对象作为多值的映射(当评估简单时)或 switch 语句(当评估更复杂时,例如根据要返回哪个 React 组件进行分支)
// don't do this
const foo = str == 'a' ? 123 : str === 'b' ? 456 : str === 'c' : 789 : 0;

// do this
const foo = {
  a: 123,
  b: 456,
  c: 789,
}[str] || 0;

// or do this
switch (str) {
  case 'a':
    return <ComponentA />;
  case 'b':
    return <ComponentB />;
  case 'c':
    return <ComponentC />;
  case 'd':
  default:
    return <ComponentD />;
}

如果您的嵌套三元表达式的形式是评估为布尔值的谓词,请优先使用独立于单独的纯函数的 if/if-else/else 语句。

const foo = getFoo(a, b);

function getFoo(a, b, c) {
  if (a.includes("foo")) {
    return 123;
  } else if (a === b) {
    return 456;
  } else {
    return 0;
  }
}
  • 在代码库中添加注释时要谨慎。注释不应该用作提醒或待办事项——这些应该在 GitHub 中创建新问题来记录。理想情况下,代码应该以清晰的方式解释自己。如果不能,您应该首先尝试重写代码。如果由于某种原因您无法清晰地编写代码,请添加注释来解释“为什么”。

// don't do this--the comment is redundant

// get the native permissions for this db
const nativePermissions = getNativePermissions(perms, groupId, {
  databaseId: database.id,
});

// don't add TODOs -- they quickly become forgotten cruft

isSearchable(): boolean {
  // TODO: this should return the thing instead
  return this.isString();
}

// this is acceptable -- the implementer explains a not-obvious edge case of a third party library

// foo-lib seems to return undefined/NaN occasionally, which breaks things
if (isNaN(x) || isNaN(y)) {
  return;
}

  • 避免 if 语句中复杂的逻辑表达式
// don't do this
if (typeof children === "string" && children.split(/\n/g).length > 1) {
  // ...
}

// do this
const isMultilineText =
  typeof children === "string" && children.split(/\n/g).length > 1;
if (isMultilineText) {
  // ...
}
  • 常量使用大写字母(ALL_CAPS)
// do this
const MIN_HEIGHT = 200;

// also acceptable
const OBJECT_CONFIG_CONSTANT = {
  camelCaseProps: "are OK",
  abc: 123,
};
  • 优先使用命名导出而非默认导出
// this makes it harder to search for Widget
import Foo from "./Widget";
// do this to enforce using the proper name
import { Widget } from "./Widget";
  • 避免使用魔术字符串和数字
// don't do this
const options = _.times(10, () => ...);

// do this in a constants file
export const MAX_NUM_OPTIONS = 10;
const options = _.times(MAX_NUM_OPTIONS,  () => ...);

编写声明性代码

您应该为其他工程师编写代码,因为其他工程师花在阅读上的时间将比您花在编写(和重写)上的时间更多。代码在告诉计算机“做什么”而不是“怎么做”时更具可读性。避免使用像 for 循环这样的命令式模式

// don't do this
let foo = [];
for (let i = 0; i < list.length; i++) {
  if (list[i].bar === false) {
    continue;
  }

  foo.push(list[i]);
}

// do this
const foo = list.filter((entry) => entry.bar !== false);

在处理业务逻辑时,您不需要关心语言的具体细节。与其编写 const query = new Question(card).query();,这涉及到实例化一个新的 Question 实例并在该实例上调用 query 方法,不如引入一个函数,例如 getQueryFromCard(card),这样实现者就可以避免考虑从卡片中获取 query 值所涉及的内容。

组件样式树环

CSS 模块

.primary {
  color: -var(--mb-color-brand);
}
import S from "./Foo.css";

const Foo = () => <div className={S.primary} />;

Emotion(不推荐)

import styled from "@emotion/styled";

const Foo = styled.div`
  color: ${(props) => props.color};
`;

const Bar = ({ color }) => <Foo color={color} />;

弹出框

浮层是弹出框或模态框。

在 Metabase 核心中,它们具有视觉响应性:它们出现在触发其出现的元素上方或下方。其高度自动计算以使其适合屏幕。

在用户旅程中何处找到浮层

创建自定义问题时

  1. 从主页点击 新建,然后点击 问题
  2. 👀 自动在 选择你的起始数据 旁边打开的选项选择器是一个 <Popover />
  3. 选择 示例数据库,如果尚未选择
  4. 选择任何表,例如 人员

在这里,点击以下内容将打开 <Popover /> 组件

  • 选择列数据 部分中标注 FieldsPicker 控件右侧的箭头)
  • 数据 部分下方带有 + 号的灰色网格图标
  • 添加筛选器以缩小您的答案范围
  • 选择您要查看的指标
  • 选择一个列进行分组
  • 可视化 按钮上方带有上下箭头的 排序 图标

单元测试

设置模式

我们使用以下模式对组件进行单元测试

import React from "react";
import userEvent from "@testing-library/user-event";
import { Collection } from "metabase-types/api";
import { createMockCollection } from "metabase-types/api/mocks";
import { renderWithProviders, screen } from "__support__/ui";
import CollectionHeader from "./CollectionHeader";

interface SetupOpts {
  collection: Collection;
}

const setup = ({ collection }: SetupOpts) => {
  const onUpdateCollection = jest.fn();

  renderWithProviders(
    <CollectionHeader
      collection={collection}
      onUpdateCollection={onUpdateCollection}
    />,
  );

  return { onUpdateCollection };
};

describe("CollectionHeader", () => {
  it("should be able to update the name of the collection", () => {
    const collection = createMockCollection({
      name: "Old name",
    });

    const { onUpdateCollection } = setup({
      collection,
    });

    await userEvent.clear(screen.getByDisplayValue("Old name"));
    await userEvent.type(screen.getByPlaceholderText("Add title"), "New title");
    await userEvent.tab();

    expect(onUpdateCollection).toHaveBeenCalledWith({
      ...collection,
      name: "New name",
    });
  });
});

关键点

  • setup 函数
  • renderWithProviders 添加了应用程序使用的提供者,包括 redux

请求模拟

我们使用 fetch-mock 来模拟请求

import fetchMock from "fetch-mock";
import { setupCollectionsEndpoints } from "__support__/server-mocks";

interface SetupOpts {
  collections: Collection[];
}

const setup = ({ collections }: SetupOpts) => {
  setupCollectionsEndpoints({ collections });

  // renderWithProviders and other setup
};

describe("Component", () => {
  it("renders correctly", async () => {
    setup();
    expect(await screen.findByText("Collection")).toBeInTheDocument();
  });
});

关键点

  • setup 函数
  • 调用 __support__/server-mocks 中的辅助函数来设置数据端点

阅读其他版本的 Metabase 的文档。

这有帮助吗?

感谢您的反馈!
想改进这些文档吗? 提出更改。
© . This site is unofficial and not affiliated with Metabase, Inc.