示例工程 45-web-component-forms

45-web-component-forms/app/index.html

html · 15 KB

运行:表单关联组件 · 让自定义元素进表单

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>表单关联组件 · 让自定义元素进表单</title>
    <meta name="description" content="formAssociated、ElementInternals、setFormValue、setValidity、reset 与 disabled。" />
    <style>
      * { box-sizing: border-box; }
      body {
        margin: 0;
        min-height: 100vh;
        padding: 30px 20px 40px;
        background: #f8fafc;
        color: #0f172a;
        font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
        line-height: 1.7;
      }
      .page { width: min(100%, 800px); margin: 0 auto; }
      .site-header { display: flex; justify-content: space-between; gap: 16px; padding-bottom: 14px; border-bottom: 1px solid #e2e8f0; }
      .brand { font-weight: 700; letter-spacing: 0.14em; font-size: 13px; }
      nav a { color: #2563eb; font-size: 13px; text-decoration: none; }
      nav a + a { margin-left: 14px; }
      main { padding: 22px 0; }
      .eyebrow { margin: 0; color: #64748b; font-size: 11px; letter-spacing: 0.18em; }
      h1 { margin: 6px 0 10px; font-size: clamp(30px, 6vw, 42px); line-height: 1.15; }
      .lead { margin: 0 0 18px; color: #334155; font-size: 17px; }
      section { margin-top: 22px; padding-top: 16px; border-top: 1px solid #e2e8f0; }
      h2 { margin: 0 0 10px; font-size: 21px; }
      p { margin: 0 0 12px; color: #334155; }
      ul { margin: 8px 0 12px; padding-left: 24px; color: #334155; }
      li + li { margin-top: 4px; }
      form { padding: 16px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
      .field { margin-bottom: 14px; }
      .field > label, legend { display: block; margin-bottom: 4px; font-size: 14px; font-weight: 600; }
      input[type="text"] { width: 100%; max-width: 360px; padding: 7px 9px; border: 1px solid #cbd5e1; border-radius: 6px; font: inherit; }
      fieldset { margin: 0 0 14px; padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 8px; }
      .actions { display: flex; gap: 8px; margin-top: 14px; }
      button { padding: 7px 14px; border: 1px solid #2563eb; border-radius: 6px; background: #2563eb; color: #fff; font: inherit; }
      button[type="reset"] { border-color: #cbd5e1; background: #fff; color: #0f172a; }
      .summary { margin-top: 12px; padding: 8px 12px; border-left: 4px solid #16a34a; background: #f0fdf4; color: #14532d; font-size: 14px; }
      .summary[data-state="error"] { border-color: #dc2626; background: #fef2f2; color: #991b1b; }
      pre { margin: 10px 0 0; padding: 14px; overflow-x: auto; border-radius: 10px; background: #0f172a; color: #e2e8f0; font-size: 12px; line-height: 1.7; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, Menlo, monospace; font-size: 0.92em; }
      .note { padding: 12px 14px; border-left: 4px solid #2563eb; border-radius: 6px; background: #eff6ff; color: #1e3a8a; font-size: 14px; }
      footer { margin-top: 24px; padding-top: 14px; border-top: 1px solid #e2e8f0; color: #64748b; font-size: 12px; }
      @media (max-width: 560px) {
        body { padding: 18px 14px 32px; }
        .site-header { flex-direction: column; }
      }
    </style>
  </head>
  <body>
    <div class="page">
      <header class="site-header">
        <span class="brand">FORMS / 2026</span>
        <nav aria-label="页内导航">
          <a href="#form">示例</a>
          <a href="#internals">接口</a>
          <a href="#rules">规则</a>
        </nav>
      </header>

      <main>
        <p class="eyebrow">LESSON / 45</p>
        <h1>表单关联组件</h1>
        <p class="lead">
          自定义元素默认不参与表单。加上 <code>formAssociated</code> 与 <code>ElementInternals</code>,它才能提交值、参与校验、被重置与禁用。
        </p>

        <section id="form">
          <h2>1. 一个真实表单</h2>
          <p>下面两个控件都是自定义元素,但 <code>FormData</code> 能像原生控件一样读到它们。</p>

          <form id="demo-form">
            <div class="field">
              <label for="name">称呼</label>
              <input id="name" name="name" type="text" value="林小满" required />
            </div>

            <fieldset>
              <legend>满意度</legend>
              <x-rating id="rating" name="rating" label="满意度" value="4" required></x-rating>
            </fieldset>

            <x-consent name="updates" value="yes" label="接收更新" required>
              接收产品更新邮件
            </x-consent>

            <div class="actions">
              <button type="submit">提交</button>
              <button type="reset">重置</button>
            </div>

            <p class="summary" id="summary" role="status">尚未提交。</p>
            <pre id="data"><code>{}</code></pre>
          </form>
        </section>

        <section id="internals">
          <h2>2. 关键接口</h2>
          <ul>
            <li><code>static formAssociated = true</code>:加入表单。</li>
            <li><code>this.attachInternals()</code>:拿到 <code>ElementInternals</code>。</li>
            <li><code>internals.setFormValue(value)</code>:提交值,<code>null</code> 表示不提交。</li>
            <li><code>internals.setValidity(flags, message, anchor)</code>:校验状态与提示。</li>
            <li><code>formResetCallback()</code>:表单重置。</li>
            <li><code>formDisabledCallback(disabled)</code>:祖先 fieldset 禁用。</li>
            <li><code>internals.labels</code>:关联的 label 元素。</li>
          </ul>
          <p class="note">值、校验与状态都由组件自己维护;浏览器负责把它们接进表单。</p>
        </section>

        <section id="rules">
          <h2>3. 规则</h2>
          <ul>
            <li>只在需要提交值时使用表单关联,展示组件不需要。</li>
            <li>初始化顺序:构造函数里 <code>attachInternals</code>,连接后设置值与校验。</li>
            <li>不提交值时调用 <code>setFormValue(null)</code>。</li>
            <li>校验失败要给出可读消息与锚点。</li>
            <li>重置要回到初始值,而不是清空。</li>
            <li>禁用要同时处理交互、样式与可访问性。</li>
          </ul>
        </section>
      </main>

      <footer>
        <p>示例数据为虚构,仅用于教学。</p>
      </footer>
    </div>

    <template id="rating-tpl">
      <style>
        :host { display: inline-block; }
        :host([disabled]) { opacity: 0.55; }
        .stars { display: inline-flex; gap: 2px; }
        button { width: 38px; height: 38px; padding: 0; border: 1px solid transparent; border-radius: 8px; background: transparent; color: #cbd5e1; font-size: 24px; line-height: 1; }
        button:hover { background: #f1f5f9; }
        button[aria-pressed="true"] { color: #d97706; }
        .hint { margin-left: 8px; color: #64748b; font-size: 13px; }
        :host(:invalid) .hint { color: #b91c1c; }
      </style>
      <div class="stars" part="stars" role="group"></div>
      <span class="hint" part="hint"></span>
    </template>

    <script>
      class XRating extends HTMLElement {
        static formAssociated = true;
        static observedAttributes = ["value", "required", "disabled", "label"];

        constructor() {
          super();
          this.internals = this.attachInternals();
          this.value = 0;
          this.defaultValue = 0;
          const tpl = document.getElementById("rating-tpl");
          this.attachShadow({ mode: "open" }).append(tpl.content.cloneNode(true));
          this.stars = this.shadowRoot.querySelector(".stars");
          this.hint = this.shadowRoot.querySelector(".hint");
          for (let i = 1; i <= 5; i += 1) {
            const button = document.createElement("button");
            button.type = "button";
            button.textContent = "★";
            button.setAttribute("aria-label", i + " 星");
            button.addEventListener("click", () => {
              if (this.hasAttribute("disabled")) return;
              this.value = i;
              this.sync();
            });
            this.stars.append(button);
          }
        }

        connectedCallback() {
          this.defaultValue = Number(this.getAttribute("value")) || 0;
          this.value = this.defaultValue;
          this.internals.role = "group";
          this.internals.ariaLabel = this.getAttribute("label") ?? "评分";
          this.internals.ariaDisabled = String(this.hasAttribute("disabled"));
          this.sync();
        }

        attributeChangedCallback(name, oldValue, newValue) {
          if (this.isConnected) {
            if (name === "value") this.value = Number(newValue) || 0;
            this.internals.ariaLabel = this.getAttribute("label") ?? "评分";
            this.internals.ariaDisabled = String(this.hasAttribute("disabled"));
            this.sync();
          }
        }

        get value() {
          return this._value ?? 0;
        }

        set value(next) {
          this._value = Math.max(0, Math.min(5, Math.round(Number(next) || 0)));
        }

        sync() {
          const value = this.value;
          [...this.stars.children].forEach((button, index) => {
            button.setAttribute("aria-pressed", String(index + 1 <= value));
            button.disabled = this.hasAttribute("disabled");
          });
          this.hint.textContent = value ? value + " / 5" : "请选择";

          if (value > 0) {
            this.internals.setFormValue(String(value));
          } else {
            this.internals.setFormValue(null);
          }

          if (this.hasAttribute("required") && value === 0) {
            this.internals.setValidity(
              { valueMissing: true },
              "请选择满意度",
              this.stars
            );
          } else {
            this.internals.setValidity({});
          }
        }

        formResetCallback() {
          this.value = this.defaultValue;
          this.sync();
        }

        formDisabledCallback(disabled) {
          this.toggleAttribute("disabled", disabled);
          this.sync();
        }

        formStateRestoreCallback(state) {
          this.value = Number(state) || 0;
          this.sync();
        }
      }
      customElements.define("x-rating", XRating);

      class XConsent extends HTMLElement {
        static formAssociated = true;
        static observedAttributes = ["checked", "required", "disabled", "value"];

        constructor() {
          super();
          this.internals = this.attachInternals();
          const root = this.attachShadow({ mode: "open" });
          root.innerHTML = `
            <style>
              :host { display: inline-flex; align-items: flex-start; gap: 8px; padding: 6px 0; cursor: pointer; }
              :host([disabled]) { opacity: 0.55; cursor: default; }
              .box { flex: none; width: 18px; height: 18px; margin-top: 3px; border: 1px solid #94a3b8; border-radius: 4px; background: #fff; display: grid; place-items: center; color: #fff; font-size: 13px; }
              :host([checked]) .box { border-color: #2563eb; background: #2563eb; }
              .box::after { content: ""; }
              :host([checked]) .box::after { content: "✓"; }
              .text { font-size: 14px; color: #334155; }
              .req { color: #b91c1c; }
            </style>
            <span class="box" part="box"></span>
            <span class="text"><slot></slot><span class="req" aria-hidden="true"> *</span></span>
          `;
          this.internals.role = "checkbox";
          this.tabIndex = 0;
          this.addEventListener("click", () => this.toggle());
          this.addEventListener("keydown", (event) => {
            if (event.key === " " || event.key === "Enter") {
              event.preventDefault();
              this.toggle();
            }
          });
        }

        connectedCallback() {
          this.defaultChecked = this.hasAttribute("checked");
          this.internals.ariaLabel = this.getAttribute("label") ?? this.textContent.trim();
          this.sync();
        }

        attributeChangedCallback() {
          if (this.isConnected) this.sync();
        }

        get checked() {
          return this.hasAttribute("checked");
        }

        set checked(next) {
          this.toggleAttribute("checked", Boolean(next));
        }

        toggle() {
          if (this.hasAttribute("disabled")) return;
          this.checked = !this.checked;
        }

        sync() {
          const checked = this.checked;
          this.internals.ariaChecked = String(checked);
          this.internals.ariaDisabled = String(this.hasAttribute("disabled"));
          this.internals.ariaRequired = String(this.hasAttribute("required"));
          if (checked) {
            this.internals.setFormValue(this.getAttribute("value") ?? "on");
            this.internals.setValidity({});
          } else {
            this.internals.setFormValue(null);
            if (this.hasAttribute("required")) {
              this.internals.setValidity(
                { valueMissing: true },
                "请勾选后再提交",
                this.shadowRoot.querySelector(".box")
              );
            } else {
              this.internals.setValidity({});
            }
          }
        }

        formResetCallback() {
          this.checked = this.defaultChecked;
          this.sync();
        }

        formDisabledCallback(disabled) {
          this.toggleAttribute("disabled", disabled);
          this.sync();
        }

        formStateRestoreCallback(state) {
          this.checked = state === "on" || state === "true";
          this.sync();
        }
      }
      customElements.define("x-consent", XConsent);

      const form = document.getElementById("demo-form");
      const summary = document.getElementById("summary");
      const data = document.getElementById("data");

      const showData = () => {
        const entries = Object.fromEntries(new FormData(form).entries());
        data.textContent = JSON.stringify(entries, null, 2);
        return entries;
      };

      form.addEventListener("submit", (event) => {
        event.preventDefault();
        const entries = showData();
        summary.dataset.state = "ok";
        summary.textContent = "已提交:" + Object.keys(entries).join("、");
      });

      form.addEventListener("reset", () => {
        summary.dataset.state = "";
        summary.textContent = "已重置为初始值。";
        setTimeout(showData, 0);
      });

      form.addEventListener("invalid", (event) => {
        summary.dataset.state = "error";
        summary.textContent = "请先修正表单:" + (event.target.getAttribute("name") ?? event.target.tagName);
      }, true);

      showData();
    </script>
  </body>
</html>