Retry HTTP request

I have Angular service which is used in the Angular pipe. The job of that service is to do a HTTP request and fetch translations. Idea is to have a pipe which returns a Observable that only first subscriber will actually trigger HTTP request. And this is how subscription happens:

{{( 'some_tag' | dynamicTranslation | async )}}

This is pipe:

@Pipe({ name: 'dynamicTranslation', standalone: true })
export class DynamicTranslationPipe implements PipeTransform {
  constructor(private translationService: DynamicTranslationService) {}

  transform(tag: string): Observable<string> {
    return this.translationService.getTranslations()
      .pipe(
        map((translations: object) => {
          if (this.tagExistsInTranslations(translations, tag)) {
            return translations[tag] as string;
          }
          return tag;
        }),
        catchError(() => {
          return of(tag);
        })
      );
  }

  private tagExistsInTranslations(translations: object, tag: string): boolean {
    return Object.prototype.hasOwnProperty.call(translations, tag);
  }
}

And this is service:

.
.
.

protected _translations$: Observable<object>;
private readonly _refreshTranslations$ = new BehaviorSubject<void>(undefined);

public getTranslations(): Observable<object> {
  if(this._translations$) {
    return this._translations$;
  }

  this._translations$ = this._refreshTranslations$
    .pipe(
      tap(() => console.log('tap')),
      switchMap(() => this.requestTranslations()),
      shareReplay(1),
      retry()
    );

  return this._translations$;
}

public refreshTranslations(): void {
  this._refreshTranslations$.next();
}

So no matter how many subscriptions happen only one HTTP call is executed and this is what was intended. BUT, calling this.refreshTranslations() is not triggering another HTTP request? Why?

Using two generic keys seems to reference the correct subset of data, however, subkeys resolve to `any` [duplicate]

I have a data structure which looks as follows:

import { ParasiteDescription, LookBackDescription } from '@/movies/static';
import type { MovieGenre, MovieDescription } from '@/movies/types';

const movies = {
  drama: {
    parasite: {
      description: ParasiteDescription,
      director: 'Bong Joon Ho',
    }
  },
  animation: {
    'Look Back': {
      description: LookBackDescription,
      director: 'Tatsuki Fujimoto'
    }
  },
  comedy: {},
  action: {},
} as const satisfies Record<
  MovieGenre,
  Record<
    string,
    {
      description: MovieDescription;
      director: string;
    }
  >


type StaticMovieData = typeof movies;

I want to create a component which will allow the user to reference any “genre” in this static list, and then any movie that’s listed under that genre. Here is what I tried:

interface MovieProps<T extends keyof StaticMovieData, K extends keyof StaticMovieData[T]> {
  genre: T;
  title: K;
}

function Movie<T extends keyof StaticMovieData, K extends keyof StaticMovieData[T]>({
  genre,
  title,
}: MovieProps<T, K>) {
  const data = movies[genre][title];
  const description = data.description;
}

data appears to show the correct type, showing something roughly like StaticMovieData[T][K] in my IDE. However, description is listed as an any type, and I can’t figure out why

Why would this be? I would think that the type would appropriately know where it’s referencing in this object which is static

Edit: TYPESCRIPT PLAYGROUND LINK

How to manually set focus on a button with refs for Keyboard Accessibility?

I have a webpage where users have a list of images they’ve uploaded. They have three buttons: Upload Image/Download Image/Delete Image. When the user clicks Delete, the Upload button will hide and Download Image/Delete Image turn to Delete/Cancel respectively.

When the user clicks this new Delete button, a modal will show up to confirm the users choice (yes/no). Whether or not the user hits Yes or No, I need to manually set focus on a button that would return a Keyboard user’s focus to where it was before the Modal opened (i.e. the Cancel button if they hit no). These button swaps are handled with conditional rendering statements. A rough outline of my code is as follows:


