Ruby on Rails Form Validation Removes Javascript Changes

I have a form that based on the users clicks, changes some of the labels and placeholder text as well as hides some of the form elements. If the form has a validation error, it resets all of the changes made by javascript back to what originally existed when the form was loaded (i.e the hidden form objects are visible again and the labels/placeholders are changed back to the original text). Is there a way to maintain these changes if a form validation error occurs? Is there a javascript event that is triggered if the form is loaded due to validation error?

I am using vanilla javascript, not jquery.

React Jest Mock a variable used inside a component while rendering the component

I have a test case where I need to render a component and check the rendered component afterwards. This rendered value depends on a variable used inside a component.

Triangle.tsx:

export const Triangle = ({
     prop1,
      prop2
    }: Props): JSX.Element => {
      const [variable1] = useVarState();
      if(!variable1) {
        return <></>;
      return (<div></div>);    

TriangleTest.tsx:

describe('Testing component', () => {
          test('Main Elements', () => {
            const prop1 = jest.fn();
            const prop2 = undefined;
        
            const container = render(
              <Triangle
                prop1={prop1}
                prop2={prop2}
              />
            );
        
            const triangle = container.container.querySelector(
              '.Triangle'
            );
            expect(triangle).not.toBeNull();
        }
    }        

How can I mock the value of variable? useVarState returns a map based on a useContext.

Could someone provide an example and explain why mutating an original array would be bad?

I am studying JS and some array method mutate the original array. I was wondering in which cases this would be a bad thing. I usually do not need the original arrays to be the same as the original ones, but i am assuming that’s because my problems are not complex yet.

I have not ran into that complexity yet and i am curious where it would be applied. An example or explanation would be awesome.

How can I use a function’s argument from another file in JavaScript?

I’m working with Express.js and thought it would be a good idea to create a “helpers.js” file with a function that would only be written once in my app.

What I want to do is, with that function, call a “req” (request) argument that belongs to another function on another file.

Here’s what I have:

someFile.js

const express = require("express");
const router = express.Router();
const someAuth = require('./someAuth');
const helper = require(./helpers.js);

router.get('/some-route', someAuth, async (req, res) => {
    try {
        const someResult = helper.someFunction(); //I want this function to use "req" argument
        res.json({someResult});
    } catch (error) {
        res.json({error});
    }
});

helpers.js

const jwt = require('jsonwebtoken');

async function someFunction() {
    const token = req.cookies.token; // "req is not defined" ReferenceError
    const decoded = jwt.decode(token);
    const email = decoded.email;

    res.json({email});
}

module.exports = { someFunction }

I thought this would work since I’m calling “someFunction()” already inside the function containing the “req” argument, but I guess the import already counts…
Is there a way to use such argument? I don’t want to export the whole function and use it as an argument for the “router.get(…” like “someAuth”.

issue with adding custom button to the toolbar of tinymce vue.js wrapper

i am trying to adding custom button to the toolbar of tinymce using the vue.js wrapper(using vue 3 and tinymce 5)
the issue that the custom button doesn’t show in the toolbar

i have tried the following , the logs in the init and setup are showing in the console and when using
tinymce.activeEditor.ui.registry.getAll().buttons i am able to see the test button there

<template>
  <Editor
    api-key="any-key"
    v-model="content"
    :init="editorSettings"
    @onInit="handleEditorInit"
  />
</template>

<script>
import Editor from '@tinymce/tinymce-vue';

export default {
  components: {
    Editor,
  },
  data() {
    return {
      content: '',
      editorSettings: {
        setup: function (editor) {
          console.log('setup', editor);
          editor.on('init', function () {
            console.log('setup init', editor);
            editor.ui.registry.addButton('test', {
              text: 'Custom',
              tooltip: 'Add Custom Action',
              onAction: function () {
                console.log('test button clicked');
              },
            });
          });
        },
        toolbar: 'test',
      },
    };
  },
};
</script>

i have came across this method editor.ui.registry.addToToolbar('customAction'); to add the button manually but it doesn’t really exist in the registry object

why my ‘while’ code doesn’t work, but the for one does?

I’m learning javascript.. my ‘while’ loop outputs senseless stuff but the ‘for’ one does the work (which is gives a prime number with 10 as a limit), i checked for syntax and ‘;’, what’s left?

Here is the working one ‘for’:

            let n = 10;
            nextPrime:
            for (let i = 2; i <= n; i++) { // for each i...
              for (let j = 2; j < i; j++) { // look for a divisor..
                if (i % j == 0 ) continue nextPrime; // not a prime, go next i
              }
              alert( i ); // a prime
            }

this one works just great.. gives 2,3,5,7 which are prime numbers..

here is the ‘while’ one:

            let n = 10; /*limit for the loop*/
            let i = 2; /*base*/
            let j = 2; /*factor*/
            nextPrime:
            while (i <= n) {
              while (j < i) {
                if (i % j == 0) {
                  continue nextPrime;
                }
                j++;
              }
              i++;
              alert(i);
            }

this one gives me senseless numbers (3,4,5,6,7,8,9,10,11).. but why? and what’s the solution?

React: Issues with rendering Promise object and useContext is null error when navigating to /verifyOtp route

I’m working on a React application and encountering two runtime errors. The first error is: “Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.” The second error is: “Cannot read properties of null (reading ‘useContext’) TypeError: Cannot read properties of null (reading ‘useContext’)”.

I have a component called VerifyPhoneNumber that makes an API call using the addPhoneNumber function. If the API call is successful, the component should navigate to the /verifyOtp route. Here’s the relevant code:

const handleVerification = async (e) => {
    e.preventDefault();
    const phoneNumberWithoutPlus = phone_number.replace('+', '');
    const { error } = await addPhoneNumber(phoneNumberWithoutPlus);
    if (error) {
        alert(error);
    } else {
        navigate('/verifyOtp');
        resetForm();
    }
};

After adding the <Route path=”/verifyOtp” element={} /> route in my App.js file, I started encountering the mentioned runtime errors. The VerifyOtp component seems to be causing the issue, but I’m not sure how to fix it.

My App.js code –

function App() {
  return (
    <div>
      <Router>
        <Navbar />
        <Routes>
          <Route
            path="/"
            element={(
              <>
                <Hero />
                <Analytics />
                <Cards />
              </>
            )}
          />
          <Route path="/login" element={<Login />} />
          <Route path="/signup" element={<Signup />} />
          <Route path="/addPhoneNumber" element={<VerifyPhoneNumber />} />
          <Route path="/verifyOtp" element={<VerifyOtp />} />
        </Routes>
      </Router>
      <Footer />
    </div>
  );
}

Additionally, the second error mentions that useContext is null. I’m using the useContext hook in some of my components, but I’m unsure why it’s null and how to resolve this error.

Could someone please help me understand what’s causing these errors and how to fix them?

Adding an OR grouping condition to this code

      {chart?.record?.settings?.yAxis?.type === 'number' &&
        chart?.record?.chartType != 'percentage' && (
          <div className="mt-1 remove remove-input-txt-border">
            <Controller
              name="settings.yAxis.aggregation"
              control={control}
              render={({ field }) => 

I want to make an addition to this code snipet here.

Currently it works when:
yAxis type = number
and
chart type != percentage

I want to change it to work when:

yAxis type = number
and
chart type != percentage

or

yAxis type = formula
and
chart type != percentage

No attempts made so far

`jest.mock` Not Mocking Utility Function That’s Prompting For User Input

Description

I am attempting to write a unit test to mock a function called prompt_user which waits for the user to input text for a text rpg I’m writing. The way I’ve put the test together is not resulting in the prompt_user function being replaced with the mock and I’m trying to understand why.

For context this is the jest documentation I’m using to try to build this test

For reference my attempts to create these unit tests can be seen here

The test hangs forever on the call to game.main_loop() since it’s waiting for user input that never happens.

game.js.test

import * as game from "./game.js"
import { user_prompt } from './shared_functions.js'

jest.mock('./shared_functions', () => {
  const originalModule = jest.requireActual( './shared_functions' );

  //Mock the default export and named export 'foo'
  return {
    __esModule: true,
    ...originalModule,
    user_prompt: jest.fn( () => 'Name' ),
  };
});

test('should do a partial mock', () => { 
    game.main_loop()
    expect( gamestate.player.inventory ).toContain( ritual_dagger );
});

game.js

import * as util from "./shared_functions.js"

function main_loop( passed_gamestate ) {
    let gamestate = {}

    util.create_character( gamestate ); // This is where the test hangs
    game_loop( gamestate );
    end_game( gamestate );
}

shared_functions.js

import PromptSync from "prompt-sync"
const prompt = PromptSync()


function create_character( gamestate ) {
    print( `n` )
    var NAME = user_prompt( 'What is your name? ' );
    let character = new Player_Class( NAME, 4, 4, 4 )
    
    character.update_condition( "fresh", true )
    print( `Welcome ${character.playername}!` )

    gamestate.player = character
}

function user_prompt ( question ) {
    return prompt( question ) ;
}

export {
    create_character,
    user_prompt
}

Odoo JS / Changes in one2many field (tree) appears only after reloading the page

I am a beginner Odoo developer, I have a little issue with my code which is I change a field called “state” in a One2many field appointment_ids (tree), it changes, but it looks the same and the change appears only after I reload the page or click any other button and return.

the codes I am using :
The wizard used to return the form view :

class choose_appointment_customer(models.TransientModel):
_name = "choose.appointment.customer"

@api.model
    def action_finish_scheduling(self, args):
// some code here that call _return_action_appointments function but it's long and it's working fine 
return self._return_action_appointments(appointment_ids, batch_id)

@api.model
    def _return_action_appointments(self, appointment_ids, batch_id):
        """
        Method to return proper actions for those appointment_ids

        Args:
         * appointment_ids - business_appointment recordset

        Returns:
         * ir.act.window dict
        """
        res = False
        if len(appointment_ids) >= 1:
            res = self.sudo().env.ref("slnee_appointment_core.business_appointment_batch_action_only_form").read()[0]
            res["res_id"] = appointment_ids[0].batch_id.id
        return res

XML:

<record id="business_appointment_batch_action_only_form" model="ir.actions.act_window">
        <field name="name">Appointment</field>
        <field name="type">ir.actions.act_window</field>
        <field name="res_model">business.appointment.batch</field>
        <field name="view_mode">form</field>
    </record>

the js function executed to return the form view:

/**
     *   Re-write to make chosen appointments + close parent dialog + open form view
    */
    _save: function () {
        var self = this;
        self.form_view.saveRecord(self.form_view.handle, {
            stayInEdit: true,
            reload: false,
            savePoint: self.shouldSaveLocally,
            viewType: 'form',
        }).then(function (changedFields) {
            var record =  self.form_view.model.get(self.form_view.handle, {raw: true})
            var chosenAppointments = self.parentRenderer.chosenAppointments;
            self._rpc({
                model: "choose.appointment.customer",
                method: "action_finish_scheduling",
                args: [{"data": record.data, "chosen": chosenAppointments}],
                context: record.context,
            }).then(function (res) {
                self.close();
                self.topWindow.closeCalc(res);
            });

        });
    },


});

The One2many field I am talking about (model : business.appointment ) :


<!--    Form View    -->
    <record id="business_appointment_batch_view_form" model="ir.ui.view">
        <field name="name">business.appointment.batch.form</field>
        <field name="model">business.appointment.batch</field>
        <field name="arch" type="xml">
            <form js_class="ba_batch_form">
<page string="Reservations">
                            <field name="appointment_ids" readonly="1"
                                   options="{'no_create_edit': 1, 'no_quick_create': 1,'no_open':True,'no_create' :1}"
                            widget="one2many_selection">
                                <tree default_order="datetime_start"
                                      decoration-success="state in ['done']"
                                      decoration-muted="state in ['cancel']"
                                      decoration-warning="state in ['missed']"
                                >
                                    <field name="hide_delete_button" invisible="1"/>
                                    <field name="is_pack" invisible="1"/>
                                    <field name="resource_id"/>
                                    <field name="service_id"/>
                                    <field name="datetime_start"/>
                                    <field name="datetime_end"/>
                                    <field name="state"/>
                                    <button name="open_this" type="object" icon="fa-list"/>
                                    <button name="%(base_cancel_reason.base_cancel_reason_wizard_action)d" type="action"
                                            icon="fa-trash"
                                            attrs="{'invisible': ['|','|',('hide_delete_button', '=', True),('state', 'in', ['cancel', 'missed', 'done']),('parent.state', '!=', 'reserved')]}"
                                    />
                                </tree>
                            </field>
                        </page>

Please help me and thank you in advance.

I tried crnd_web_view_refresh_timed module in Odoo apps store but it did not reload the tree view “appointment_ids”

How to vary stroke or fill color based on (secondary) data property in d3.js?

I’m able to draw lines just fine, however when trying to alter line’s color based on the data’s property deviationFromAvg, it only ever returns the first color based on the value at index [0].

How do I vary the line color based on the property deviationFromAvg?

      // shape of data
      // fooData = Array<{
      //    value: number;
      //    deviationFromAvg: number; 
      // }>

      var leftLine = d3.line()
       .x(function(d, i) { return x(i); })
       .y(function(d, i) { return y((d as any).value); });

      // this produces a correct length list of {value: fooNumber, deviationFromAvg: fooNumber}
      console.log(deviationFromAvg);

      updateNode.append("path")
      .datum(fooData)
      .style("fill", "none")
      .style("stroke", function(d, i) {

        // logs only once... value: 123, deviationFromAvg: -1
        console.log(d[i]);

        if((d[i] as any).deviationFromAvg > 0)
          return "red"
        else if((d[i] as any).deviationFromAvg < 0)
          return "green";
        else
          return "blue"
      })
      .style("stroke-width", 1.5)
      .attr("d", leftLine as any);

Additionally, if I try something like this, it only ever draws one random color for the whole set of lines each time i refresh:

      return rgbToHex(
             Math.floor(Math.random() * 255), 
             Math.floor(Math.random() * 255), 
             Math.floor(Math.random() * 255) 
      );

Am I able to escape inertness when using the HTML inert property?

I’m building web component that contains <dialog> element. I’m opening the dialog with HTMLDialogElement.showModal(), which moves the dialog to the top layer. Some of the content of the dialog is top-layer incompatible, namely, Google Recaptcha, which renders beneath the dialog.

A number of other individuals have noted the same issue with dialog elements and ReCaptcha, and one approach appears to be to use HTMLDialogElement.show() instead of showModal. From a usability standpoint, I think this is acceptable, but from an accessibility standpoint, I’d really like the benefits that HTMLDialogElement.showModal() provide. Namely, making all other HTML elements inert and thus noninteractive and hidden from the accessibility tree. And by using the inert attribute or property, I can make a certain subtree of an HTML document inert myself.

As of today’s date (2023-10-31), both MDN and the HTML Living Specification indicate that it’s possible to “escape inertness”, but this doesn’t appear to be possible for HTML authors. For example, using Chrome/Edge, with the following HTML, I can’t interact with the elements inside of the dialog if opened with .show(), when I’m attempting to deliberately “escape inertness” via setting the dialog’s inert property to false.

Is it possible for HTML authors to be able to escape inertness in this way?

const dialogOpener = document.getElementById("dialogOpener")
const modalOpener = document.getElementById("modalOpener")
const dialogCloser = document.getElementById("dialogCloser")
const testDialog = document.getElementById("testDialog")

dialogOpener.addEventListener("click", evt => {
  testDialog.show()
  document.body.inert = true
  testDialog.inert = false
})

modalOpener.addEventListener("click", evt => {
  testDialog.showModal()
  // modal inertness is implicit, and the following lines have no effect:
  document.body.inert = true
  testDialog.inert = false
})

document.getElementById("dialogCloser").addEventListener("click", evt => {
  testDialog.close()
  document.body.inert = null
  testDialog.inert = null
})
<button id="modalOpener">.showModal()</button>
<button id="dialogOpener">.show()</button>

<dialog id="testDialog">
  <p>
    ... Some <a href="https://developer.mozilla.org/en-US/docs/Glossary/Top_layer">HTML Top Layer</a>-incompatible content here
  </p>

  <button id="dialogCloser">
    Close Dialog
  </button>
</dialog>

How to handle with disable values that are send like a information to back-end?

I’m working on an application that has a settings screen. The main feature here is that when specific binary buttons at the top of the page are active, the cards below are disabled. More specifically, the time units [“dias”,“horas”,“minutos”] are disabled. However, when a time unit is disabled, it’s not sent to the back-end in the POST request (I’m using Laravel in the back-end).
enter image description here

I need the value to be passed to the back-end even if it’s set to false. My question is more about what would be the best approach in a situation like this. I know some “solutions”, like duplicating hidden fields of the cards, creating a back-end logic to consider the value zero when saving if the item isn’t set, or even removing the disable and just setting the value of timeUnits to zero when submitting.

However, all these options seem more like stopgap measures rather than real solutions. Any advice would be appreciated

JavaScript fetch-request to backend results in .catch(), but the backend returns a Statuscode 200 [closed]

JS-Version: 18.13.0
Vue-Version: 5.0.8

Hey guys! I am currently working on a web-application. I am using Vue.js in my Frontend with JS, and I am currently stuck on a common fetch request to my backend.
The thing is my code always results in the .catch(console.log(“error”)) but my backend responds with a 200 Statuscode with the correct JSON-Format, when I send the request. My CORS-Configuration is therefore also correct I guess.
I maybe have to add, that I am developing with my backend and frontend run at the same time on different ports. (Idk if that can mess up anything)

Frontend-Code-Snippet:

const userData = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(user)
}

const response = await fetch('http://localhost:8080/register', userData).catch(console.log("error"))

if (response.ok) {

  const requestOptions = {
    method: 'GET',
    redirect: 'follow'
  }

  const id = await fetch('http://localhost:8080/userEmail/' + email, requestOptions).catch(console.log("error"))
  this.navigateToLogin()

} else {
  alert("it didnt work, try again")
}

Backend-Controller-Endpoint:

@PostMapping("/register")
    public ResponseEntity<AuthenticationResponse> register(@RequestBody RegisterRequest request){
    return ResponseEntity.ok(service.register(request));
}

Does someone have a clue why it is like this?

Load iframe only one time, and hide it with toggle event

I have different iframe, but it slows down. I want the iframe to only load, when a button is clicked. And then hide/show iframe with toggle event.
Example of the code:

<script>
    $(document).ready(function(){
        $("#button2").click(function(){
            $("#iframecon").toggle();
        });
    });
</script>
<input type="checkbox" id="button2" onClick='document.getElementById("iframe2").src="/page1.php";'>
<div id="iframecon">
    <iframe id="iframe2" width="100%" height="100%"></iframe>
</div>

How can I do it? Thanks