扩展客户端行为

备注

本文档概述如何扩展 Wagtail 的客户端行为。关于 Wagtail 各 JavaScript 组件更详细的 API 参考,见 JavaScript 组件。

很多常见定制都无需深入 JavaScript 即可完成,但取决于你想利用或定制客户端交互的哪些部分,你可能需要使用 React、Stimulus 或纯(原生)JS。

React 用于 Wagtail 中较复杂的部分,例如侧边栏、评论系统和 Draftail 富文本编辑器。 对于基础的 JavaScript 驱动的交互,Wagtail 正在向 Stimulus 迁移。

你不需要了解或使用这些库就能为元素添加自定义行为,而且很多情况下简单的 JavaScript 就够用了,但对更复杂的用例,Stimulus 是推荐的做法。

基于这些库构建的许多定制,都不需要为你的自定义 Wagtail 安装运行 Node.js 工具链,但在某些情况下,例如构建软件包时,它可能让较复杂的开发更轻松。

备注

避免使用 jQuery 和未文档化的 jQuery 插件,因为它们会在 Wagtail 未来的版本中被移除。

添加自定义 JavaScript

在 Wagtail 的管理后台中,有几种添加 JavaScript 的方式。

最简单的方式是通过 hook 添加全局 JavaScript 文件,见 insert_editor_js 和 insert_global_admin_js。

对于仅在特定 Widget 被使用时才加载的 JavaScript,你可以添加一个内部 Media 类,确保该文件在 widget 被使用时加载,见 Django 关于其表单 Media 类的文档。

类似地,Wagtail 的 模板组件 提供了 media 属性或 Media 类,用于在渲染时添加脚本。

这些做法都会确保在核心 JavaScript 管理文件加载完成之后,所添加的文件才会在管理后台中被使用。

用 DOM 事件扩展

在着手客户端定制或引入新组件时,先尽量让实现保持简单,你可能根本不需要了解 Stimulus、React、JavaScript 模块或构建系统就能达成目标。

为浏览器附加行为最简单的方式是通过 DOM 事件和纯(原生)JavaScript。

Wagtail 的自定义 DOM 事件

Wagtail 通过监听或派发自定义 DOM 事件支持一些自定义行为。

用 Stimulus 扩展

Wagtail 使用 Stimulus 在管理后台中提供轻量的客户端交互或自定义 JavaScript widget。

使用 Stimulus 的关键好处是,当 widget 动态出现时(例如在模态框、InlinePanel 或 StreamField 面板中),你的代码无需手动初始化。

Stimulus 手册是学习如何与 Stimulus 配合使用并理解它的最佳资料。

添加自定义 Stimulus 控制器

Wagtail 暴露了两个供使用 Stimulus 的客户端全局对象。

  1. window.wagtail.app,核心管理后台 Stimulus WagtailApplication 实例。

  2. window.StimulusModule,从 @hotwired/stimulus 导出的 Stimulus 模块。

首先,创建一个自定义的 Stimulus 控制器,用JavaScript 类继承扩展基础类 window.StimulusModule.Controller。如果你使用构建工具,可以通过 import { Controller } from '@hotwired/stimulus'; 导入你的基础控制器。

创建好自定义控制器之后,你需要通过 window.wagtail.app.register 方法手动注册你的 Stimulus 控制器。

一个简单的控制器示例

首先,创建你的 HTML,让它出现在 Wagtail 管理后台的某个位置。

<!-- Will log 'My controller has connected: hi' to the console -->
<div data-controller="my-controller">Hi</div>
<!-- Will log 'My controller has connected: hello' to the console, with the span element-->
<div data-controller="my-controller">
    Hello <span data-my-controller-target="label"></span>
</div>

其次,创建一个包含控制器代码的 JavaScript 文件。该控制器会在 connect 时记录一条简单消息,connect 发生在控制器被创建并连接到带有匹配 data-controller 属性的 HTML 元素之后。

// myapp/static/js/example.js

class MyController extends window.StimulusModule.Controller {
    static targets = ['label'];
    connect() {
        console.log(
            'My controller has connected:',
            this.element.innerText,
            this.labelTargets,
        );
    }
}

window.wagtail.app.register('my-controller', MyController);

