首页 > web前端 > js教程 > 正文

通过实践学习 TDD:在 Umbraco 的富文本编辑器中标记成员

Barbara Streisand
发布: 2024-10-08 06:21:01
原创
808 人浏览过

Learning TDD by doing: Tagging members in Umbraco

在我正在构建的系统中,我需要能够在网站的文本中提及 Umbraco 成员。为此,我需要构建 Umbraco 富文本编辑器的扩展:TinyMCE。

语境

作为内容编辑者,我想在消息或文章中标记成员,以便他们收到有关他们的新内容的通知。

我研究了类似的实现,例如 Slack 或 X 上的实现。Slack 在编写过程中使用特殊的 html 标签进行提及,然后使用特定格式的令牌将数据发送到后端。我决定采取类似的方法,但现在忘记翻译步骤。在内容中,提及将如下所示:


<mention user-id="1324" class="mceNonEditable">@D_Inventor</mention>


登录后复制

初步探索

在开始构建之前,我一直在寻找连接 Umbraco 中的 TinyMCE 的方法。这是我最不喜欢在 Umbraco 后台扩展的事情之一。不过我之前已经这样做过,并且我发现如果我在 AngularJS 中的 Umbraco 的tinyMceService 上创建一个装饰器,扩展编辑器是最简单的。在 TinyMCE 的文档中,我发现了一个名为“autoCompleters”的功能,它完全满足了我的需要,因此我可以使用编辑器。我的初始代码(尚未进行任何测试)如下所示:


rtedecorator.$inject = ["$delegate"];
export function rtedecorator($delegate: any) {
  const original = $delegate.initializeEditor;

  $delegate.initializeEditor = function (args: any) {
    original.apply($delegate, arguments);

    args.editor.contentStyles.push("mention { background-color: #f7f3c1; }");
    args.editor.ui.registry.addAutocompleter("mentions", {
      trigger: "@",
      fetch: (
        pattern: string,
        maxResults: number,
        _fetchOptions: Record<string, unknown>
      ): Promise<IMceAutocompleteItem[]>
        // TODO: fetch from backend
        => Promise.resolve([{ type: "autocompleteitem", value: "1234", text: "D_Inventor" }]),
      onAction: (api: any, rng: Range, value: string): void => {
        // TODO: business logic
        api.hide();
      },
    });
  };

  return $delegate;
}


登录后复制

我在这个项目中使用了 vite 和 typescript,但我没有安装任何 TinyMCE 类型。现在我会保留any并尽可能避免TinyMCE。

使用 TDD 进行构建

我决定使用 jest 进行测试。我发现入门很简单,并且很快就成功了。

✅ Success
I learned a new tool for unit testing in frontend code. I succesfully applied the tool to write a frontend with unit tests

我编写了第一个测试:

提及-manager.test.ts


describe("MentionsManager.fetch", () => {
  let sut: MentionsManager;
  let items: IMention[];

  beforeEach(() => {
    items = [];
    sut = new MentionsManager();
  });

  test("should be able to fetch one result", async () => {
    items.push({ userId: "1234", userName: "D_Inventor" });
    const result = await sut.fetch(1);
    expect(result).toHaveLength(1);
  });
});


登录后复制

Typescript 编译器的严格性让我有些惊讶。此处的分步操作实际上意味着不添加任何您尚未实际使用的内容。例如,我想添加对“UI”的引用,因为我知道稍后会使用它,但在使用构造函数中放入的所有内容之前,我实际上无法编译 MentionsManager。

经过几轮红、绿和重构,我最终得到了这些测试:

提及-manager.test.ts


describe("MentionsManager.fetch", () => {
  let sut: MentionsManager;
  let items: IMention[];

  beforeEach(() => {
    items = [];
    sut = new MentionsManager(() => Promise.resolve(items));
  });

  test("should be able to fetch one result", async () => {
    items.push({ userId: "1234", userName: "D_Inventor" });
    const result = await sut.fetch(1);
    expect(result).toHaveLength(1);
  });

  test("should be able to fetch empty result", async () => {
    const result = await sut.fetch(1);
    expect(result).toHaveLength(0);
  });

  test("should be able to fetch many results", async () => {
    items.push({ userId: "1324", userName: "D_Inventor" }, { userId: "3456", userName: "D_Inventor2" });
    const result = await sut.fetch(2);
    expect(result).toHaveLength(2);
  });

  test("should return empty list upon error", () => {
    const sut = new MentionsManager(() => {
      throw new Error("Something went wrong while fetching");
    }, {} as IMentionsUI);
    return expect(sut.fetch(1)).resolves.toHaveLength(0);
  });
});


登录后复制

有了这个逻辑,我就可以从任何来源获取提及并通过“fetch”挂钩在 RTE 中显示它们。
我使用相同的方法创建一个“pick”方法来获取选定的成员并将提及插入到编辑器中。这是我最终得到的代码:

提及-manager.ts


export class MentionsManager {
  private mentions: IMention[] = [];

  constructor(
    private source: MentionsAPI,
    private ui: IMentionsUI
  ) {}

  async fetch(take: number, query?: string): Promise<IMention[]> {
    try {
      const result = await this.source(take, query);
      if (result.length === 0) return [];
      this.mentions = result;

      return result;
    } catch {
      return [];
    }
  }

  pick(id: string, location: Range): void {
    const mention = this.mentions.find((m) => m.userId === id);
    if (!mention) return;

    this.ui.insertMention(mention, location);
  }
}


登录后复制
❓ Uncertainty
The Range interface is a built-in type that is really difficult to mock and this interface leaks an implementation detail into my business logic. I feel like there might've been a better way to do this.

回顾

总的来说,我认为我最终得到了易于更改的简单代码。这段代码中仍有一些部分我不太喜欢。我希望业务逻辑来驱动 UI,但代码最终更像是一个简单的商店,它也对 UI 进行了一次调用。我想知道是否可以更牢固地包装 UI,以便更好地利用管理器。

以上是通过实践学习 TDD:在 Umbraco 的富文本编辑器中标记成员的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!