项目

PHP 集成 tiptap

引言

在 Laravel、Livewire、Inertia.js、Alpine.jsTailwind CSS,甚至直接在 PHP 中,你可以使用 Tiptap。

Tiptap for PHP

我们提供了官方的 PHP 包来处理 Tiptap 内容。你可以将与 Tiptap 兼容的 JSON 转换为 HTML,反之亦然,还可以净化或修改内容。

Laravel Livewire

my-livewire-component.blade.php

<!--
  在你的 Livewire 组件中,如果你想每10秒自动保存编辑器中的内容,
  可以添加一个名为 "autosave" 的方法
-->
<x-editor
  wire:model="foo"
  wire:poll.10000ms="autosave"
></x-editor>

注意
在 Livewire v3 中,.defer 修饰符已不再可用,因为更新状态默认是延迟的。如果需要在服务器端实时更新状态,请使用 .live 修饰符。

editor.blade.php

<div
  x-data="setupEditor(
    $wire.entangle('{ { $attributes->wire('model')->value() }}').defer
  )"
  x-init="() => init($refs.editor)"
  wire:ignore
  { { $attributes->whereDoesntStartWith('wire:model') }}
>
  <div x-ref="editor"></div>
</div>

index.js

import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'

window.setupEditor = function (content) {
  let editor

  return {
    content: content,

    init(element) {
      editor = new Editor({
        element: element,
        extensions: [
          StarterKit,
        ],
        content: this.content,
        onUpdate: ({ editor }) => {
          this.content = editor.getHTML()
        }
      })

      this.$watch('content', (content) => {
        // 如果新内容与 Tiptap 的内容匹配,则跳过。
        if (content === editor.getHTML()) return

        // 否则,意味着外部力量(如 Livewire)正在修改这个 Alpine 组件的数据。
        // 此时,只需更新 Tiptap 的内容即可。有关 `setContent()` 方法的更多信息,请参阅:
        // https://www.tiptap.dev/api/commands/set-content
        editor.commands.setContent(content, false)
      })
    }
  }
}

这段代码展示了如何在 Laravel 的 Livewire 组件中集成 Tiptap 编辑器,并处理内容的更新和保存。请确保安装了相应的包并按照指示进行配置。

在本文档中