Predictive Search Shopify

i have been following the Shopify documentation for implementing the predictive search for the Shopify. You guys can access the documentation from the following link.
https://shopify.dev/docs/themes/navigation-search/search/predictive-search

So my problem is images are rendering only 50px on the search. So since its being rendered only 50px even i make the images bigger with using css images are being blurry.

{%- if predictive_search.performed -%}
  <div id="predictive-search-results">
    {%- if predictive_search.resources.products.size > 0 -%}
      <h3 id="predictive-search-products">
        Products
      </h3>
      <ul role="listbox" aria-labelledby="predictive-search-products">
        {%- for product in predictive_search.resources.products -%}
          <li role="option">
            <a href="{{ product.url }}">
              {{ product | image_url: width: 50 | image_tag }}
              <span>{{ product.title }}</span>
            </a>
          </li>
        {%- endfor -%}
      </ul>
    {%- endif -%}
    <button>
      Search for “{{ predictive_search.terms }}”
    </button>
  </div>
{%- endif -%}

I did tried many things for the following part but any change i made from here not effecting at all.

{{ product | image_url: width: 50 | image_tag }}

Heres my full code

   <predictive-search>
      <form action="{{ routes.search_url }}" method="get" role="search">
        <input
          id="Search"
          type="search"
          name="q"
          placeholder="Search Products"
          required
          role="combobox"
          aria-expanded="false"
          aria-owns="predictive-search-results"
          aria-controls="predictive-search-results"
          aria-haspopup="listbox"
          aria-autocomplete="list"
        >
        <input name="options[prefix]" type="hidden" value="last">
        <div id="predictive-search" tabindex="-1"></div>
      </form>
    </predictive-search>

{%- if predictive_search.performed -%}
  <div id="predictive-search-results">
    {%- if predictive_search.resources.products.size > 0 -%}
      <h3 id="predictive-search-products">
        Products
      </h3>
      <ul role="listbox" aria-labelledby="predictive-search-products">
        {%- for product in predictive_search.resources.products -%}
          <li role="option">
            <a href="{{ product.url }}">
              {{ product | image_url: width: 50 | image_tag }}
              <span>{{ product.title }}</span>
            </a>
          </li>
        {%- endfor -%}
      </ul>
    {%- endif -%}
    <button>
      Search for “{{ predictive_search.terms }}”
    </button>
  </div>
{%- endif -%}


<script>
  function toggleSearch() {
  const modalContainer = document.getElementById("modal-container");
  const body = document.body;

  if (modalContainer.style.display === "flex") {
    modalContainer.style.display = "none";
    body.classList.remove("modal-open");
  } else {
    modalContainer.style.display = "flex";
    body.classList.add("modal-open");
  }
}
</script>


<script>
class PredictiveSearch extends HTMLElement {
  constructor() {
    super();

    this.input = this.querySelector('input[type="search"]');
    this.predictiveSearchResults = this.querySelector('#predictive-search');

    this.input.addEventListener('input', this.debounce((event) => {
      this.onChange(event);
    }, 300).bind(this));
  }

  onChange() {
    const searchTerm = this.input.value.trim();

    if (!searchTerm.length) {
      this.close();
      return;
    }

    this.getSearchResults(searchTerm);
  }

  getSearchResults(searchTerm) {
    fetch(`/search/suggest?q=${searchTerm}&section_id=predictive-search`)
      .then((response) => {
        if (!response.ok) {
          var error = new Error(response.status);
          this.close();
          throw error;
        }

        return response.text();
      })
      .then((text) => {
        const resultsMarkup = new DOMParser().parseFromString(text, 'text/html').querySelector('#shopify-section-predictive-search').innerHTML;
        this.predictiveSearchResults.innerHTML = resultsMarkup;
        this.open();
      })
      .catch((error) => {
        this.close();
        throw error;
      });
  }

  open() {
    this.predictiveSearchResults.style.display = 'block';
  }

  close() {
    this.predictiveSearchResults.style.display = 'none';
  }

  debounce(fn, wait) {
    let t;
    return (...args) => {
      clearTimeout(t);
      t = setTimeout(() => fn.apply(this, args), wait);
    };
  }
}