export const Images = ({ setUserImages, userImages }) => {
    const cancelRef = useRef(null);
...
    const handleFocus = () => {
        setShowDeleteModal(false);
        cancelRef.current.focus();
    };

return (
    <Container>
        ...
            <ButtonsContainer>
                        {enableSelect ? (
                            <>
                                {selectionType === "delete" && (
                                    <>
                                        {" "}
                                        <Button onClick={() => setShowDeleteModal(true)}>Delete</Button>
                                        <Button
                                            ref={cancelRef}
                                            onClick={() => {
                                                setEnableSelect(false);
                                                setSelectedImages([]);
                                            }}
                                        >
                                            Cancel
                                        </Button>
                                    </>
                                )}
                                {selectionType === "download" && (
                                    <>
                                        {" "}
                                        <Button
                                            onClick={() => handleDownload()}
                                        >
                                            Download
                                        </Button>
                                        <Button
                                            onClick={() => {
                                                setEnableSelect(false);
                                                setSelectedImages([]);
                                            }}
                                        >
                                            Cancel
                                        </Button>
                                    </>
                                )}
                            </>
                        ) : (
                            /* show upload/download/delete instead */
                        )}
                    </ButtonsContainer>
            <ImagesContainer>{renderedImages()}</ImagesContainer>
            {showDeleteModal && (
                <Modal
                    onClose={() => {
                        setShowDeleteModal(false);
                        setSelectedImages([]);
                    }}
                >
                    <ModalInner>
                        <h2>Are you sure you want to delete the selected image(s)?</h2>
                        <ButtonWrapper>
                            <Button primary onClick={() => handleDelete()}>
                                Yes
                            </Button>
                            <Button secondary onClick={handleFocus}>
                                No
                            </Button>
                        </ButtonWrapper>
                    </ModalInner>
                </Modal>
            )}
    </Container>
)

Before adding refs, when a keyboard user exited the modal, the focus would throw them all the way to the bottom of the page into the footer, which is outside of the body of the page. This only occurs on chromium browsers, doesn’t happen on Firefox, which is why I’m in this mess.

For some reason the ref is always null when I try this, despite the Cancel button being rendered on screen. I haven’t used refs much, so I’m a bit uneducated, but could the issue be that the Cancel button is being rendered conditionally?

I also tried using autoFocus with some state stuff but it didn’t do anything.

Sorry about the code formatting. I had to cut out a bunch of irrelevant content and it got a bit messy.

js v8 computed property names and inline cache

as far as my understanding go, in v8 if property access occurs on object with persistent shape jit optimize it to prety much struct acces that is just offsetting a pointer but is the same rules applies when dealing with computed property?
its obvious that if property is mutable/inconsistent its imposible, but what about following example

const kBar = "bar";

class Foo {
    [kBar] = 42;
}

/**
 * @param { Foo } foo 
 */
function getBar(foo) {
    return foo[kBar]
}

due to key being constant, in theory it can be optimized the same way as plain property access

im also intersted about symbol-key access, is in inheritly slower than plain property access or if variable containing key is constant its not make any difference ?

Keeping Modal open with AJAX background data refresh

I have a Node.js Express app using DataTables, and in those DataTables, I have child rows with bootstrap 5 modals. The modals open just fine; however, I am refreshing the data in the background every 5 minutes, and when that happens, the modal disappears, but the page is still “disabled.”

Here are some of the things I have tried:

  • using ‘beforeSend’ to “preventDefault” action of the modal being closed on refresh, then using ‘complete’ to enable this action;
  • use the action on ‘show.bs.model’ to set it to set an “isModalOpen” variable to true and then trying to delay the reload; and
  • used a function to “preventDefault” action, .then call the reload, and .then enable the close again.

I’m just looking for a solution that works!

TiA

Jason

How can I detect or show the actual browser download path using JavaScript and sync it?

I’m building a browser extension and I want to show the user where their screenshots will be saved by default.
I tried detecting the OS using JavaScript and displaying an estimated default path like:

image-1

But I realized this might not always be correct — especially if the user has changed their browser’s download path in settings.
Something like this:

image-2

I have tried detecting OS with navigator.platform + userAgent. Displaying common download paths based on platform. I have also read some docs about chrome.downloads.download() for extensions.

After this i realized that Web apps can’t access the filesystem or browser download settings due to security reasons. The browser always decides the actual download path. Even if I pass a filename, it’s saved relative to the default download folder, not something I can fully control.

Any ideas? how can i implement an approach that let users know where there files will be saved even if they change their default download location from browser settings.

New, need help please [closed]

I have a main sheet named DRIVER LEDGERS. I have many other sheets added to the DRIVER LEDGERS sheet. I want the sheet named COPY of MAINTENANCE POs to automatically copy columns A through I to one of the other sheets to columns A through I to the next available row based off my selection in column J.

I have entered the following and it does not work and I don’t understand why. Can anyone assist?

function onEdit(e) {
const sourceSheetName = "COPY of MAINTENANCE POs";
const sheet = e.source.getActiveSheet();
const editedRow = e.range.getRow();
const editedCol = e.range.getColumn();

// Only trigger if edit is in column J of the correct sheet
if (sheet.getName() === sourceSheetName && editedCol === 10) {
const destinationSheetName = e.value;
const destinationSheet = e.source.getSheetByName(destinationSheetName);

if (!destinationSheet) {
  Logger.log("Destination sheet not found: " + destinationSheetName);
  return;
}

const rowData = sheet.getRange(editedRow, 1, 1, 9).getValues()[0]; // A to I
const lastRow = destinationSheet.getLastRow();
destinationSheet.getRange(lastRow + 1, 1, 1, 9).setValues([rowData]);

// Optional: Clear the row from source sheet after copying
// sheet.getRange(editedRow, 1, 1, 10).clearContent();
}
}

I tried entering the above and I was expecting information from one sheet to automatically transfer to what ever sheet is outlined in column j

install ENTCORE

I’m currently installing ENT open ent, (entcore, springboard, infra-front etc). I’m having some installation problems, particularly with the widgets and timeline. If any of you have already installed this software, I’d love to hear from you! thank you!

lien/link: https://github.com/edificeio/springboard

run the software and publish

How to properly use nullable/optional values in Dexie JS?

I apologize if the title is a little vague as it’s hard to explain in only one short sentence, but here’s what I’m trying to do:

In Angular 17 with DexieJS, I have the following object:

export interface IView {
 x?: number,
 y?: number,
 z?: number,
 id: string,
 name?: string,
}

The coordinates and the name are optional because although I will need them, they’re not accessible from every part of the application.

For the database, I have the following:

export class MyDB extends Dexie {
  viewDatabase!: Table<IView, string>;
  constructor() {
      super('database');
      this.version(1).stores({
         viewDatabase: 'id',
      });
    }
}
export const db = new MyDB();

And I have the following get/set functions in another class:

async getView(id: string) {
   return db.viewDatabase
      .where('id')
      .equals(id)
      .first((data) => {
        return data;
      });
}

async addOrUpdateView(view: IView) {
    return db.viewDatabase.put(view);
}

And finally, this is what I’m trying to achieve:

Because some of the values in iView are optional, I want the database to not overwrite those values with undefined/null if a value passed in doesn’t have all of them. Instead, I want it to detect if there’s already values in there for the optional variables, and if so, just keep them and add the new stuff on top. I.e, if I initialize the following into the database:

{
  x: 1,
  y: 2,
  z: 3,
  id: '109210abc',
  name: 'test'
}

And then later I push the following value to the database, which has the same id (because I want to overwrite the values):

{
  x: 5,
  id: '109210abc',
  name: 'test_updated'
}

I want the database to keep the original values for y and z because they were not changed. I don’t want them to automatically get set to undefined or null. I only want x and the name to change since those are the only values that changed.

I understand I could do this manually by reading the database first, grabbing what’s in there, and then making a new value composed of both old and new data, but this is really tedious, especially in a large program where you may have to wait for the database to respond. Is there a way to do this automatically or at least more efficiently?

In the current program, it’s not working correctly because the optional values just keep getting removed/reset if they’re not defined when I save the value. I’m looking for a solution that allows me to keep the values as optional, if possible.

How would you make this CSS ‘cutoff’ type animation? [closed]

I’m developing a demo site & came across a certain animation style whilst looking for inspiration. It’s an animation where the elements ‘climbUp’ per-se on the page. How would you make this animation style? It seems as if it’s cut off as it moves up until it finishes. I’m using ‘@keyframes’ w/ CSS. I will link an image.

Animation seen on this website on launch: https://demo.kaliumtheme.com/restaurant/

I have no code to share as this is a subjective question.

I’ve tried overflow: hidden; and that didn’t seem to work (I might just be doing it wrong). I was thinking maybe an element in front of the animating element that makes it ‘invisible’ so you could see through it to the background-img whilst animation.

How do return jsonobject instead of Map inside Rust

i am using sort function to sort JSON based on object key this is my function as below

#[wasm_bindgen]
 pub fn sort_json_array(arr: JsValue, key: &str, ascending: bool) -> JsValue {
// Deserialize the JsValue into a Vec<Value>
let mut objects: Vec<Value> = from_value(arr).unwrap_or_default();

// Sort the objects by the specified key
objects.sort_by(|a, b| {
    let a_val = a.get(key).unwrap_or(&Value::Null);
    let b_val = b.get(key).unwrap_or(&Value::Null);

    // Perform type-aware comparison
    match (a_val, b_val) {
        (Value::String(a_str), Value::String(b_str)) => {
            if ascending {
                a_str.cmp(b_str)
            } else {
                b_str.cmp(a_str)
            }
        }
        (Value::Number(a_num), Value::Number(b_num)) => {
            if ascending {
                a_num.as_f64().partial_cmp(&b_num.as_f64()).unwrap_or(std::cmp::Ordering::Equal)
            } else {
                b_num.as_f64().partial_cmp(&a_num.as_f64()).unwrap_or(std::cmp::Ordering::Equal)
            }
        }
        (Value::Bool(a_bool), Value::Bool(b_bool)) => {
            if ascending {
                a_bool.cmp(b_bool)
            } else {
                b_bool.cmp(a_bool)
            }
        }
        _ => std::cmp::Ordering::Equal, // Default to equal for unsupported types
    }
});

let json_object = Value::Object(&objects);

// Serialize the sorted objects back into JsValue
to_value(&json_object).unwrap()   //[{}]
}

This working fine however i m facing issues like
instead of JSON object {} its returning like Map and i would like to pass additional param type if type is String i am interested in calling only string compared method and similar for number and bools to enhance time complexity.

Modal animation doesn’t work on dismissal

I’m trying to make a modal animate on showing, which works, but when I try to dismiss it by adding a hide class, the animation doesn’t work.

Here is the CSS styling:

/* MODAL STYLING */
.modal{
    height: 100vh;
    width: 100vw;
    min-height: 100%;
    min-width: 100%;
    margin-inline: auto;
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 50;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(3px);
    display: none;
}

.modal.show{
    display: flex;
    animation: pop-up 0.5s ease-in-out;
}

.modal.hide{ 
    /* opacity: 1; */
    animation: pop-down 0.5s ease-in;
}

.hidden{
    display: none !important;
}

/* Animations */

@keyframes pop-up {
    0%{
        transform: scale(0.5);
        opacity: 0;
    }
    70%{
        transform: scale(1.1);
        opacity: 1;
    }
    100%{
        transform: scale(1);
    }
}

@keyframes pop-down {
    0% {
        opacity: 1;
        transform: scale(1);
      }
      100% {
        opacity: 0;
        transform: scale(0.8);
      }
}

The JavaScript code:

const toggleModal = show => {
    if (show) {
        modal.classList.remove('hide');
        modal.classList.remove('hidden');
        modal.classList.add('show');
    } else {
        modal.classList.remove('show');
        modal.classList.add('hide');

        modal.addEventListener('animationend', (e) => {
            if (e.animationName === 'pop-down') {
                //For some reason, this never triggers.
                modal.classList.remove('hide');
                modal.classList.add('hidden');
            }
           },{ once: true }
        );
    }

}

brandElement.addEventListener('click', (e) => {
    toggleModal(true);
})

closeBtn.addEventListener('click', (e) => {
    toggleModal(false);
})

window.addEventListener('click', (e) => {
    if (e.target == modal) {
        // modal.classList.remove('show');
        toggleModal(false);
    }
})

After inspecting the modal element after dismissal, I found that the animation wasn’t cascaded out but the animation didn’t play.

Devtools capture

I have checked around and have found nothing on this. I could have simply animated with transitions, but I want more control over the animations. I

I checked different AI chatbots to debug but they kept regurgitating the same thing. I even looked up different ways to animate modals dismissal but found nothing similar.

‘this’ has a different value in the script from what is reported in Firefox console

Here is an html file:

<!DOCTYPE html>
<html>
<head>
  <title>check-this</title>
  <meta charset="utf-8">
  <script type="module">
    console.log(this);               //undefined
  </script>
</head>
</html>

As I would expect, since it’s a module, console.log(this) prints undefined.

However, if I use the Firefox debugger to pause the code, and type this at the console prompt, it gets reported as Window

>>this
Window https://example.com/check-this.html

Is this a bug in Firefox or is it what’s supposed to happen?

I’m using Firefox 136.0 on Ubuntu.

Chrome 135.0.7049.95, on the same machine, reports this as undefined in the console.

How to Stop Safari Web Extension from Asking for Permissions When Clicking a Toolbar Button

I am writing an extension for the Safari browser and one of its functions is to open a specific website when pressing a button in the toolbar. The site should open regardless of which tab is currently active. My extension manifest:

{
    "manifest_version": 2,
    "default_locale": "ru",
    
    "name": "__MSG_extension_name__",
    "description": "__MSG_extension_description__",
    "version": "1.0",
    
    "browser_action": {
        "default_icon": {
            "16": "images/FaNote_16.png",
            "32": "images/FaNote_32.png",
            "64": "images/FaNote_64.png",
            "128": "images/FaNote_128.png"
        }
    },

    "content_scripts": [{
        "js": [ "content.js" ],
        "matches": [
            "https://music.yandex.ru/*",
            "https://music.yandex.by/*",
            "https://music.yandex.kz/*",
            "https://music.yandex.uz/*",
            "https://music.yandex.com/*"
        ]
    }],
    
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    },

    "optional_permissions": [
        "nativeMessaging"
    ]
}

In this configuration, when pressing the toolbar button, for example, when the site https://stackoverflow.com is open, the extension asks for permissions.

enter image description here

This is not the result I expect. I expected the site https://music.yandex.com to open.