richeditor.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package richeditor
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/qor5/admin/media/media_library"
  6. media_view "github.com/qor5/admin/media/views"
  7. "github.com/qor5/ui/redactor"
  8. v "github.com/qor5/ui/vuetify"
  9. "github.com/qor5/web"
  10. h "github.com/theplant/htmlgo"
  11. "gorm.io/gorm"
  12. )
  13. // how to add more plugins from https://imperavi.com/redactor/plugins/
  14. // 1. add {{plugin}}.min.js to redactor dir
  15. // 2. add plugin name in Plugins array
  16. // how to add own plugins
  17. // 1. load plugin jss,css to PluginsJS,PluginsCSS
  18. // 2. add plugin names in Plugins array
  19. var Plugins = []string{"alignment", "table", "video", "imageinsert"}
  20. var PluginsJS [][]byte
  21. var PluginsCSS [][]byte
  22. type RichEditorBuilder struct {
  23. db *gorm.DB
  24. name string
  25. value string
  26. label string
  27. placeholder string
  28. plugins []string
  29. setPlugins bool
  30. rawConfig interface{}
  31. }
  32. func RichEditor(db *gorm.DB, name string) (r *RichEditorBuilder) {
  33. r = &RichEditorBuilder{db: db, name: name}
  34. return
  35. }
  36. func (b *RichEditorBuilder) Value(v string) (r *RichEditorBuilder) {
  37. b.value = v
  38. return b
  39. }
  40. func (b *RichEditorBuilder) Label(v string) (r *RichEditorBuilder) {
  41. b.label = v
  42. return b
  43. }
  44. func (b *RichEditorBuilder) Placeholder(v string) (r *RichEditorBuilder) {
  45. b.placeholder = v
  46. return b
  47. }
  48. func (b *RichEditorBuilder) Plugins(v []string) (r *RichEditorBuilder) {
  49. b.plugins = v
  50. b.setPlugins = true
  51. return b
  52. }
  53. // Note: RawConfig overwrites Plugins
  54. func (b *RichEditorBuilder) RawConfig(v interface{}) (r *RichEditorBuilder) {
  55. b.rawConfig = v
  56. return b
  57. }
  58. func (b *RichEditorBuilder) MarshalHTML(ctx context.Context) ([]byte, error) {
  59. p := Plugins
  60. if b.setPlugins {
  61. p = b.plugins
  62. }
  63. redactorB := redactor.New().Value(b.value).Placeholder(b.placeholder).Attr(web.VFieldName(b.name)...)
  64. if b.rawConfig != nil {
  65. redactorB.RawConfig(b.rawConfig)
  66. } else {
  67. redactorB.Config(redactor.Config{Plugins: p})
  68. }
  69. r := h.Components(
  70. v.VSheet(
  71. h.Label(b.label).Class("v-label theme--light"),
  72. redactorB,
  73. h.Div(
  74. media_view.QMediaBox(b.db).FieldName(fmt.Sprintf("%s_richeditor_medialibrary", b.name)).
  75. Value(&media_library.MediaBox{}).Config(&media_library.MediaBoxConfig{
  76. AllowType: "image",
  77. }),
  78. ).Class("hidden-screen-only"),
  79. ).Class("pb-4").Rounded(true).Attr("data-type", "redactor").Attr("style", "position: relative; z-index:1;"),
  80. )
  81. return r.MarshalHTML(ctx)
  82. }