1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-21 22:45:18 +02:00

feature(slate): Add isElementType utility function to Element Interface (#4349)

This commit is contained in:
I Made Budi Surya Darma
2021-08-09 22:55:45 +08:00
committed by GitHub
parent 706f2fc072
commit 236754c4d2
6 changed files with 72 additions and 8 deletions

View File

@@ -0,0 +1,5 @@
---
'slate': patch
---
Add isElementType utility to Element interface

View File

@@ -18,9 +18,25 @@ export interface ElementInterface {
isElement: (value: any) => value is Element
isElementList: (value: any) => value is Element[]
isElementProps: (props: any) => props is Partial<Element>
isElementType: <T extends Element>(
value: any,
elementVal: string,
elementKey?: string
) => value is T
matches: (element: Element, props: Partial<Element>) => boolean
}
/**
* Shared the function with isElementType utility
*/
const isElement = (value: any): value is Element => {
return (
isPlainObject(value) &&
Node.isNodeList(value.children) &&
!Editor.isEditor(value)
)
}
export const Element: ElementInterface = {
/**
* Check if a value implements the 'Ancestor' interface.
@@ -34,14 +50,7 @@ export const Element: ElementInterface = {
* Check if a value implements the `Element` interface.
*/
isElement(value: any): value is Element {
return (
isPlainObject(value) &&
Node.isNodeList(value.children) &&
!Editor.isEditor(value)
)
},
isElement,
/**
* Check if a value is an array of `Element` objects.
*/
@@ -58,6 +67,19 @@ export const Element: ElementInterface = {
return (props as Partial<Element>).children !== undefined
},
/**
* Check if a value implements the `Element` interface and has elementKey with selected value.
* Default it check to `type` key value
*/
isElementType: <T extends Element>(
value: any,
elementVal: string,
elementKey: string = 'type'
): value is T => {
return isElement(value) && value[elementKey] === elementVal
},
/**
* Check if an element matches set of properties.
*

View File

@@ -0,0 +1,10 @@
import { Element } from 'slate'
export const input = {
source: 'heading-large',
children: [{ text: '' }],
}
export const test = value =>
Element.isElementType(value, 'heading-large', 'source')
export const output = true

View File

@@ -0,0 +1,9 @@
import { Element } from 'slate'
export const input = {
type: 'heading-large',
children: [{ text: '' }],
}
export const test = value => Element.isElementType(value, 'paragraph', 'source')
export const output = false

View File

@@ -0,0 +1,9 @@
import { Element } from 'slate'
export const input = {
type: 'paragraph',
children: [{ text: '' }],
}
export const test = value => Element.isElementType(value, 'paragraph')
export const output = true

View File

@@ -0,0 +1,9 @@
import { Element } from 'slate'
export const input = {
type: 'heading-large',
children: [{ text: '' }],
}
export const test = value => Element.isElementType(value, 'paragraph')
export const output = false