customElements.define('predictive-search', PredictiveSearch);

</script>

how i can avoid expression expected and unterminated string literal in my ejs file,

<button class="btn-remove" onclick="confirmDelete('<%= cartItem._id %>','<%= cartItem.productId.productName.replace(/'/g, '&apos;') %>')"><i class="icon-close"></i></button>

The code is working perfectly, the problem is it is showing a red line in the code editor also
it is showing

"expression expected and unterminated string"

This code is to delete a cart item from the cart, I am using sweetalert when the user clicks on the cart delete button, I want to display the name of the deleted product as a sweetalert .

in the above line everything is working, but just shows a red line in the code editor,

"expression expected and an unterminated string"

How do I write the src correctly?

Hello I’m just starting out with coding and I’m reading this book “Javascript from Beginner to Professional-Laurence_Lars_Svekis”, and I’m having a difficult time following this one specific example because it keeps popping up as an error when I try to run it.

This is the code from the book that I originally inputted the src did not have a ‘<‘ in front of it.

the code in the book resulted in this error.

Then in the code in my notepad I added a ‘<‘ in front of src and it worked.

This was the what I was trying to accomplish and I did it using the extra ‘<‘ before src.

Can someone explain why this happened and why the way the book had it resulted in an error versus what I put.

How to hide all but only selected elements under parent element using Jquery?

I have an HTML structure like the following

<div class="fieldset-wrapper">
  <div data-index="one">...</div>
  <div data-index="two">...</div>
  <div data-index="three">...</div>
  <div data-index="four">...</div>
</div>

I want to keep only the div elements with ‘data-index’ attribute values ‘one’ & ‘three’.
I have tried the following, but it is not working.

$('.fieldset-wrapper div:not([data-index="one"]):not([data-index="three"])').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<div class="fieldset-wrapper">
  <div data-index="one">one</div>
  <div data-index="two">two</div>
  <div data-index="three">three</div>
  <div data-index="four">four</div>
</div>

How should I do this?

multiple use of java script function for diffrent dynemic css Ids

i have a ui frm page where user can add many New sections as much as he wants
and also inside those sections he can add many resources he wants
and also he can change the order of resources using up and down arrow key for that
i have written java script function for up and down arrow key
the problem is that every time user add any new section dynimacally new SectionId is created (for exa =SectionId_1 )like this
and user can add many sections as much as he wants so (SectionId_1) would be every time new i want to write such java script function for fnUpOrderCustomResource ,fnDownOrderCustomResource so that if i change the order of resources using up and down arrow key it identifies each section uniquely on the basis of order length and it don’t get confuse.

