Skip to content

Commit

Permalink
Merge pull request #2439 from bitzesty/remote-submit-flash-messages
Browse files Browse the repository at this point in the history
Generic flash messages on remote forms
  • Loading branch information
Lubosky authored Jul 27, 2023
2 parents d412689 + 0b855cd commit dbc7cb9
Show file tree
Hide file tree
Showing 55 changed files with 247 additions and 95 deletions.
5 changes: 3 additions & 2 deletions app/assets/javascripts/admin/comments.js.coffee
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ready = ->
$('body').on 'submit', '.new_comment', (e) ->
$(document).on 'submit', '.new_comment', (e) ->
that = $(this)
e.preventDefault()
$.ajax
Expand Down Expand Up @@ -30,8 +30,9 @@ ready = ->
else
signatureWrapper.html("")

window.fire(that[0], 'ajax:x:success', data)

$('body').on 'submit', '.destroy-comment', (e) ->
$(document).on 'submit', '.destroy-comment', (e) ->
e.preventDefault()
$.ajax
url: $(this).attr('action')
Expand Down
13 changes: 6 additions & 7 deletions app/assets/javascripts/admin/financial_data.js.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ jQuery ->
overallBenchmarksTable = ($ "#overall-financial-benchmarks")
financialTable = ($ "#financial-table")

($ "input", form).on "change keyup keydown paste", ->
timer ||= setTimeout(saveFinancials, 500 )
$("input", form).on "change keyup keydown paste", ->
timer ||= setTimeout(saveFinancials, 500)

($ "button", form).on "click", (event) ->
do event.preventDefault
$(this).closest(".form-group").removeClass("form-edit")


updateExportsGrowth = (exports) ->
exportsGrowth = ($ 'tr.exports-growth td.value', benchmarksTable)
values = exports.map (i, td) ->
Expand Down Expand Up @@ -91,13 +90,13 @@ jQuery ->
url = form.attr('action')
formData = form.serialize()
updateBenchmarks()

jqXHR = $.ajax({
$.ajax
url: url
data: formData
type: 'POST'
dataType: 'js'
})
dataType: 'script'
success: (_data) ->
window.fire(form[0], 'ajax:x:success', null)

($ 'td.value', financialTable).each (i, td) ->
input = ($ 'input', ($ td))
Expand Down
12 changes: 8 additions & 4 deletions app/assets/javascripts/admin/form_answers.js.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -434,24 +434,28 @@ editFormAnswerAutoUpdate = ->
$(".sic-code .form-save-link").on "click", (e) ->
e.preventDefault()
e.stopPropagation()
that = $("#form_answer_sic_code")
form = $(".edit_form_answer")
input = $("#form_answer_sic_code")
form = $(e.target).closest('form')
$.ajax
action: form.attr("action")
data: form.serialize()
method: "PATCH"
dataType: "json"

success: (result) ->
formGroup = that.parents(".form-group")
formGroup = input.parents(".form-group")
formGroup.removeClass("form-edit")
formGroup.find(".form-value p").text(that.find("option:selected").text())
console.log(formGroup, input)
formGroup.find(".form-value p").text(input.val())
sicCodes = result["form_answer"]["sic_codes"]
counter = 1
for row in $(".sector-average-growth td")
$(row).text(sicCodes[counter.toString()])
counter += 1
$(".avg-growth-legend").text(result["form_answer"]["legend"])

window.fire(form[0], 'ajax:x:success', null)

bindRags =(klass) ->
$(document).on "click", "#{klass} .btn-rag .dropdown-menu a", (e) ->
e.preventDefault()
Expand Down
17 changes: 14 additions & 3 deletions app/assets/javascripts/application-admin.js.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,18 @@
#= require clean-paste

$(document).ready(() ->
$("html").removeClass("no-js").addClass("js")
($ ".timepicker").timePicker()
($ ".datepicker").datepicker({dateFormat: "dd/mm/yy"})
$('html').removeClass('no-js').addClass('js')
($ '.timepicker').timePicker()
($ '.datepicker').datepicker({dateFormat: 'dd/mm/yy'})
)

$(document).on 'ajax:success', 'form', (event, data, _status, _xhr) ->
fire(this, 'ajax:x:success', data)

$(document).on 'ajax:error', 'form', (event, data, _status, _xhr) ->
fire(this, 'ajax:x:error', data)

window.fire = (obj, name, data) ->
event = new CustomEvent(name, detail: data, bubbles: true, cancelable: true)
obj.dispatchEvent(event)
!event.defaultPrevented
7 changes: 7 additions & 0 deletions app/controllers/admin/admins_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ def create
authorize @resource, :create?

@resource.save

render_flash_message_for(@resource)

location = @resource.persisted? ? admin_admins_path : nil
respond_with :admin, @resource, location: location
end
Expand All @@ -32,13 +35,17 @@ def update
@resource.update_without_password(resource_params)
end

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_admins_path
end

def destroy
authorize @resource, :destroy?
@resource.soft_delete!

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_admins_path
end

Expand Down
7 changes: 7 additions & 0 deletions app/controllers/admin/assessors_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ def create

@resource.save
location = @resource.persisted? ? admin_assessors_path : nil

render_flash_message_for(@resource)

respond_with :admin, @resource, location: location
end

Expand All @@ -32,13 +35,17 @@ def update
@resource.update_without_password(resource_params)
end

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_assessors_path
end

def destroy
authorize @resource, :destroy?
@resource.soft_delete!

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_assessors_path
end

Expand Down
8 changes: 8 additions & 0 deletions app/controllers/admin/base_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ def current_subject
current_admin
end

def render_flash_message_for(resource, message: nil)
if resource.errors.any?
flash[:error] = message || "An unknown error has occurred, please try again."
else
flash[:notice] = message || "Success!"
end
end