最后,用 hook 把这个 JavaScript 文件加载到 Wagtail 的管理后台。

# myapp/wagtail_hooks.py
from django.templatetags.static import static
from django.utils.html import format_html

from wagtail import hooks


@hooks.register("insert_global_admin_js")
def global_admin_js():
    return format_html('<script src="{}"></script>', static("js/example.js"))

现在你刷新那个显示这些 HTML 的管理后台页面,应该能在控制台看到两条日志。

一个更复杂的控制器示例

现在我们来创建一个 WordCountController,它在被控制的 input 元素旁边添加一个小小的 output 元素,显示已输入的词数。

// myapp/static/js/word-count-controller.js
class WordCountController extends window.StimulusModule.Controller {
    static values = { max: { default: 10, type: Number } };

    connect() {
        this.setupOutput();
        this.updateCount();
    }

    setupOutput() {
        if (this.output) return;
        const template = document.createElement('template');
        template.innerHTML = `<output name='word-count' for='${this.element.id}' class='output-label'></output>`;
        const output = template.content.firstChild;
        this.element.insertAdjacentElement('beforebegin', output);
        this.output = output;
    }

    updateCount(event) {
        const value = event ? event.target.value : this.element.value;
        const words = (value || '').split(' ');
        this.output.textContent = `${words.length} / ${this.maxValue} words`;
    }

    disconnect() {
        this.output && this.output.remove();
    }
}
window.wagtail.app.register('word-count', WordCountController);

这样,数据属性 data-word-count-max-value 决定该控制器的「配置」,而数据属性中的动作则决定输出元素更新的「触发时机」。

# models.py
from django import forms

from wagtail.admin.panels import FieldPanel
from wagtail.models import Page


