Project Icon

snabbdom

轻量级高性能的模块化虚拟 DOM 库

Snabbdom 是一个轻量级高性能的模块化虚拟 DOM 库。其核心仅约 200 行代码,通过模块化架构实现功能扩展。Snabbdom 支持高效 DOM 更新、事件监听和 CSS 动画等特性,还提供 JSX 和服务器端渲染支持。该库以小巧灵活著称,适用于构建现代 Web 应用。

Snabbdom

A virtual DOM library with a focus on simplicity, modularity, powerful features and performance.


License: MIT Build Status npm version npm downloads Join the chat at https://gitter.im/snabbdom/snabbdom

Donate to our collective

Thanks to Browserstack for providing access to their great cross-browser testing tools.


English | 简体中文 | Hindi

Introduction

Virtual DOM is awesome. It allows us to express our application's view as a function of its state. But existing solutions were way too bloated, too slow, lacked features, had an API biased towards OOP , and/or lacked features I needed.

Snabbdom consists of an extremely simple, performant, and extensible core that is only ≈ 200 SLOC. It offers a modular architecture with rich functionality for extensions through custom modules. To keep the core simple, all non-essential functionality is delegated to modules.

You can mold Snabbdom into whatever you desire! Pick, choose, and customize the functionality you want. Alternatively you can just use the default extensions and get a virtual DOM library with high performance, small size, and all the features listed below.

Features

  • Core features
    • About 200 SLOC – you could easily read through the entire core and fully understand how it works.
    • Extendable through modules.
    • A rich set of hooks available, both per vnode and globally for modules, to hook into any part of the diff and patch process.
    • Splendid performance. Snabbdom is among the fastest virtual DOM libraries.
    • Patch function with a function signature equivalent to a reduce/scan function. Allows for easier integration with a FRP library.
  • Features in modules
  • Third party features

Example

import {
  init,
  classModule,
  propsModule,
  styleModule,
  eventListenersModule,
  h
} from "snabbdom";

const patch = init([
  // Init patch function with chosen modules
  classModule, // makes it easy to toggle classes
  propsModule, // for setting properties on DOM elements
  styleModule, // handles styling on elements with support for animations
  eventListenersModule // attaches event listeners
]);

const container = document.getElementById("container");

const vnode = h(
  "div#container.two.classes",
  { on: { click: () => console.log("div clicked") } },
  [
    h("span", { style: { fontWeight: "bold" } }, "This is bold"),
    " and this is just normal text",
    h("a", { props: { href: "/foo" } }, "I'll take you places!")
  ]
);
// Patch into empty DOM element – this modifies the DOM as a side effect
patch(container, vnode);

const newVnode = h(
  "div#container.two.classes",
  { on: { click: () => console.log("updated div clicked") } },
  [
    h(
      "span",
      { style: { fontWeight: "normal", fontStyle: "italic" } },
      "This is now italic type"
    ),
    " and this is still just normal text",
    h("a", { props: { href: "/bar" } }, "I'll take you places!")
  ]
);
// Second `patch` invocation
patch(vnode, newVnode); // Snabbdom efficiently updates the old view to the new state

More examples


Table of contents

Core documentation

The core of Snabbdom provides only the most essential functionality. It is designed to be as simple as possible while still being fast and extendable.

init

The core exposes only one single function init. This init takes a list of modules and returns a patch function that uses the specified set of modules.

import { classModule, styleModule } from "snabbdom";

const patch = init([classModule, styleModule]);

patch

The patch function returned by init takes two arguments. The first is a DOM element or a vnode representing the current view. The second is a vnode representing the new, updated view.

If a DOM element with a parent is passed, newVnode will be turned into a DOM node, and the passed element will be replaced by the created DOM node. If an old vnode is passed, Snabbdom will efficiently modify it to match the description in the new vnode.

Any old vnode passed must be the resulting vnode from a previous call to patch. This is necessary since Snabbdom stores information in the vnode. This makes it possible to implement a simpler and more performant architecture. This also avoids the creation of a new old vnode tree.

patch(oldVnode, newVnode);

Unmounting

While there is no API specifically for removing a VNode tree from its mount point element, one way of almost achieving this is providing a comment VNode as the second argument to patch, such as:

patch(
  oldVnode,
  h("!", {
    hooks: {
      post: () => {
        /* patch complete */
      }
    }
  })
);

Of course, then there is still a single comment node at the mount point.

h

It is recommended that you use h to create vnodes. It accepts a tag/selector as a string, an optional data object, and an optional string or an array of children.

import { h } from "snabbdom";

const vnode = h("div#container", { style: { color: "#000" } }, [
  h("h1.primary-title", "Headline"),
  h("p", "A paragraph")
]);

fragment (experimental)

Caution: This feature is currently experimental and must be opted in. Its API may be changed without an major version bump.

const patch = init(modules, undefined, {
  experimental: {
    fragments: true
  }
});

Creates a virtual node that will be converted to a document fragment containing the given children.

import { fragment, h } from "snabbdom";

