Infinite-zooming image in browser canvas?

working on a electron microscope project. We’d like to implement infinitely zooming image, where it always loads another image, when scaled. So it never runs out of images. The idea is to be able to scroll infinitely.

I would appreciate the help. if you know of any library that functions this way.

I tried searching for such library but i couldnt find any. I was wondering if there is any open source library for this. I was able to find something similar to my goal: codepen.io/smallcoder/pen/dypEBxa your text

Thanks,
Jan

Issue with Form validation in React with React Hook Form

Hello fellow developers,

I’m new to React and I’m having some troubles with form validation. I’m working on a CRUD app with API. When I update form fields the validation tells me that form input is required even if they have data already.

To replicate the issue, from the Read view just click on update button, on any record, and when you’re inside the Update view click the Update Button without changing anything.

Screenshot -> https://ibb.co/zXXy5ML

APP -> https://react-phonebook.vercel.app/

Source CODE -> https://github.com/alessiooli/react-phonebook

I read all the documentation and examples of React Hook Form but didn’t find a solution. Since I’m a beginner in React it’s hard to debug the issue all by myself.

is there anyway skip event bubbling one child element?

Lets say i have parent -> child -> sub child and adding click event listener to all the three elements. i am trying to achieve when click sub child i want to skip child listener but want execute parent listeners. is there any way to achieve this ?

function parentClick() {
 alert('parent click');
}


function childClick() {
 alert('childClick');
}

function subChildClick() {
 alert('subChildClick');
}
.parent {
 width: 200px;
 height: 200px;
 background-color: green;
 color: white;
 padding: 20px;
}

.child {
 width: 150px;
 height: 150px;
 background-color: yellow;
 color: red;
 padding: 20px;
}

.sub-child {
 width: 100px;
 height: 100px;
 background-color: red;
 color: white;
 padding: 20px;
}
<div class="parent" onClick="parentClick()">
 parent
  <div class="child" onClick="childClick()">
     child
    <div class="sub-child" onClick="subChildClick()">sub child</div>
  </div>
</div>

thanks.

Jest runs test for the file that is not specified testRegex file patters

Issue

I have a small util with a dedicated test file:

enqueue.js
enqueue.test.js

Later the util is imported into another module and used there:

