Skip to content

Commit

Permalink
WIP: Remote Partial Component
Browse files Browse the repository at this point in the history
Try to extract the logic to render the content of the dialog and the error handing into a separate component.
  • Loading branch information
sascha-karnatz committed Jun 27, 2024
1 parent e3fcc6b commit 98eb7aa
Show file tree
Hide file tree
Showing 6 changed files with 157 additions and 37 deletions.
1 change: 1 addition & 0 deletions app/javascript/alchemy_admin/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import "alchemy_admin/components/uploader"
import "alchemy_admin/components/overlay"
import "alchemy_admin/components/page_select"
import "alchemy_admin/components/preview_window"
import "alchemy_admin/components/remote_partial"
import "alchemy_admin/components/select"
import "alchemy_admin/components/spinner"
import "alchemy_admin/components/tags_autocomplete"
Expand Down
91 changes: 91 additions & 0 deletions app/javascript/alchemy_admin/components/remote_partial.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { translate } from "alchemy_admin/i18n"

/**
* the remote partial will automatically load the content of the given url and
* put the fetched content into the inner component. It also handles different
* kinds of error cases.
*/
class RemotePartial extends HTMLElement {
constructor() {
super()
this.addEventListener("ajax:success", this)
this.addEventListener("ajax:error", this)
}

/**
* handle the ajax event from inner forms
* this is an intermediate solution until we moved away from jQuery
* @param {CustomEvent} event
* @deprecated
*/
handleEvent(event) {
const status = event.detail[1]
/** @type {XMLHttpRequest} xhr */
const xhr = event.detail[2]

switch (event.type) {
case "ajax:success":
const isTextResponse = xhr
.getResponseHeader("Content-Type")
.match(/html/)

if (isTextResponse) {
this.innerHTML = xhr.responseText
}
break
case "ajax:error":
this.#showErrorMessage(status, xhr.responseText, "error")
break
}
}

/**
* show the spinner and load the content
* after the content is loaded the spinner will be replaced by the fetched content
*/
connectedCallback() {
this.innerHTML = `<alchemy-spinner size="medium"></alchemy-spinner>`

fetch(this.url, {
redirect: "error",
headers: { "X-Requested-With": "XMLHttpRequest" }
})
.then(async (response) => {
if (response.ok) {
this.innerHTML = await response.text()
} else {
this.#showErrorMessage(
response.statusText,
await response.text(),
"error"
)
}
})
.catch(() => {
this.#showErrorMessage(
translate("The server does not respond."),
translate("Please check server and try again.")
)
})
}

/**
* @param {string} title
* @param {string} description
* @param {"warning"|"error"} type
*/
#showErrorMessage(title, description, type = "warning") {
this.innerHTML = `
<alchemy-message type="${type}">
<h1>${title}</h1>
<p>${description}</p>
</alchemy-message>
`
}

get url() {
return this.getAttribute("url")
}
}

customElements.define("alchemy-remote-partial", RemotePartial)
51 changes: 15 additions & 36 deletions app/javascript/alchemy_admin/dialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,20 @@ export class Dialog {
*/
open() {
this.#build()
// Show the dialog with the spinner after a small delay.
// in most cases the content of the dialog is already available and the spinner is not flashing
setTimeout(() => this.#openDialog, 300)
this.#openDialog()
this.#select2Handling()

this.#loadContent().then((content) => {
// create the dialog markup and show the dialog
this.#dialogComponent.innerHTML = content
this.#select2Handling()
this.#openDialog()
// bind the current class instance to the DOM - element
// this should be an intermediate solution
// the main goal, is to close the dialog with the turbo:submit-end - event
this.#dialogComponent.dialogClassInstance = this

// bind the current class instance to the DOM - element
// this should be an intermediate solution
// the main goal, is to close the dialog with the turbo:submit-end - event
this.#dialogComponent.dialogClassInstance = this

// the dialog is closing with the overlay, esc - key, or close - button
// the reject - callback will be fired, because the user decided to close the
// dialog without saving anything
this.#dialogComponent.addEventListener("sl-request-close", () => {
this.#removeDialog()
this.#onReject()
})
// the dialog is closing with the overlay, esc - key, or close - button
// the reject - callback will be fired, because the user decided to close the
// dialog without saving anything
this.#dialogComponent.addEventListener("sl-after-hide", () => {
this.#removeDialog()
this.#onReject()
})

