前端

实体加载器

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

实体加载器的良好用途

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

当前可用实体

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

使用加载器有两种方式:作为 React “渲染属性” 组件,或作为 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 的数据库。如果您想使用渲染属性组件,您的代码将如下所示。

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>
    );
  }
}

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

@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 prop 传递给组件的根元素。它可以使用 classnames 包中的 cx 函数与附加类合并。
  • 为了使组件更具可重用性,组件应仅将其类或样式应用于组件的根元素,这些类或样式会影响其自身内容的布局/样式,但影响其自身在其父容器中的布局。例如,它可以包含内边距或 flex 类,但不应包含外边距或 flex-fullfullabsolutespread 等。这些应通过组件的消费者通过 classNamestyle props 传递,消费者知道组件应如何在其自身内部定位。
  • 避免在一个组件内将 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))。
  • 优先使用 function 声明来编写顶层函数,包括 React 函数组件。返回值的单行函数除外
// 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;
  • 避免嵌套三元运算符,因为它们通常会导致代码难以阅读。如果您的代码中存在依赖字符串值的逻辑分支,则在评估简单时优先使用对象作为多值的映射,或者在评估更复杂时(例如,在选择要返回的 React 组件时)使用 switch 语句。
// 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 中创建新 issue 来记录这些。理想情况下,代码应该以清晰自解释的方式编写。如果代码不够清晰,您应该首先尝试重写代码。如果由于某种原因无法清晰地编写,请添加注释来解释“为什么”。

// 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) {
  // ...
}
  • 常量使用大写字母
// 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. 选择任意表格,例如 People

在此处,点击以下内容将打开 <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 其他版本的文档。

© . All rights reserved.