private

def user_not_authorized
Expand Down
13 changes: 10 additions & 3 deletions app/controllers/admin/comments_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def create
head :ok
end
else
render_flash_message_for(@comment)
redirect_to admin_form_answer_path(form_answer)
end
end
Expand All @@ -38,7 +39,10 @@ def update
log_event if resource.update(update_params)

respond_to do |format|
format.html { redirect_to([namespace_name, form_answer]) }
format.html do
render_flash_message_for(resource)
redirect_to([namespace_name, form_answer])
end
format.js { head :ok }
end
end
Expand All @@ -49,8 +53,11 @@ def destroy
log_event if resource.destroy

respond_to do |format|
format.json{ render(json: :ok)}
format.html{ redirect_to admin_form_answer_path(form_answer)}
format.json { render(json: :ok)}
format.html do
render_flash_message_for(resource)
redirect_to(admin_form_answer_path(form_answer))
end
end
end

Expand Down
2 changes: 2 additions & 0 deletions app/controllers/admin/custom_emails_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ def create
@form = CustomEmailForm.new(custom_email_form_attributes)
if @form.valid?
CustomEmailWorker.perform_async(custom_email_form_attributes)
render_flash_message_for(@form)
redirect_to admin_custom_email_path, notice: "Email was successfully scheduled"
else
render_flash_message_for(@form)
render :show
end
end
Expand Down
7 changes: 7 additions & 0 deletions app/controllers/admin/judges_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ def create

@resource.save
location = @resource.persisted? ? admin_judges_path : nil

render_flash_message_for(@resource)

respond_with :admin, @resource, location: location
end

Expand All @@ -32,13 +35,17 @@ def update
@resource.update_without_password(resource_params)
end

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_judges_path
end

def destroy
authorize @resource, :destroy?
@resource.soft_delete!

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_judges_path
end

Expand Down
5 changes: 5 additions & 0 deletions app/controllers/admin/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ def create

@resource.save
location = @resource.persisted? ? admin_users_path : nil

render_flash_message_for(@resource)

respond_with :admin, @resource, location: location
end

Expand All @@ -39,6 +42,8 @@ def update
@resource.update_without_password(resource_params)
end

render_flash_message_for(@resource)

respond_with :admin, @resource, location: admin_users_path
end

Expand Down
5 changes: 4 additions & 1 deletion app/controllers/concerns/admin_shortlisted_docs_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def create

respond_to do |format|
format.html do
render_flash_message_for(attachment)
redirect_to [namespace_name, form_answer]
end

Expand All @@ -30,7 +31,8 @@ def create
else
respond_to do |format|
format.html do
redirect_to [namespace_name, form_answer], alert: attachment.errors.full_messages.join(", ")
render_flash_message_for(attachment)
redirect_to [namespace_name, form_answer]
end

format.js do
Expand All @@ -55,6 +57,7 @@ def destroy
if request.xhr? || request.format.js?
head :ok
else
render_flash_message_for(resource)
redirect_to [namespace_name, form_answer]
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ def create

respond_to do |format|
format.html do
render_flash_message_for(resource)

redirect_to [namespace_name, form_answer], alert: render_errors
end

Expand Down
2 changes: 2 additions & 0 deletions app/controllers/concerns/draft_notes_mixin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def create

respond_to do |format|
format.html do
render_flash_message_for(resource)
redirect_to [namespace_name, form_answer]
end

Expand All @@ -28,6 +29,7 @@ def update

respond_to do |format|
format.html do
render_flash_message_for(resource)
redirect_to [namespace_name, form_answer]
end

Expand Down
70 changes: 70 additions & 0 deletions app/javascript/controllers/inline_flash_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
export default class extends ApplicationController {
static targets = ['form', 'link'];

static values = {
error: String,
success: String,
};

connect() {
this.formTargets.forEach((el) => {
el.addEventListener('ajax:x:success', this.onSuccess);
el.addEventListener('ajax:x:error', this.onError);
});
}

disconnect() {
this.formTargets.forEach((el) => {
el.removeEventListener('ajax:x:success', this.onSuccess);
el.removeEventListener('ajax:x:error', this.onError);
});
}

success(event) {
return this.onSuccess(event);
}

error(event) {
return this.onError(event);
}

onSuccess = (event) => {
const msg = this.hasSuccessValue ? this.successValue : 'Success!';
const [alert, identifier] = this.createAlert('success', msg);

setTimeout(() => this.showAlert(alert, identifier), 1);
};

onError = (event) => {
const msg = this.hasErrorValue ? this.errorValue : 'An unknown error has occurred, please try again.';
const [alert, identifier] = this.createAlert('danger', msg);

setTimeout(() => this.showAlert(alert, identifier), 1);
};

createAlert = (type, message) => {
const id = 'alert__' + String(Math.random()).slice(2, -1);
const element = `
<div id='${id}' class='alert alert-${type}' data-controller='element-removal' role='alert' style='padding-top: 6px; padding-bottom: 6px; margin-bottom: 8px;'>
${message}
<button type='button' class='close' data-action='click->element-removal#remove' aria-label='Close' style='font-size: 18px;'>
<span aria-hidden='true'>&times;</span>
</button>
</div>
`;

return [element, id];
};

showAlert = (alert, identifier) => {
const existing = this.element.querySelector('[id*=alert__]')
if (existing) existing.remove()

this.element.insertAdjacentHTML('afterbegin', alert);

setTimeout(() => {
const inserted = document.getElementById(identifier);
if (inserted) inserted.remove();
}, 4000);
};
}
Loading

0 comments on commit dbc7cb9

Please sign in to comment.