lib/svelte_on_rails/turbo_stream.rb



module SvelteOnRails
  class TurboStream
    def dispatch_event(event: 'stream-action', event_detail: nil, selector: nil, component: nil, channel: nil)

      if event != 'stream-action' && !selector
        raise "Another event name than the default one is only possible together with a selector"
      end

      args = {
        eventDetail: event_detail,
        component: component,
        event: event,
        selector: selector
      }

      args_enc = Base64.strict_encode64(args.to_json)

      Turbo::StreamsChannel.send(
        "broadcast_append_to",
        channel || configs['channel'],
        target: configs['target_html_id'],
        content: "<div style=\"display: none;\" data-controller=\"svelte-on-rails-turbo-stream\" data-args=\"#{args_enc}\"></div>"
      )

    end

    private

    def configs
      @configs ||= begin

                     conf = SvelteOnRails::Configuration.instance
                     unless conf.configs[:turbo_stream]
                       raise '[svelte-on-rails] missing configuration: :turbo_stream'
                     end
                     unless conf.configs[:turbo_stream]['target_html_id']
                       raise '[svelte-on-rails] missing configuration: turbo_stream/target_html_id'
                     end
                     unless conf.configs[:turbo_stream]['channel']
                       raise '[svelte-on-rails] missing configuration: turbo_stream/channel'
                     end

                     conf.configs[:turbo_stream]
                   end
    end
  end
end