node.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import type { LexicalNode, NodeKey, SerializedLexicalNode } from 'lexical'
  2. import { DecoratorNode } from 'lexical'
  3. import ContextBlockComponent from './component'
  4. import type { Dataset } from './index'
  5. export type SerializedNode = SerializedLexicalNode & { datasets: Dataset[]; onAddContext: () => void }
  6. export class ContextBlockNode extends DecoratorNode<JSX.Element> {
  7. __datasets: Dataset[]
  8. __onAddContext: () => void
  9. static getType(): string {
  10. return 'context-block'
  11. }
  12. static clone(node: ContextBlockNode): ContextBlockNode {
  13. return new ContextBlockNode(node.__datasets, node.__onAddContext)
  14. }
  15. isInline(): boolean {
  16. return true
  17. }
  18. constructor(datasets: Dataset[], onAddContext: () => void, key?: NodeKey) {
  19. super(key)
  20. this.__datasets = datasets
  21. this.__onAddContext = onAddContext
  22. }
  23. createDOM(): HTMLElement {
  24. const div = document.createElement('div')
  25. div.classList.add('inline-flex', 'items-center', 'align-middle')
  26. return div
  27. }
  28. updateDOM(): false {
  29. return false
  30. }
  31. decorate(): JSX.Element {
  32. return (
  33. <ContextBlockComponent
  34. nodeKey={this.getKey()}
  35. datasets={this.getDatasets()}
  36. onAddContext={this.getOnAddContext()}
  37. />
  38. )
  39. }
  40. getDatasets(): Dataset[] {
  41. const self = this.getLatest()
  42. return self.__datasets
  43. }
  44. getOnAddContext(): () => void {
  45. const self = this.getLatest()
  46. return self.__onAddContext
  47. }
  48. static importJSON(serializedNode: SerializedNode): ContextBlockNode {
  49. const node = $createContextBlockNode(serializedNode.datasets, serializedNode.onAddContext)
  50. return node
  51. }
  52. exportJSON(): SerializedNode {
  53. return {
  54. type: 'context-block',
  55. version: 1,
  56. datasets: this.getDatasets(),
  57. onAddContext: this.getOnAddContext(),
  58. }
  59. }
  60. getTextContent(): string {
  61. return '{{#context#}}'
  62. }
  63. }
  64. export function $createContextBlockNode(datasets: Dataset[], onAddContext: () => void): ContextBlockNode {
  65. return new ContextBlockNode(datasets, onAddContext)
  66. }
  67. export function $isContextBlockNode(
  68. node: ContextBlockNode | LexicalNode | null | undefined,
  69. ): boolean {
  70. return node instanceof ContextBlockNode
  71. }