return new Promise((resolve, reject) => {
Expand All @@ -69,24 +61,13 @@ export class Dialog {
})
}

/**
* load content of the given url
* @returns {Promise<string>}
*/
async #loadContent() {
const response = await fetch(this.url, {
headers: { "X-Requested-With": "XMLHttpRequest" }
})
return await response.text()
}

/**
* create and append the dialog container to the DOM
*/
#build() {
this.#dialogComponent = createHtmlElement(`
<sl-dialog label="${this.title}" style="${this.styles}">
<alchemy-spinner size="medium"></alchemy-spinner>
<alchemy-remote-partial url="${this.url}"></alchemy-remote-partial>
</sl-dialog>
`)
document.body.append(this.#dialogComponent)
Expand All @@ -107,10 +88,8 @@ export class Dialog {
* remove the dialog from dom
*/
#removeDialog() {
this.#dialogComponent.addEventListener("sl-after-hide", () => {
this.#dialogComponent.remove()
this.#isOpen = false
})
this.#dialogComponent.remove()
this.#isOpen = false
}

/**
Expand Down
3 changes: 3 additions & 0 deletions app/javascript/alchemy_admin/locales/en.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export const en = {
"No anchors found": "No anchors found",
"Select a page first": "Select a page first",
Close: "Close",
"The server does not respond.": "The server does not respond.",
"Please check server and try again.": "Please check server and try again.",
"Please check log and try again.": "Please check log and try again.",
formats: {
datetime: "Y-m-d H:i",
date: "Y-m-d",
Expand Down
2 changes: 1 addition & 1 deletion spec/features/admin/page_editing_feature_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@
let!(:new_parent) { create(:alchemy_page) }

it "can change page parent" do
within(".simple_form:first-child") do
within(".simple_form.edit_page") do
expect(page).to have_css("#s2id_page_parent_id")
select2_search(new_parent.name, from: "Parent")
find(".edit_page .submit button").click
Expand Down
46 changes: 46 additions & 0 deletions spec/javascript/alchemy_admin/components/remote_partial.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import "alchemy_admin/components/remote_partial"

describe("alchemy-remote-partial", () => {
global.fetch = jest.fn(() =>
Promise.resolve({
text: () => Promise.resolve("Foo")
})
)

/**
* @type {RemotePartial | undefined}
*/
let partial = undefined

const renderComponent = (url = null) => {
document.body.innerHTML = `<alchemy-remote-partial url="${url}"></alchemy-remote-partial>`
partial = document.querySelector("alchemy-remote-partial")
return new Promise((resolve) => {
setTimeout(() => resolve())
})
}

it("should render a spinner as initial content", () => {
renderComponent()
expect(document.querySelector("alchemy-spinner")).toBeTruthy()
})

it("should fetch the given url", () => {
renderComponent("http://foo.bar")
expect(fetch).toHaveBeenCalledWith("http://foo.bar", {
headers: { "X-Requested-With": "XMLHttpRequest" }
})
})

it("should replace the spinner with the fetched content", async () => {
await renderComponent()
expect(partial.innerHTML).toBe("Foo")
})

it("should render an error message", async () => {
fetch.mockImplementationOnce(() => Promise.reject("API is down"))

await renderComponent()
expect(partial.innerHTML).toBe("1231231223112312123132312")
})
})

0 comments on commit 98eb7aa

Please sign in to comment.