Module: SMEditor::Rails::FormHelper

Defined in:
lib/smeditor/rails/form_helper.rb

Overview

View helper that mounts a self-contained SMEditor inside a Rails form. The gem ships the browser bundle and default theme itself; host apps do not need npm, React, esbuild, importmap pins, or jsbundling-rails.

Instance Method Summary collapse

Instance Method Details

#smeditor_assets ⇒ Object

Render the packaged JS/CSS once for this view context. This makes the form helper work without editing the host layout. Apps that prefer to include assets in can call smeditor_assets there and disable auto inclusion with config.auto_include_assets = false.



13
14
15
16
17
18
19
20
21
# File 'lib/smeditor/rails/form_helper.rb', line 13

def smeditor_assets
  return "".html_safe if defined?(@_smeditor_assets_rendered) && @_smeditor_assets_rendered

  @_smeditor_assets_rendered = true
  safe_join([
    stylesheet_link_tag("smeditor", "data-turbo-track": "reload"),
    javascript_include_tag("smeditor", defer: true, "data-turbo-track": "reload"),
  ])
end

#smeditor_editor(form, method, options = {}) ⇒ Object

form - a Rails FormBuilder method - the model attribute (stored as an HTML string) options - :kit ("starter" | "full"), :class, :placeholder, :upload_url, :label, :include_assets



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/smeditor/rails/form_helper.rb', line 27

def smeditor_editor(form, method, options = {})
  object = form.object
  current = object.respond_to?(method) ? object.public_send(method) : nil
  kit = (options[:kit] || SMEditor.config.default_kit).to_s
  upload_url = options.fetch(:upload_url, smeditor_upload_url)
  include_assets = options.fetch(:include_assets, SMEditor.config.auto_include_assets)
  stylesheet_url = asset_path("smeditor.css")

  hidden = form.hidden_field(
    method,
    value: current.to_s,
    data: { smeditor_input: true },
  )

  mount = (
    :div,
    "",
    class: "smeditor-mount",
    data: {
      smeditor: true,
      smeditor_kit: kit,
      smeditor_placeholder: options[:placeholder],
      smeditor_upload_url: upload_url,
      smeditor_label: options[:label],
      smeditor_stylesheet: stylesheet_url,
    }.compact,
  )

  wrapper_class = ["smeditor-field", options[:class]].compact.join(" ")
  field = (:div, safe_join([hidden, mount]), class: wrapper_class)

  include_assets ? safe_join([smeditor_assets, field]) : field
end