Delta被用做描述Quill编辑器的内容和变化,简单但表达力强的数据格式。这种格式本质上是一种JSON格式,人类可读同时及其也能容易识别。Delta能描述任意Quill内容,包括所有的文本、格式信息,并且没有HTML多义性及复杂性的缺点。
不要被他的名称delta迷惑,Deltas(Δ增量)代表文档和文档的改变。如果将Deltas看做是一个文档到另一个文档的操作指令,那么Delta表示一个文档就是从空文档开始到现有文档的操作指令的表达。
Delta被独立成一个单独的库,以便其能在Quill以外的地方使用。它非常适合Operational Transform,可以用于实时的,类似Google Docs的应用。想要更深入的了解Delta,请查看设计Delta格式.
注意:不推荐手动构建Delta格式,推荐用链式操作insert(), delete(), and retain() 新建Delta对象。
Delta格式几乎是完全独立解析。下面这个示例中,描述了字符串"Gandalf the Grey",其中"Gandalf“是加粗的,”Grey"的颜色是 #cccccc。
{ ops: [ { insert: 'Gandalf', attributes: { bold: true } }, { insert: ' the ' }, { insert: 'Grey', attributes: { color: '#cccccc' } } ] }正如它名称所暗示的,对于Delta,描述内容实际上是一种特别的情况。上面的示例中更具体的说明了:插入加粗字符"Gandalf"、没有格式的 " the “,接下来插入带有颜色#cccccc的字符串”Grey"。当使用Delta来描述内容时,可以将其看作是delta执行于空文档所创建的内容。
因为Delta是一种数据格式,所以它没有在内部定义attribute的键-值对。例如,Delta格式中没有规定颜色值必须是十六进制的。这是Quill做出的取舍,如果需要,可以用Parchment修改。
对于非文本内容,如图像、公式,插入的值是对象。这个对象应该来确定其类型的键(key)。如果你是用Parchment自定义内容的话,这个键是blotName。和文本一样,嵌入对象仍需要 attributes来描述作用与这个嵌入对象上的格式。所有嵌入对象的长度都为1。
{ ops: [{ // An image link insert: { image: 'https://quilljs.com/assets/images/icon.png' }, attributes: { link: 'https://quilljs.com' } }] }带有换行符的内容对应属性是描述一行的格式。
{ ops: [ { insert: 'The Two Towers' }, { insert: '\n', attributes: { header: 1 } }, { insert: 'Aragorn sped on up the hill.\n' } ] }所有的Quill文档须以换行符结尾,甚至在最后一行上没有格式设置。这样你始终有一个字符的位置来表示应用行格式。
很多行格式是独占的,例如,Quill不允许同一行同时作为标题和列表,尽管他们可以用Delta格式来表示。
当你监听 Quill的 text-change事件时,你会得到一个描述哪些内容改变了的参数。除了 insert操作以外,Delta可以还有delete 或 retain操作。
删除操作必然明确指示:接下来删除的字符数。
{ ops: [ { delete: 10 } // Delete the next 10 characters ] }Delta的删除操作是不可逆的,因为delete 操作没有包含被删除的内容。
retain 操作只表示不做修改的保留接下来指定数量的字符串。如果带有attributes值,则表示只保留这些字符串但要应用被attributes定义的格式。如果attributes定义的格式值为null表示移除文本原来的格式。
从上面提到的 “Gandalf the Grey” 示例开始:
// { // ops: [ // { insert: 'Gandalf', attributes: { bold: true } }, // { insert: ' the ' }, // { insert: 'Grey', attributes: { color: '#cccccc' } } // ] // } { ops: [ // Unbold and italicize "Gandalf" { retain: 7, attributes: { bold: null, italic: true } }, // Keep " the " as is { retain: 5 }, // Insert "White" formatted with color #fff { insert: "White", attributes: { color: '#fff' } }, // Delete "Grey" { delete: 4 } ] }注意,Delta的指令总是从文档开头开始。因为有简单的retain ,所以我们不需要再为delete 或 insert 操作定义一个index值。