const vnode = fragment(["I am", h("span", [" a", " fragment"])]);

toVNode

Converts a DOM node into a virtual node. Especially good for patching over pre-existing, server-side generated HTML content.

import {
  init,
  styleModule,
  attributesModule,
  h,
  toVNode
} from "snabbdom";

const patch = init([
  // Initialize a `patch` function with the modules used by `toVNode`
  attributesModule // handles attributes from the DOM node
  datasetModule, // handles `data-*` attributes from the DOM node
]);

const newVNode = h("div", { style: { color: "#000" } }, [
  h("h1", "Headline"),
  h("p", "A paragraph"),
  h("img", { attrs: { src: "sunrise.png", alt: "morning sunrise" } })
]);

patch(toVNode(document.querySelector(".container")), newVNode);

Hooks

Hooks are a way to hook into the lifecycle of DOM nodes. Snabbdom offers a rich selection of hooks. Hooks are used both by modules to extend Snabbdom, and in normal code for executing arbitrary code at desired points in the life of a virtual node.

Overview

NameTriggered whenArguments to callback
prethe patch process beginsnone
inita vnode has been addedvnode
createa DOM element has been created based on a vnodeemptyVnode, vnode
insertan element has been inserted into the DOMvnode
prepatchan element is about to be patchedoldVnode, vnode
updatean element is being updatedoldVnode, vnode
postpatchan element has been patchedoldVnode, vnode
destroyan element is directly or indirectly being removedvnode
removean element is directly being removed from the DOMvnode, removeCallback
postthe patch process is donenone

The following hooks are available for modules: pre, create, update, destroy, remove, post.

The following hooks are available in the hook property of individual elements: init, create, insert, prepatch, update, postpatch, destroy, remove.

Usage

To use hooks, pass them as an object to hook field of the data object argument.

h("div.row", {
  key: movie.rank,
  hook: {
    insert: (vnode) => {
      movie.elmHeight = vnode.elm.offsetHeight;
    }
  }
});

The init hook

This hook is invoked during the patch process when a new virtual node has been found. The hook is called before Snabbdom has processed the node in any way. I.e., before it has created a DOM node based on the vnode.

The insert hook

This hook is invoked once the DOM element for a vnode has been inserted into the document and the rest of the patch cycle is done. This means that you can do DOM measurements (like using getBoundingClientRect in this hook safely, knowing that no elements will be changed afterwards that could affect the position of the inserted elements.

The remove hook

Allows you to hook into the removal of an element. The hook is called once a vnode is to be removed from the DOM. The handling function receives both the vnode and a callback. You can control and delay the removal with the callback. The callback should be invoked once the hook is done doing its business, and the element will only be removed once all remove hooks have invoked their callback.

The hook is only triggered when an element is to be removed from its parent – not if it is the child of an element that is removed. For that, see the destroy hook.

The destroy hook

This hook is invoked on a virtual node when its DOM element is removed from the DOM or if its parent is being removed from the DOM.

To see the difference between this hook and the remove hook, consider an example.

const vnode1 = h("div", [h("div", [h("span", "Hello")])]);
const vnode2 = h("div", []);
patch(container, vnode1);
patch(vnode1, vnode2);

Here destroy is triggered for both the inner div element and the span element it contains. remove, on the other hand, is only triggered on the div element because it is the only element being detached from its parent.

You can, for instance, use remove to trigger an animation when an element is being removed and use the destroy hook to additionally animate the disappearance of the removed element's children.

Creating modules

Modules work by registering global listeners for hooks. A module is simply a dictionary mapping hook names to functions.

const myModule = {
  create: (oldVnode, vnode) => {
    // invoked whenever a new virtual node is created
  },
  update: (oldVnode, vnode) => {
    // invoked whenever a virtual node is updated
  }
};

With this mechanism you can easily augment the behaviour of Snabbdom. For demonstration, take a look at the implementations of the default modules.

Modules documentation

This describes the core modules. All modules are optional. JSX examples assume you're using the jsx pragma provided by this library.

The class module

The class module provides an easy way to dynamically toggle classes on elements. It expects an object in the class data property. The object should map class names to booleans that indicate whether or not the class should stay or go on the vnode.

h("a", { class: { active: true, selected: false } }, "Toggle");

In JSX, you can use class like this:

<div class={{ foo: true, bar: true }} />
// Renders as: <div class="foo bar"></div>

The props module

Allows you to set properties on DOM elements.

h("a", { props: { href: "/foo" } }, "Go to Foo");

In JSX, you can use props like this:

<input props={{ name: "foo" }} />
// Renders as: <input name="foo" /> with input.name === "foo"

Properties can only be set. Not removed. Even though browsers allow addition and deletion of custom properties, deletion will not be attempted by this module. This makes sense, because native DOM properties cannot be removed. And if you are using custom properties for storing values or referencing objects on the DOM, then please consider using data-* attributes instead. Perhaps via the dataset module.

The attributes module

Same as props, but set attributes instead of properties on DOM elements.

h("a", { attrs:
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号