However, when I run the single test for the enqueue.test.js or for the whole project, Jest looks into the parent module that has no test suits and outputs the error for it:

 ReferenceError: nn is not defined

      37 |
      38 |     function init() {
    > 39 |         if (nn?.launch.allModulesInitialised) {
         |         ^
      40 |             return;
      41 |         }
      42 |

… while the Jest config has a testRegexp property:

testRegex: '(/__tests__/.*|(\.|/)(test|spec))\.m?[jt]sx?$'

Files content

enter image description here

I have many other tests in the project that run well however this one fails, I suspect that it might have something to do with introducing web pack aliases to jest config:

{
    verbose: true,
    rootDir: rootPath,
    transform: {}, // Disable default babel-jest transform to enable support for ES Modules
    testRegex: '(/__tests__/.*|(\.|/)(test|spec))\.m?[jt]sx?$',
    // testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
    testEnvironment: 'jsdom',

    modulePaths: [
        '<rootDir>/build/node_modules',
    ],

    moduleNameMapper: {
        "^@common/(.*)$": "<rootDir>/src/js/common/js/$1",
        "^@common.values": "<rootDir>/src/js/common/js/values",
        "^@common.utils": "<rootDir>/src/js/common/js/utils",
    },
};

… but still not sure what would be the reason of this behavior, did someone ever experience similar issue?

How to display list of textboxes(price list) while clicking checkbox in css

While changing the supplier and store the item list dynamically populates , while clicking the item user wants to enter the ordered quantity , the question is how can i display the ordered quantity textbox in left to the item checkbox in css`enter image description here

this is the piece of code for item and ordered quantity

how to style this piece of code such that ordered quantity will be left to the item

How to renew taiga authToken?

There is a big problem with taiga to renew authToekn because of refresh(refreshToken) expiretime that expire approximately 30 seconds.
To refresh the auth token send a POST request containing the following data:

refresh (required): the refresh token

curl -X POST 
-H "Content-Type: application/json" 
-d '{
        "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYyNzI5OTQzMiwianRpIjoiMmNkMmNhNzQwYjRiNGZkNzk0ZDlmMDlmNWYwNzAwMTkiLCJ1c2VyX2lkIjo1fQ.vez_-n6y9yQo2uFgXTPB5YdJHFKUIAsCrNVJ29_T3wM"
    }' 
-s http://localhost:8000/api/v1/auth/refresh

I send request to this api and at the first time its ok but my refresh token expire for second time.

Highlight entire row in Django admin list

I’ve been stuck on this issue for days. I have a change_list with applicants, now I want to highlight the rows of objects that have been changed recently.

To do this I made a custom property:

@property
def has_recently_been_modified(self):
    return datetime.now() - self.updated_at < timedelta(days=5)

Which I use in the admin.py to create a field that houses a class I need:

 def recently_modified(self, obj):
    if obj.has_recently_been_modified:
        return mark_safe("<span class='row_yellow'></span>")

recently_modified.allow_tags = True
list_display = ('custom_status','viewed', 'updated_at', 'first_name', 'last_name', 'vacancy', 'created_at', 'recently_modified')

And with JS I use that class to color the row:

window.onload = function () {
        const x = document.getElementsByClassName("row_yellow");
        let i;
        for (i = 0; i < x.length; i++) {
            let ligne = x[i].parentNode;
            while (ligne.tagName !== "TR") {
                ligne = ligne.parentNode;
            }
            ligne.style.backgroundColor = "yellow";
        }
    }

Although it does color the entire row, the extra empty column at the end of the row is a real thorn in my eye. Removing it from the list_display doesn’t obviously work.

So my question is, is there a clever way to “hide” it? Or even a completely different method to color the row?

I have tried using django-liststyle, but that seems like a broken package. I immediatly get a TemplateSyntaxError at the second import line in their file.

How to write unit test case to check modal is defined or not

I need to write unit test cases where i need to check

  1. when i’m in particular page then only onclick sign-out i get confirmation modal pop up.
  2. when i’m in other pages other than particular page onclick sign-out it should call a function

JS code

import { ConfirmationModal } from '../form.js';

export class Auth {
  attachListeners() {
    // signout
    this.store.on('signout', async () => {
      const { pathname } = this.store.location;
      const pagepath = `${this.store.hrefRoot}/my-account/pagepath`;
      if (pathname === pagepath) {
        this.pagepathWarningModal(pathname);
      } else {
        this.onSignOutPage(pathname);
      }
    });
  }

  async onSignOutPage() {
    localStorage.removeItem('Hello World!');
  }

  async pagepathWarningModal(pathname) {
    const ph = {
      deleteShould: 'Delete changes',
      leave: 'Leave',
      cancel: 'Cancel',
    };
    const onConfirm = async () => {
      this.onSignOutPage(pathname);
    };

    try {
      await ConfirmationModal({
        onConfirm,
        title: ph.changesToQuickOrderWillNotBeSaved,
        confirmText: ph.leave,
        abortText: ph.cancel,
      });
    } catch (e) {}
  }

  async signout() {
    this.session = undefined;
    this.save();
  }
}

Unit test file


import { Auth } from '../../../scripts/modules/Auth.js';
import { Hello_world } from '../scripts.js';
/**
 * @param {Partial<Store>} [overrides]
 * @returns {Partial<Store>}
 */
const makeMockStore = (overrides = {}) => ({
  location: window.location,
  upstreamURL: 'http://localhost',
  ...overrides,
});

describe('Auth Script', () => {
  /** @type {Partial<Store>} */
  let mockStore;
  /** @type {Record<keyof Console, jest.Mock & { squelch: () => void }>} */
  let mockLogger;
  /** @type {(name: string) => typeof console} */
  let _ogLogger;
  /** @type {Auth} */
  let auth;
  describe('given localStorage', () => {
    beforeAll(() => {
      _ogLogger = { ...global.logger.getLogger('Auth') };
      localStorage.setItem(Hello_world, []);
    });

    beforeEach(async () => {
      mockStore = makeMockStore({
        Auth: {
          session: {
            customer: {
              email: '[email protected]',
            },
          },
        },
        isReady: () => true,
        on: jest.fn().mockImplementation((ev, action) => {
          if (ev === 'auth:signout:submit') action();
        }),
        emit: async () => {},
        load: async () => {},
        DataLayer: { pageShownHandler: jest.fn(() => true) },
      });

      // wrap each logger function
      mockLogger = global.logger.getLogger('Auth');
      Object.entries(_ogLogger).forEach(([lvl, fn]) => {
        const newFn = jest.fn().mockImplementation(fn);
        newFn.squelch = () => {
          newFn.mockImplementation(() => {});
        };
        mockLogger[lvl] = newFn;
      });

      auth = new Auth(mockStore);
    });

    afterEach(() => {
      Object.keys(_ogLogger).forEach(lvl => {
        mockLogger[lvl] = _ogLogger[lvl];
      });
    });

    describe('when there is order pad skus key in the local storage', () => {
      test('then user clicks on signout', async () => {
        auth.store.emit('signout');
        const Hello_worldVar= JSON.parse(localStorage.getItem(Hello_world));
        expect(Hello_worldVar).toBeNull();
      });
    });
  });
});

How would i write code so that when i’m particular page the modal displays in all other pages no modal displays signout directly

While pressing any key Button gets visible of Password field(function like Instagram’s login page)

I tried to make clone of Instagram’s login page. I tried to copy “Show Button”(in password field) functionality like this:

const input = document.querySelector('.password');
input.addEventListener('keydown', showButton);

function showButton(e) {
    button.style.display = "block";
}

Problem with the code is, that its also working on pressing keys like – shift,alt,ctrl etc.
i wanted to work it only on alphabetic and numeric keys which are most likely to be filled in input of type-password, so then user can see the button(Show) to see the password.

Enable TouchStart, TouchHold, & TouchEnd on Android for Measuring Finger Ring Size

I am working to build an APP with Nuxt3 framework for Ring Sizing on Touch Screen. I want to Enable Touch Function on Android Screen, Enabled it but I Want to hold till the user dos not remove touch event and Measure the Area of Finger as RING Size on event Touch Removed. please guide me regarding this issue and please let me know how I can make a finger size doted line as Touch event start and want to display the Result as Touch event Removed by a popup window/screen. in this case my touch function start and instantly removed as start and a popup window displayed but the problem is when I click Ok to and touch screen again popup received, that should not receive and also touch event should stop and redirect it to main page to Measure it Again.

<template>

<div id="source" class="source" @touchstart="setSize()">

  </div>

</template>

<script setup>

const setSize = () => {
  if (typeof window !== "undefined") {

    document.addEventListener('touchstart', onTouchStart, true)
  
    function onTouchStart() {
      console.log('touch start')
      const src = document.getElementById("source");

      src.addEventListener("touchstart", size);
      src.addEventListener("touchmove", size);
      src.addEventListener("touchend", size);

      function size(e) {
        const touch = e.changedTouches.item(0);
        src.style.width = `${touch.radiusX}px`;
        src.style.height = `${touch.radiusY}px`;
        console.log(`${touch.radiusX}px`);
        console.log(`${touch.radiusY}px`);
        e.preventDefault();
      }
      
        
        removeListeners();
        displayResult();
      console.log('touch removed')
      // touch detected: do stuff

    }
    function removeListeners() {
      document.removeEventListener('touchstart', onTouchStart, false)
    }
  }

}

</script>

How do I make this link perform an onclik event after loading (Laravel)

I have the below link

<a href="javascript:void(0)"  onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a>

I’d like it to change the language of page (happens after reloading the page) then make the xtenderSearchItem visible as above once the link has loaded.

I have the below so far, but it makes the xtenderSearchItem visible first then loads the page/changes the language.

<a href="language/{{ 'zh' }}" onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a>

Html Filter with Option Tag

Does someone know how to do this for option instead of button?
The Script should filter the HTML section. My Problem is that apparently it doesn´t work with instead of . Results in not showing me anything instead of the all class.

CSS
.show {
  display: block;
}
.filterDiv {
  display: none;
}

This is the filter section. By default it should be set on all

                        <div class="col-lg-6 col-sm-6 col-12" id="myBtnContainer">
                            <div class="release-filter justify-content-end d-flex">
                                    <div class="filter-title">
                                        <select name="year">
                                            <option class="btn active" value="" onclick="filterSelection('all')" disabled selected>Filter By Year</option>
                                            <option class="btn" value="2023" onclick="filterSelection('2023')">2023</option>
                                            <option class="btn" value="2022" onclick="filterSelection('2022')">2022</option>
                                            <option class="btn" value="2021" onclick="filterSelection('2021')">2021</option>
                                            <option class="btn" value="2020" onclick="filterSelection('2020')">2020</option>
                                          </select>
                                    </div>
                            </div>
                        </div>

This is one of the items that should be filtered. But as mentioned above it doesnt work. It simply doesnt filter anything and ends up in not showing me anything.

                        <div class="col-xl-6 col-lg-6 col-12 filterDiv 2023">
                            <div class="collection-release">
                            </div>
                        </div>
JS
    
        filterSelection("all")
function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("filterDiv");
  if (c == "all") c = "";
  // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
  }
}

// Show filtered elements
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}

// Hide elements that are not selected
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}

// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>