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 fc9ba6c
Show file tree
Hide file tree
Showing 6 changed files with 249 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
98 changes: 98 additions & 0 deletions app/javascript/alchemy_admin/components/remote_partial.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
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) {
/** @type {String} status */
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, {
headers: { "X-Requested-With": "XMLHttpRequest" }
})
.then(async (response) => {
if (response.ok) {
if (response.redirected) {
this.#showErrorMessage(
translate("You are not authorized!"),
translate("Please close this window.")
)
} else {
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
5 changes: 5 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,11 @@ 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.",
"You are not authorized!": "You are not authorized!",
"Please close this window.": "Please close this window.",
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
129 changes: 129 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,129 @@
import "alchemy_admin/components/remote_partial"

describe("alchemy-remote-partial", () => {
/**
* @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())
})
}

/**
* @param {{
* ok: boolean|undefined,
* redirected: boolean|undefined,
* statusText: string|undefined,
* text: function|undefined
* }} response
*/
const mockFetch = (response = {}) => {
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
redirected: false,
statusText: "",
text: () => Promise.resolve("Foo"),
...response
})
)
}

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

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

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

describe("server errors", () => {
it("doesn't respond", async () => {
mockFetch()
fetch.mockImplementationOnce(() => Promise.reject())

await renderComponent()
expect(partial.innerHTML).toContain("The server does not respond")
})

it("response with an error if the server response with an error", async () => {
mockFetch({ ok: false, statusText: "Ruby Error" })

await renderComponent()
expect(partial.innerHTML).toContain("Ruby Error")
})

it("response with an redirect", async () => {
mockFetch({ redirected: true })

await renderComponent()
expect(partial.innerHTML).toContain("You are not authorized!")
})
})
})

describe("jQuery Remote Call", () => {
const dispatchCustomEvent = (
eventName = "ajax:success",
responseText = "Bar",
contentType = "text/html"
) => {
const event = new CustomEvent(eventName, {
bubbles: true,
detail: [
{},
eventName === "ajax:success" ? "OK" : "Error",
{
responseText,
getResponseHeader: jest.fn().mockReturnValue(contentType)
}
]
})
partial.dispatchEvent(event)
}

beforeEach(async () => {
mockFetch()
await renderComponent()
})

describe("ajax:success - event", () => {
it("should replace the partial content with html response", () => {
dispatchCustomEvent()
expect(partial.innerHTML).toContain("Bar")
})

it("should not replace the partial content with json response", () => {
dispatchCustomEvent("ajax:success", "Bar", "application/json")
expect(partial.innerHTML).toContain("Foo")
})
})

describe("ajax:error - event", () => {
it("should replace the partial content with html response", () => {
dispatchCustomEvent("ajax:error", "Very Broken")
expect(partial.innerHTML).toContain("Very Broken")
})
})
})
})

0 comments on commit fc9ba6c

Please sign in to comment.