class BlogPage(Page):
    # ...
    content_panels = Page.content_panels + [
        FieldPanel('subtitle', classname="full"),
        FieldPanel(
            'introduction',
            classname="full",
            widget=forms.TextInput(
                attrs={
                    'data-controller': 'word-count',
                    # allow the max number to be determined with attributes
                    # note we can use Python values here, Django will handle the string conversion (including escaping if applicable)
                    'data-word-count-max-value': 5,
                    # decide when you want the count to update with data-action
                    # (e.g. 'blur->word-count#updateCount' will only update when field loses focus)
                    'data-action': 'word-count#updateCount paste->word-count#updateCount',
                }
            )
        ),
    #...

下面这段代码展示了 insert_editor_js hook 用法的一个更高级版本,它被设置为追加供后续控制器使用的额外脚本。

# wagtail_hooks.py
from django.utils.html import format_html_join
from django.templatetags.static import static

from wagtail import hooks


@hooks.register("insert_editor_js")
def editor_js():
    # add more controller code as needed
    js_files = [
        "js/word-count-controller.js",
    ]
    return format_html_join(
        "\n",
        '<script src="{0}"></script>',
        ((static(filename),) for filename in js_files),
    )

你应该能在自己的博客页面中看到,introduction 字段旁边现在多了一个小小的 output 元素,显示已用词数和最大词数。

一个更复杂的 widget 示例

对于更复杂的 widget,现在只要 widget 出现在渲染出的 HTML 中(无论是初次加载还是动态出现),我们都可以集成额外的库,无需任何内联 script 元素。

在这个示例中,我们将使用 Coloris JavaScript 库构建一个颜色选择器 widget,并支持自定义 widget 选项。

首先从 HTML 开始,它建立在 Wagtail 为 FieldPanel 和 FieldBlock 所支持的 Django widgets 体系之上。我们用 build_attrs 方法构建合适的 Stimulus 数据属性,以支持把常见数据结构传入控制器。

请注意,我们对复杂取值(此处是一个字符串列表)使用了 json.dumps,Django 在渲染时会自动转义这些值,从而避免不安全的客户端代码的常见成因。

# myapp/widgets.py
import json

from django.forms import Media, TextInput

from django.utils.translation import gettext as _


class ColorWidget(TextInput):
    """
    See https://coloris.js.org/
    """

    def __init__(self, attrs=None, swatches=[], theme="large"):
        self.swatches = swatches
        self.theme = theme
        super().__init__(attrs=attrs)

    def build_attrs(self, *args, **kwargs):
        attrs = super().build_attrs(*args, **kwargs)
        attrs["data-controller"] = "color"
        attrs["data-color-theme-value"] = self.theme
        attrs["data-color-swatches-value"] = json.dumps(swatches)
        return attrs

    @property
    def media(self):
        return Media(
            js=[
                # load the UI library
                "https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js",
                # load controller JS
                "js/color-controller.js",
            ],
            css={
                "all": [
                    "https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.css"
                ]
            },
        )

至于 Stimulus 控制器,我们把值传给该 JavaScript 库,其中包括通过 this.element.id 对被控制元素的引用。

// myapp/static/js/color-controller.js

class ColorController extends window.StimulusModule.Controller {
    static values = { swatches: Array, theme: String };

    connect() {
        // create
        Coloris({ el: `#${this.element.id}` });

        // set options after initial creation
        setTimeout(() => {
            Coloris({ swatches: this.swatchesValue, theme: this.themeValue });
        });
    }
}

window.wagtail.app.register('color', ColorController);

现在就可以在任何 FieldPanel 或 StreamField 的任何 FieldBlock 中使用这个 widget,它会自动为该字段的元素实例化 JavaScript。

# blocks.py

# ... other imports
from django import forms
from wagtail.blocks import FieldBlock

from .widgets import ColorWidget


class ColorBlock(FieldBlock):
    def __init__(self, *args, **kwargs):
        swatches = kwargs.pop("swatches", [])
        theme = kwargs.pop("theme", "large")
        self.field = forms.CharField(widget=ColorWidget(swatches=swatches, theme=theme))
        super().__init__(*args, **kwargs)
# models.py

# ... other imports
from django import forms
from wagtail.admin.panels import FieldPanel

from .blocks import ColorBlock
from .widgets import ColorWidget


BREAD_COLOR_PALETTE = ["#CFAC89", "#C68C5F", "#C47647", "#98644F", "#42332E"]


class BreadPage(Page):
    body = StreamField(
        [
            # ...
            ("color", ColorBlock(swatches=BREAD_COLOR_PALETTE)),
            # ...
        ],
        use_json_field=True,
    )
    color = models.CharField(blank=True, max_length=50)

    # ... other fields

    content_panels = Page.content_panels + [
        # ... other panels
        FieldPanel("body"),
        FieldPanel("color", widget=ColorWidget(swatches=BREAD_COLOR_PALETTE)),
    ]

使用构建系统

你需要确保构建输出为 ES6/ES2015 或更高版本。你可以使用暴露的全局模块 window.StimulusModule,也可以通过 npm 模块 @hotwired/stimulus 提供自己的。

// myapp/static/js/word-count-controller.js
import { Controller } from '@hotwired/stimulus';

class WordCountController extends Controller {
    // ... the same as above
}

window.wagtail.app.register('word-count', WordCountController);

你可能希望避免把 Stimulus 打包进你的 JavaScript 输出,而是把该全局对象当作外部/别名模块处理,具体做法请参考你所用构建系统的文档。

用 React 扩展

要定制或扩展 React 组件,你可能也需要使用 React,以及其它相关库。

为便于这样做,Wagtail 把其 React 相关依赖以全局变量的形式暴露在管理后台中。可用的包如下:

// 'focus-trap-react'
window.FocusTrapReact;
// 'react'
window.React;
// 'react-dom'
window.ReactDOM;
// 'react-transition-group/CSSTransitionGroup'
window.CSSTransitionGroup;

Wagtail 也暴露了自己的一些 React 组件。你可以复用:

window.wagtail.components.Icon;
window.wagtail.components.Portal;

包含富文本编辑器的页面还可以访问:

// 'draft-js'
window.DraftJS;
// 'draftail'
window.Draftail;

// Wagtail’s Draftail-related APIs and components.
window.draftail;
window.draftail.DraftUtils;
window.draftail.ModalWorkflowSource;
window.draftail.ImageModalWorkflowSource;
window.draftail.EmbedModalWorkflowSource;
window.draftail.LinkModalWorkflowSource;
window.draftail.DocumentModalWorkflowSource;
window.draftail.Tooltip;
window.draftail.TooltipEntity;

扩展 Draftail

扩展 StreamField

扩展编辑器