function fnUpOrderCustomResource(order) {

if (order == 1) {
//alert(‘You are at first position, you can not move up!’);
swal(“”, “You are at first position, you can not move up!”, “warning”);
return false;
}
else if (order > 1) {
var curr_order = order;
var up_order = order – 1;

var curr_element = $(“.CustomResource .frmResources[data-order='” + curr_order + “‘]”);

var up_element = $(“.CustomResource .frmResources[data-order='” + up_order + “‘]”);

curr_element.css(“order”, up_order);
curr_element.attr(“data-order”, up_order);

up_element.css(“order”, curr_order);
up_element.attr(“data-order”, curr_order);

curr_element.find(“.uparrow”).attr(“onclick”, ‘fnUpOrderCustomResource(‘ + up_order + ‘)’);
curr_element.find(“.downarrow”).attr(“onclick”, ‘fnDownOrderCustomResource(‘ + up_order + ‘)’);

up_element.find(“.uparrow”).attr(“onclick”, ‘fnUpOrderCustomResource(‘ + curr_order + ‘)’);
up_element.find(“.downarrow”).attr(“onclick”, ‘fnDownOrderCustomResource(‘ + curr_order + ‘)’);

}
}

function fnDownOrderCustomResource(order) {
var order_length = $(“.CustomResource .frmResources”).length;

if (order == order_length) {
//alert(‘You are at last position, you can not move down!’);
swal(“”, “You are at last position, you can not move down!”, “warning”);
return false;
}
else if (order

ESLint disable `no-dupe-keys` doesn’t work

I’m using Typescript and ESLint in my project and I am stuck on a problem with the error: An object literal cannot have multiple properties with the same name.

I just want to disable checking for this error in the line but I don’t know how to do it.

This looks like the no-dupe-keys rule from the docs but for some reason it doesn’t work in my project.

testFetch.ts

import fetch from 'node-fetch';

export function testRequest() {
  const url:string = 'https://example.com/api';
  
  // eslint-disable-next-line camelcase
  const test_camel = 'sd'

  const body = {
    "key[0]": "arr_val_1",
    // eslint-disable-next-line no-dupe-keys
    "key[0]": "arr_val_2",
    // eslint-disable-next-line camelcase
    "key[1]": test_camel,
  }

  fetch(url, {body})
  .then((res) => res.json())
  .then((res) => console.log(res))
  .catch((err) => console.error('error:' + err));
}

I know… but such weird body params are required.

As you can see on the screenshot linter highlights it anyway.

enter image description here

.eslitrc.cjs

/* eslint-env node */
module.exports = {
  extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  root: true,
  rules: {
    "no-dupe-keys": "error",
    camelcase: "error",
  },
  ignorePatterns: [ 
        "test/*", 
        "dist/*",
        ".eslintrc.cjs"
    ],
  // "noInlineConfig": true,
};

Works perfeclty in the playground but not in the real project:

enter image description here

Javascript issues, new to programming

I have written this code to check if the input fields in my login form are empty then it gives me error for each field. The issue in this code is, even when i fill the fields it still gives me the prompt to fill in all required fields. I am new to front end so help will be appreciated. Thanks

document.getElementById(“login”).addEventListener(“submit”, (e) => {
const inputErrors = [];

    inputElements.forEach((inputElement) => {
        const isFieldEmpty = inputElement.value.trim() === "";
        if (isFieldEmpty) {
            setInputError(inputElement, `${inputElement.placeholder} is required`);
            inputErrors.push(inputElement);
        } else {
            clearInputError(inputElement);
        }
    });

    const loginUsername = document.getElementById("loginUsername").value;
    const loginPassword = document.getElementById("loginPassword").value;

    const usernameField = document.getElementById("loginUsername");
    const passwordField = document.getElementById("loginPassword");

    if (loginUsername.length === 0) {
        setInputError(usernameField, "Username or email address is required");
        inputErrors.push(usernameField);
    } else {
        clearInputError(usernameField);
    }

    if (loginPassword.length === 0) {
        setInputError(passwordField, "Password is required");
        inputErrors.push(passwordField);
    } else {
        clearInputError(passwordField);
    }

    // Check for both empty fields and errors
    if (inputErrors.length > 0) {
        e.preventDefault();
        setTimeout(() => {
            alert("Please fill in all required fields.");
        }, 0);
    } else {
        console.log("Form submitted successfully!");
    }
});

I have tried to change the button from submit to button and the eventlistener from submit to click but it gets worse.

how to bring google drive audio to own Htm player?

html audio we use to have our own player and we keepts our audio in google drive and we pest to there with unick code now not working pls look at www.onlinenepalimeeting.org>speakers>

i try to copy unick code
https://drive.google.com/file/d/**1o-OjUnvTCA2Hp9XqsKNEqMJReyIk6Nch**/view?usp=sharing to pest here in url

“name”: “xxxx”,
“artist”: “xxxxx.”,
“album”: “Speakers Topic Meeting “,
“url”: “https://docs.google.com/uc?export=download&id=1o-OjUnvTCA2Hp9XqsKNEqMJReyIk6Nch“,
“cover_art_url”: “https://www.onlinenepalimeeting.org/Untitled.png”
},

this is example of Js. can you guys help me

Assistance Needed with GoogleGenerativeAI Library Script ID for Google Apps Script

I hope this message finds you well. I am writing to seek assistance regarding the
GoogleGenerativeAI Library for use in Google Apps Script.

Recently, I came across Google tutorial on building multi-turn conversations (chat) using the
GoogleGenerativeAI Library, which can be found here:
https://ai.google.dev/tutorials/web_quickstart#multi-turn-conversations-chat.

However, I encountered a challenge while attempting to integrate the GoogleGenerativeAI Library
into my Google Apps Script. As per my understanding, Google Apps Script does not support the
“import” syntax typically used in other JavaScript environments. Instead, it requires a Script ID to
import external libraries.

In light of this, I kindly request your guidance in obtaining the Script ID for the GoogleGenerativeAI Library. This information is crucial for me to successfully implement the library in my Google Apps Script projects.

I would greatly appreciate any help or directions you could provide regarding this matter.
Understanding the steps or process to access the Script ID would enable me to utilize this
powerful tool effectively.

Thank you very much for your time and assistance. I am looking forward to your guidance and am
eager to advance my project with the capabilities of the GoogleGenerativeAI Library.

Warm regards,
YH

Need help for ai generated script [closed]

I tried to run this script, but in my gsheet, it keeps throwing the following exception : range not found. I generated this script using ChatGPT 3.0 and pasted it in app sheet then saved it. I also created button with assigned task within in, but the problem keeps coming.

function copyDataToCompile2Sheet() {
  // Get the active spreadsheet
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  
  // Get the source and target sheets
  var inputSheet = spreadsheet.getSheetByName("INPUT");
  var compile2Sheet = spreadsheet.getSheetByName("COMPILE2");
  
  // Get the values from the source range in "INPUT" sheet (C7:C14 and F7:F14)
  var inputDataRange = inputSheet.getRange("C7:C14,F7:F14");
  var inputValues = inputDataRange.getValues();
  
  // Find the last row in the "COMPILE2" sheet
  var lastRow = compile2Sheet.getLastRow() + 1;
  
  // Get the target range in "COMPILE2" sheet starting from the last row
  var compile2DataRange = compile2Sheet.getRange(lastRow, 1, inputValues.length, inputValues[0].length);
  
  // Set the values in the target range
  compile2DataRange.setValues(inputValues);
  
  // Show a pop-up message
  SpreadsheetApp.getActiveSpreadsheet().toast('Data Terkirim', 'Success');
}

Obtaining the coordinate of a null value when using spanGaps with ChartJS?

I’m wondering if ChartJS exposes an API for plugins that allows us to obtain the coordinate of a null point that has been “Spanned” by ChartJS?

For example as illustrated in this question ChartJS enables smooth curves through null points when settings spanGaps to `true.

So we could have data points like this.

data: [7, null, 11, null,  5 , null,  8, null,   3, null,  7],

Corresponding to these labels.

["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Blue", "Yellow", "Green", "Purple", "Green"],

Is there a way ( Perhaps via the Plugin API ) to get the values of the nulls?

So for a given quadratic curve that chart JS draws for:

data: [7, null, 11, null,  5 , null,  8, null,   3, null,  7],

We could call for example:

const arr = ChartJSPluginAPI.deriveNulls(data);

And get something like:

data: [7, 8, 11, 6,  5 , 6,  8, 4,   3, 5,  7],

Thoughts?

How i do .When switching languages, the error message content appears depending on the active language

How i do .When switching languages, the error message content appears depending on the active language.
Expected result :warning message should displayed in Arabic if language is Arabic
Actual result : warning message displayed in English although language is Arabic

import { AxiosError } from "axios";
import { useEffect, useMemo, useState } from "react";
import { Alert } from "reactstrap";
import { useLanguage } from "../contexts/LanguageContext/languageContext";

interface Props {
  error: unknown;
  onDismiss?: () => void;
}

export const ErrorMessage = ({ error, onDismiss }: Props) => {
  const [isOpen, setIsOpen] = useState<boolean>();
  const { getText } = useLanguage();

  useEffect(() => {
    setIsOpen(true);
  }, [error]);

  const friendlyErrorMessage = useMemo(() => {
    if (typeof error === "string") return error;
    if (error instanceof Error) return error.message;
    return JSON.stringify(error);
  }, [error]);

  const title = useMemo(() => {
    if (typeof error === "string") return error;

    if (error instanceof AxiosError) {
      if (error.code === "ERR_NETWORK") return getText("networkError");
      return error.name;
    }

    return getText("error");
  }, [error, getText]);

  return (
    <Alert
      className="mb-3"
      color="danger"
      toggle={() => {
        setIsOpen(false);
        onDismiss?.();
      }}
      isOpen={isOpen}
    >
      <strong>{title}</strong>
      <hr />
      <pre className="mb-0" style={{ whiteSpace: "break-spaces" }}>
        {friendlyErrorMessage}
      </pre>
    </Alert>
  );
};

Expected result :warning message should displayed in Arabic if language is Arabic
Actual result : warning message displayed in English although language is Arabic

Is there a way to check for missing closing brackets or ; efficiently?

this is a problem I believe many may come across.
When working on code, especially JS, I often loose track of my closing brackets and semicolons. To conquer these annoying issues in my code I am looking for a way to “fix” code where there are brackets missing either within VSCODE or an external program.

Maybe there is an AI for that?

I know stackoverflow isn’t a forum for ‘Looking for program’ posts but since this is directly related to programming I believe many may find it helpful.

When dealing with 300~ lines of code ChatGPT and Copilot are sadly overwhelmed and return mish mash. Maybe I was giving it the wrong prompts…

How to prevent Apps.Microsoft.com cookies with iframe sandbox?

I would like to embed the Microsoft Store (our App page) into our web site, but I don’t want them to create any cookies. How can I display Microsoft App Store information without allowing them to make some tracking cookies.

I have enabled SANDBOX feature like this:

<iframe sandbox="allow-scripts allow-same-origin" src="https://apps.microsoft.com/store/detail/APP NAME">

Enable authorization in express-gateway

I’m having a bit of an issue enabling authorization in express-gateway.

Based on the docs, Express Gateway is designed to apply policies to specific endpoints using its configuration files (gateway-config.yml), and that’s what I’d like to avoid.

I’d like to perform global authentication or authorization for all requests before they reach Express Gateway’s policies, i.e. instead of adding a jwt policy to all my pipelines like this:

pipelines:
  testing:
    apiEndpoints:
      - testing
    policies:
      - jwt:
          - action:
              secretOrPublicKeyFile: certs/key.pem

I would like to intercept all the requests before they reach the gateway, authorize/authenticate, and then forward the request to the gateway for handling the routing to the correct endpoint.

I thought of using Express to handle all the incoming traffic, route the requests to Passport middleware for authentication/authorization, and upon successful authentication/authorization, forward the request to express-gateway.

passport-config.js

const fs = require('fs');
const path = require('path');
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;

const secretKeyPath = path.join(__dirname, '..', 'certs', 'key.pem');
const secretKey = fs.readFileSync(secretKeyPath, 'utf-8');

const jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: secretKey,
};

passport.use(new JwtStrategy(jwtOptions, (payload, done) => {
    const user = payload.user;

    if (user) {
        return done(null, user);
    } else {
        return done(null, false);
    }
}));

module.exports = passport;

middleware.js

const passport = require('./passport-config');

function authenticationMiddleware(req, res, next) {
    passport.authenticate('jwt', { session: false }, (err, user) => {
        if (err || !user) {
            return res.status(401).json({ message: user });
        }
        req.user = user;
        next();
    })(req, res, next);
}

module.exports = authenticationMiddleware;

server.js

const path = require('path');
const gateway = require('express-gateway');
const express = require('express');
const authenticationMiddleware = require('./middleware/auth-middleware');

gateway()
    .load(path.join(__dirname, 'config'))
    .run();

const app = express();

app.use(require('./middleware/passport-config').initialize());

app.use(authenticationMiddleware);

app.listen(8080, () => {
    console.log('Server listening on port 8080');
});

So with the above setup, the requests are going to Express, and Passport is successfully authorizing the requests, but I’m not sure how to send the request through to the gateway after Passport has successfully authorized the request.

Is there a better way of doing this? it looks a bit overkill.