loop-index

loop-index

I am trying to integrate a TipTap editor into my edit FormComponent. Right now I have a separate LiveView component for the editor:

@impl true
  def render(%{value: %Phoenix.HTML.FormField{} = field} = assigns) do
    errors = if Phoenix.Component.used_input?(field), do: field.errors, else: []

    assigns
    |> assign(:errors, Enum.map(errors, &translate_error(&1)))

    ~H"""
    <div phx-hook="TextEditor" class="tiptap-editor" id={"editor-#{@name}"} phx-update="ignore" data-class={@class} data-value={@value.value}>
      <div data-editor={@name}></div>
      <.input type="text" name={@name} field={@value} data-editor-hidden={@name} phx-change="validate" />
      <.error :for={msg <- @errors}><%= msg %></.error>
    </div>
    """
  end

Called from the FormComponent:

<.simple_form
        for={@form}
        id="project-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:title]} type="text" label="Title" />
        <.live_component
          module={FeedWeb.ProjectLive.EditorComponent}
          id="tiptap-editor"
          name="body"
          class="w-full p-2 mt-2 border rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6 border-zinc-300 focus:border-zinc-400"
          value={@form[:body]}
        />
        <%!-- <.input field={@form[:body]} type="textarea" rows="12" label="Body" /> --%>
        <:actions>
          <.button phx-disable-with="Saving..." class="px-2 py-1 text-white bg-blue-500 rounded-md">
            Save Project
          </.button>
        </:actions>
      </.simple_form>

And on app.js, some code to hydrate the editor:

const TextEditor = {
    editor: null,
    content: null,
    buttonSetup: {
        bold: { run: (editor) => editor.chain().focus().toggleBold().run(), check: (editor) => editor.isActive("bold") },
        italic: { run: (editor) => editor.chain().focus().toggleItalic().run(), check: (editor) => editor.isActive("italic") },
        h1: {
            run: (editor) => editor.chain().focus().toggleHeading({ level: 1 }).run(),
            check: (editor) => editor.isActive("heading", { level: 1 }),
        },
    },

    initialValue() {
        return this.el.dataset.value || "";
    },
    classes() {
        return this.el.dataset.class || "";
    },
    mounted() {
        const element = this.el.querySelector("[data-editor]");
        const hidden = this.el.querySelector("[data-editor-hidden]");
        const controlButtons = this.el.closest("form").querySelectorAll("[data-editor-control]");

        controlButtons.forEach((btn) => {
            btn.addEventListener("click", (e) => {
                const config = this.buttonSetup[e.target.dataset.editorControl];
                if (config && typeof config.run === "function") {
                    config.run(this.editor);
                }
            });
        });

        this.editor = new Editor({
            element,
            extensions: [
                StarterKit,
                Typography,
                Table.configure({
                    resizable: false,
                }),
                TableCell,
                TableHeader,
                TableRow,
            ],
            onUpdate: ({ editor }) => {
                this.content = editor.getHTML();
                hidden.value = this.content;
                // this.pushEventTo(this.el, "change", { value: this.content });
                // console.log("content", this.content);
            },
            content: this.initialValue(),
            editorProps: {
                attributes: {
                    class: this.classes()
                }
            },
            onTransaction: ({ editor }) => {
                controlButtons.forEach((btn) => {
                    const config = this.buttonSetup[btn.dataset.editorControl];
                    if (config && typeof config.check === "function") {
                        if (config.check(this.editor)) {
                            btn.classList.add("editor-active");
                        } else {
                            btn.classList.remove("editor-active");
                        }
                    }
                });
            },
        });
    },
};

(this would be put into the hooks param)

The problem is when I hit save, whatever typed into the editor is not saved. I’m guessing since I’m wrapping the entire editor component in phx-update=“ignore” the value of the hidden input is not being synced to the server and hence not submitted to the form. I have tried to use pushEventTo on editor change, but somehow that unfocuses the editor on every keystroke.

I’d appreciate it if someone can explain for me how this works and how I should fix it! Would really love to understand how this should work.

Showing Posts 1 to 2

codeanpeace

codeanpeace

Welcome to elixirforum!

Take a look at this example of a WYIWYG JS editor populating a hidden input form field via a LiveView client side hook:

loop-index

loop-index OP

Thank you for responding! I have looked at that thread before, but the setup for TipTap seems more complex than Trix so I wasn’t able to figure out anything new from there.

I was able to solve my problem by just putting the editor and the hidden input in the top level form component instead of extracting it to a separate component. I guess maybe passing a form field down into a child component doesn’t track the changes too well.

<.simple_form
        for={@form}
        id="project-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:title]} type="text" label="Title" />

         <%!-- TipTap editor --%>
        <div
          phx-hook="TextEditor"
          id="editor-wrapper"
          data-value={@form[:body].value}
          data-class="w-full p-2 mt-2 border rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6 border-zinc-300 focus:border-zinc-400"
        >
          <div data-editor="body" id="editor-component" phx-update="ignore"></div>
          <.input type="hidden" field={@form[:body]} data-editor-hidden="body" />
        </div>
        <:actions>
          <.button phx-disable-with="Saving..." class="px-2 py-1 text-white bg-blue-500 rounded-md">
            Save Project
          </.button>
        </:actions>
      </.simple_form>

This works fine now, I’d love to extract it out into a reuseable component but this will work for now.

My TipTap integration was based on this guide if anybody wants to do the same:

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews