diff --git a/docs/src/_documentation/how_tos/using-shoelace-with-mrujs.md b/docs/src/_documentation/how_tos/using-shoelace-with-mrujs.md new file mode 100644 index 00000000..e74cfd23 --- /dev/null +++ b/docs/src/_documentation/how_tos/using-shoelace-with-mrujs.md @@ -0,0 +1,52 @@ +--- +title: Using Shoelace with Mrujs +doc_order: 70 +--- + +Mrujs ships with a Shoelace plugin. Currently this plugin is fairly minimal. At its +core, the plugin listens for all Shoelace submit events, will grab the Shoelace form, +check for a `action` and `method` on the Shoelace form. (These are currently non-standard +attributes on Shoelace forms) + +it will then submit this form via AJAX and go through the normal `ajax:` lifecycle within +mrujs. + +Example: + +```html + + +``` + +

+ + Usage + +

+ +```js +import mrujs from "mrujs" +import { Shoelace } from "mrujs/plugins" + +mrujs.start({ + plugins: [ + Shoelace() + ] +}) +``` + +## Usage with Rails view helpers + +Currently there is a PR sitting for changing the wrapper_tag of +`form_with`. + +In the meantime, here are some ViewHelpers created by @yuki to help use +Shoelace with Rails form helpers: + + + +Shoelace-Rails also has a frontend package which clobbers +a lot of mrujs behavior and is not recommended, but the ViewHelpers should work fine. + +If you would prefer to not use the ViewHelpers, thats fine too. They +aren't required to use Shoelace with Rails. diff --git a/plugins/src/shoelace.ts b/plugins/src/shoelace.ts new file mode 100644 index 00000000..3b130c93 --- /dev/null +++ b/plugins/src/shoelace.ts @@ -0,0 +1,39 @@ +import { MrujsPluginInterface } from '../../types' + +export function Shoelace (): MrujsPluginInterface { + return { + name: 'Shoelace', + initialize, + disconnect + } +} + +function initialize (): void { + document.addEventListener('sl-submit', shoelaceFormListener as EventListener) +} + +function disconnect (): void { + document.removeEventListener('sl-submit', shoelaceFormListener as EventListener) +} + +async function shoelaceFormListener (event: CustomEvent): Promise { + const form = event.currentTarget as HTMLFormElement + const formData = event.detail.formData + + const action = form.getAttribute('action') + let method = form.getAttribute('method') + + if (action == null) { + console.warn("No 'action' attribute on your Shoelace form. Aborting...") + return + } + + if (method == null) method = 'get' + + return await window.mrujs.fetch(action, { + element: form, + dispatchEvents: true, + method: method, + body: window.mrujs.urlEncodeFormData(formData) + }) +}