Adding the WebWorker to the compiler options in tsconfig.json?

I’ve created a starter template / project for Typescript projects and I’m cloning it down and initializing it like this.

git clone https://github.com/fireflysemantics/fs-typescript-starter fs-highlightjs-worker
cd fs-highlightjs-worker 
npm i
npm run build

And the build runs fine. I want this project to use the Web Worker API and this means that WebWorker has to be added to lib under compilerOptions in tsconfig.json like this:

"lib": ["es2021", "DOM", "DOM.Iterable", "WebWorker"],

However if I do this and run the build it now creates these errors.


node_modules/typescript/lib/lib.dom.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImportExportKind, TableKind, ExportValue, Exports, ImportValue, Imports, ModuleImports, ValueType, name, AlgorithmIdentifier, AllowSharedBufferSource, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, CSSKeywordish, CSSNumberish, CSSPerspectiveValue, CSSUnparsedSegment, CanvasImageSource, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, FileSystemWriteChunkType, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, Int32List, MessageEventSource, NamedCurve, OffscreenRenderingContext, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReadResult, ReadableStreamReader, ReportList, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, XMLHttpRequestBodyInit, AlphaOption, AvcBitstreamFormat, BinaryType, CSSMathOperator, CSSNumericBaseType, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ClientTypes, CodecState, ColorGamut, ColorSpaceConversion, CompressionFormat, DocumentVisibilityState, EncodedVideoChunkType, EndingType, FileSystemHandleKind, FontDisplay, FontFaceLoadStatus, FontFaceSetLoadStatus, GlobalCompositeOperation, HardwareAcceleration, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, LatencyMode, LockMode, MediaDecodingType, MediaEncodingType, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PredefinedColorSpace, PremultiplyAlpha, PushEncryptionKeyName, RTCEncodedVideoFrameType, ReadableStreamReaderMode, ReadableStreamType, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestPriority, RequestRedirect, ResizeQuality, ResponseType, SecurityPolicyViolationEventDisposition, ServiceWorkerState, ServiceWorkerUpdateViaCache, TransferFunction, VideoColorPrimaries, VideoEncoderBitrateMode, VideoMatrixCoefficients, VideoPixelFormat, VideoTransferCharacteristics, WebGLPowerPreference, WebTransportCongestionControl, WebTransportErrorSource, WorkerType, WriteCommandType, XMLHttpRequestResponseType

23 interface AddEventListenerOptions extends EventListenerOptions {
   ~~~~~~~~~

  node_modules/typescript/lib/lib.webworker.d.ts:23:1
    23 interface AddEventListenerOptions extends EventListenerOptions {
       ~~~~~~~~~
    Conflicts are in this file.

node_modules/typescript/lib/lib.dom.d.ts:3632:5 - error TS2374: Duplicate index signature for type 'number'.

3632     [index: number]: CSSNumericValue;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:5234:5 - error TS2374: Duplicate index signature for type 'number'.

5234     [index: number]: CSSTransformComponent;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:5290:5 - error TS2374: Duplicate index signature for type 'number'.

5290     [index: number]: CSSUnparsedSegment;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:6471:5 - error TS2374: Duplicate index signature for type 'number'.

6471     [index: number]: string;
         ~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:8412:5 - error TS2374: Duplicate index signature for type 'number'.

8412     [index: number]: File;
         ~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImportExportKind, TableKind, ExportValue, Exports, ImportValue, Imports, ModuleImports, ValueType, name, AlgorithmIdentifier, AllowSharedBufferSource, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, CSSKeywordish, CSSNumberish, CSSPerspectiveValue, CSSUnparsedSegment, CanvasImageSource, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, FileSystemWriteChunkType, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, Int32List, MessageEventSource, NamedCurve, OffscreenRenderingContext, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReadResult, ReadableStreamReader, ReportList, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, XMLHttpRequestBodyInit, AlphaOption, AvcBitstreamFormat, BinaryType, CSSMathOperator, CSSNumericBaseType, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ClientTypes, CodecState, ColorGamut, ColorSpaceConversion, CompressionFormat, DocumentVisibilityState, EncodedVideoChunkType, EndingType, FileSystemHandleKind, FontDisplay, FontFaceLoadStatus, FontFaceSetLoadStatus, GlobalCompositeOperation, HardwareAcceleration, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, LatencyMode, LockMode, MediaDecodingType, MediaEncodingType, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PredefinedColorSpace, PremultiplyAlpha, PushEncryptionKeyName, RTCEncodedVideoFrameType, ReadableStreamReaderMode, ReadableStreamType, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestPriority, RequestRedirect, ResizeQuality, ResponseType, SecurityPolicyViolationEventDisposition, ServiceWorkerState, ServiceWorkerUpdateViaCache, TransferFunction, VideoColorPrimaries, VideoEncoderBitrateMode, VideoMatrixCoefficients, VideoPixelFormat, VideoTransferCharacteristics, WebGLPowerPreference, WebTransportCongestionControl, WebTransportErrorSource, WorkerType, WriteCommandType, XMLHttpRequestResponseType

23 interface AddEventListenerOptions extends EventListenerOptions {
   ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:23:1
    23 interface AddEventListenerOptions extends EventListenerOptions {
       ~~~~~~~~~
    Conflicts are in this file.

node_modules/typescript/lib/lib.webworker.d.ts:1234:5 - error TS2374: Duplicate index signature for type 'number'.

1234     [index: number]: CSSNumericValue;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:1266:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'CSSNumericValue' must be of type '{ new (): CSSNumericValue; prototype: CSSNumericValue; parse(cssText: string): CSSNumericValue; }', but here has type '{ new (): CSSNumericValue; prototype: CSSNumericValue; }'.

1266 declare var CSSNumericValue: {
                 ~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:3664:13
    3664 declare var CSSNumericValue: {
                     ~~~~~~~~~~~~~~~
    'CSSNumericValue' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:1355:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'CSSStyleValue' must be of type '{ new (): CSSStyleValue; prototype: CSSStyleValue; parse(property: string, cssText: string): CSSStyleValue; parseAll(property: string, cssText: string): CSSStyleValue[]; }', but here has type '{ new (): CSSStyleValue; prototype: CSSStyleValue; }'.

1355 declare var CSSStyleValue: {
                 ~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:5189:13
    5189 declare var CSSStyleValue: {
                     ~~~~~~~~~~~~~
    'CSSStyleValue' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:1383:5 - error TS2374: Duplicate index signature for type 'number'.

1383     [index: number]: CSSTransformComponent;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:1424:5 - error TS2374: Duplicate index signature for type 'number'.

1424     [index: number]: CSSUnparsedSegment;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:2247:5 - error TS2374: Duplicate index signature for type 'number'.

2247     [index: number]: string;
         ~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:2763:5 - error TS2374: Duplicate index signature for type 'number'.

2763     [index: number]: File;
         ~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:3075:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'FormData' must be of type '{ new (form?: HTMLFormElement | undefined, submitter?: HTMLElement | null | undefined): FormData; prototype: FormData; }', but here has type '{ new (): FormData; prototype: FormData; }'.

3075 declare var FormData: {
                 ~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:8758:13
    8758 declare var FormData: {
                     ~~~~~~~~
    'FormData' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:4185:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'Notification' must be of type '{ new (title: string, options?: NotificationOptions | undefined): Notification; prototype: Notification; readonly permission: NotificationPermission; requestPermission(deprecatedCallback?: NotificationPermissionCallback | undefined): Promise<...>; }', but here has type '{ new (title: string, options?: NotificationOptions | undefined): Notification; prototype: Notification; readonly permission: NotificationPermission; }'.

4185 declare var Notification: {
                 ~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:16699:13
    16699 declare var Notification: {
                      ~~~~~~~~~~~~
    'Notification' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:5693:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'URL' must be of type '{ new (url: string | URL, base?: string | URL | undefined): URL; prototype: URL; canParse(url: string | URL, base?: string | undefined): boolean; createObjectURL(obj: Blob | MediaSource): string; revokeObjectURL(url: string): void; }', but here has type '{ new (url: string | URL, base?: string | URL | undefined): URL; prototype: URL; canParse(url: string | URL, base?: string | undefined): boolean; createObjectURL(obj: Blob): string; revokeObjectURL(url: string): void; }'.

5693 declare var URL: {
                 ~~~

  node_modules/typescript/lib/lib.dom.d.ts:22904:13
    22904 declare var URL: {
                      ~~~
    'URL' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9187:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onmessage' must be of type '((this: Window, ev: MessageEvent<any>) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: MessageEvent<any>) => any) | null'.

9187 declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
                 ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28270:13
    28270 declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;
                      ~~~~~~~~~
    'onmessage' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9189:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onmessageerror' must be of type '((this: Window, ev: MessageEvent<any>) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: MessageEvent<any>) => any) | null'.

9189 declare var onmessageerror: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
                 ~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28272:13
    28272 declare var onmessageerror: ((this: Window, ev: MessageEvent) => any) | null;
                      ~~~~~~~~~~~~~~
    'onmessageerror' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9216:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'location' must be of type 'Location', but here has type 'WorkerLocation'.

9216 declare var location: WorkerLocation;
                 ~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27594:13
    27594 declare var location: Location;
                      ~~~~~~~~
    'location' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9222:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'.

9222 declare var navigator: WorkerNavigator;
                 ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27611:13
    27611 declare var navigator: Navigator;
                      ~~~~~~~~~
    'navigator' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9224:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onerror' must be of type 'OnErrorEventHandler', but here has type '((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null'.

9224 declare var onerror: ((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null;
                 ~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27967:13
    27967 declare var onerror: OnErrorEventHandler;
                      ~~~~~~~
    'onerror' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9226:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onlanguagechange' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9226 declare var onlanguagechange: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28268:13
    28268 declare var onlanguagechange: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~~~~~~~~~
    'onlanguagechange' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9228:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onoffline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9228 declare var onoffline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28274:13
    28274 declare var onoffline: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~~
    'onoffline' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9230:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'ononline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9230 declare var ononline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28276:13
    28276 declare var ononline: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~
    'ononline' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9231:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onrejectionhandled' must be of type '((this: Window, ev: PromiseRejectionEvent) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null'.

9231 declare var onrejectionhandled: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
                 ~~~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28284:13
    28284 declare var onrejectionhandled: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
                      ~~~~~~~~~~~~~~~~~~
    'onrejectionhandled' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9232:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onunhandledrejection' must be of type '((this: Window, ev: PromiseRejectionEvent) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null'.

9232 declare var onunhandledrejection: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
                 ~~~~~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28288:13
    28288 declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
                      ~~~~~~~~~~~~~~~~~~~~
    'onunhandledrejection' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9238:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'self' must be of type 'Window & typeof globalThis', but here has type 'WorkerGlobalScope & typeof globalThis'.

9238 declare var self: WorkerGlobalScope & typeof globalThis;
                 ~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27695:13
    27695 declare var self: Window & typeof globalThis;
                      ~~~~
    'self' was also declared here.


Found 28 errors in 2 files.

Errors  Files
     6  node_modules/typescript/lib/lib.dom.d.ts:23
    22  node_modules/typescript/lib/lib.webworker.d.ts:23

Any ideas?

Don`t see the next section of page after the fixed slider in NextJs

I have a NextJs component Slider
which is responsible for the fact that when scrolling, the lower section “runs over” the upper section and overlaps it. Here is code:

"use client"

import { useEffect, useState } from 'react';
import UploadSlider from "./UploadSlider";
import RecommendedCandiates from './RecommendedCandiates';
import WorkWithAI from './WorkWithAI';
import UseSupport from './UseSupport';
import FreeVacancy from './FreeVacancy';

const sections = [
    <UploadSlider key="upload-slider" />,
    <RecommendedCandiates key="recommended-candidates" />,
    <WorkWithAI key="work-with-ai" />,
    <UseSupport key="use-support" />,
    <FreeVacancy key="free-vacancy" />
  ];
  
  const Slider = () => {
  const [currentSection, setCurrentSection] = useState(0);
  const [hasStartedSliding, setHasStartedSliding] = useState(false);

  const startedSlidingHandler = (scrollPosition, triggerHeight) => {
    const sectionHeight = window.innerHeight;
    const newSection = Math.min(
    sections.length - 1,
      Math.floor((scrollPosition - triggerHeight / 2.3) / sectionHeight)
    );
    if (newSection !== currentSection) {
      setCurrentSection(newSection);
    }
  }
  
  const handleScroll = () => {
    const scrollPosition = window.scrollY;
    const triggerHeight = document.getElementById('sliding-sections').offsetTop;

    if (scrollPosition >= triggerHeight && !hasStartedSliding) {
      setHasStartedSliding(true);
    }

    if (hasStartedSliding) {
      startedSlidingHandler(scrollPosition, triggerHeight);
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [currentSection, hasStartedSliding]);

  return (
    <>
      <div id="sliding-sections" className="relative">
        <div  style={{height: `${sections.length * 100}vh `}}>
          <div className="min-h-screen">
            {sections[0]}
          </div>
        </div>

        {sections.slice(1).map((section, index) => (
          <div
            key={index + 1}
            className={`fixed top-0 w-full h-full transition-transform duration-1000 ease-in-out transform ${
              hasStartedSliding && currentSection >= index + 1 ? 'translate-y-0' : 'translate-y-full'
            }`}
          >
            {section}
          </div>
        ))}
      </div>
    </>
  );
};

export default Slider;

But the problem I have is that when I place another section under this component on the same page, it is not visible because the slider covers its content.
As far as I understand, this is due to the fact that I define fixed top-0 for the sections in the slider.

Here is page.js code

import EmployerHeader from "@/components/employer/EmployerHeader";
import MainSection from "@/components/employer/MainSection";
import ResumeBase from "@/components/employer/ResumeBase";
import Slider from "@/components/employer/sliders/Slider";
import Reviews from "@/components/employer/Reviews";

export default function Home() {
    return(
        <div className="w-full">
            <EmployerHeader />
            <MainSection />
            <ResumeBase />
            <Slider />
            <Reviews />   
        </div>
    )
}

In my case the Reviews section hides under the Slider component

If I change fixed to absolute, scrolling stops working for me. How can I fix this?

file opener 2 is not working with api level 34 (Android 14)

I am trying to open a pdf file just after downloading it via cordova file transfer plugin. Even after downloading it and passing the exact same path in fileOpener2.open function, i am getting file not found. It does not matter where the file is being stored i just want the file to be displayed just after the download button click.

i tried using every cordova.file.* to set a path for download and use the same path to open but i am getting the same error since. If fileopener2 is not convenient i am okay to use another plugin just to open a downloaded pdf file. I know about the scoped storage stuff in new androids and fileopener2 is not maintained now but i want something to work as the task is extremely simple but due to lack of knowledge in android dev, i am unable to achieve this for the past 2 weeks. I want for both android and ios.

Below is my current code

function downloadFile() {
// Remote URL of the PDF file
var fileUrl =
“”;

      // Local filesystem URL where the file will be saved
      var targetPath =
        cordova.file.externalApplicationStorageDirectory +
        "CRS_Form" +
        ".pdf"; // You can change the target path as needed

      // Check if the FileTransfer plugin is available
      if (typeof FileTransfer !== "undefined") {
        // Initialize the File Transfer Plugin
        var fileTransfer = new FileTransfer();

        // Define the options for the download
        var options = {
          trustAllHosts: true, // Set this to true if you're using a self-signed SSL certificate
        };

        // Start the download
        fileTransfer.download(
          fileUrl,
          targetPath,
          function (entry) {
            // Success callback
            console.log("Download success! File saved to: " + entry.toURL());
            // You can perform additional actions here after successful download
            cordova.plugins.fileOpener2.open(targetPath, "application/pdf", {
              error: function (e) {
                console.log(
                  "Error status: " +
                    e.status +
                    " - Error message: " +
                    e.message
                );
              },
              success: function () {
                console.log("file opened successfully");
              },
            });
          },
          function (error) {
            // Error callback
            console.error("Download error: " + JSON.stringify(error));
          },
          options
        );
      } else {
        // Handle the case when the FileTransfer plugin is not available
        console.error("FileTransfer plugin not available.");
      }
    }

getting error: file not found in the line

cordova.plugins.fileOpener2.open(targetPath, “application/pdf”, {
error: function (e)

Dynamic recursive treeview using nested-mat-tree by fetching data from rest api and json file alternatively

I’m trying to populate a dynamic treeview using nested-mat-tree.

The tree view alternates between fetching data from an API and displaying child nodes from a JSON file as you toggle through the levels. Here’s a recap:

First Level:
API Call: Fetch data from Spring Boot.
Display Data: Show fetched data.
Toggle: Reveals child nodes from a JSON file.

Next Level:
Toggle JSON Data: Triggers an API call with different end-point based on condition.
API Call: Fetch more data.
Display Data: Show the newly fetched api data.

Further Levels:
Toggle API Data: Displays child nodes from JSON again.
Repeat: This process continues indefinitely.
This ensures that the tree view dynamically switches between API calls and JSON data at each level of expansion.

Please provide if any reference for this case.

treeview.html

<div class="split-container">
  <div class="subpanel">
    <!-- Header for the Tree View section -->
    <div class="subpanel-header">Tree-View </div>
    <!-- Body of the Tree View section -->
    <div class="subpanel-body" id="subpanel-body">
      <!-- Angular Material Tree component -->
      <mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
        <!-- Tree node template for leaf nodes -->

        <!-- Tree node template for expandable nodes -->
        <mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">
          <div class="mat-tree-node">
            <button class="mat-icon-button-custom" (click)="onParentToggle(node)">
              <mat-icon>{{ treeControl.isExpanded(node) ? 'remove' : 'add' }}</mat-icon>
            </button>
            <button mat-button class="trail-button" (click)="attrVisualization(node)">
              {{ node.name.type?.toUpperCase().slice(0, 3) }}
            </button>
            <mat-icon class="status-icon" [ngStyle]="{'color': getIconColor(node)}">fiber_manual_record</mat-icon>
            {{node.name.name}}
          </div>
          <ul [class.example-tree-invisible]="!treeControl.isExpanded(node)">
            <ng-container matTreeNodeOutlet></ng-container>
          </ul>
        </mat-nested-tree-node>

        <!-- Tree node template for leaf nodes -->
        <mat-nested-tree-node *matTreeNodeDef="let node">
          <div class="mat-tree-node" (click)="onChildToggle(node)">
            <button class="mat-icon-button-custom">
              <mat-icon>{{ treeControl.isExpanded(node) ? 'remove' : 'add' }}</mat-icon>
            </button>
            {{node.name.name}}

            <ul [class.example-tree-invisible]="!treeControl.isExpanded(node)" *ngIf="node.children">
              <ng-container matTreeNodeOutlet>
                <ul *ngFor="let child of node.children">
                  <button class="mat-icon-button-custom" (click)="onChildToggle(child)">
                     <mat-icon>{{ treeControl.isExpanded(child) ? 'remove' : 'add' }}</mat-icon>
                   </button>
                 {{child.name.name}}
                </ul>
              </ng-container>
            </ul>
            
          </div>
        </mat-nested-tree-node>

      </mat-tree>
    </div>
  </div>

treeviewcomponent.ts

export interface TreeNode {
  name: {
    [key: string]: any;
  };
  children?: TreeNode[];
  parentId?: string; // Ensure parentId is defined in the interface
  parentDetails?: TreeNode;
}

@Component({
  selector: 'app-treeview',
  templateUrl: './treeview.component.html',
  styleUrls: ['./treeview.component.css']
})
export class TreeviewComponent implements OnInit {
  openTreeView = false;
  selectedNode: TreeNode | null = null;
  LocationData: any;
  treeChildren: any;
  apiData: any;

  treeControl = new NestedTreeControl<TreeNode>(node => node.children);
  dataSource = new MatTreeNestedDataSource<TreeNode>();

  constructor(
    private router: Router,
    private treeviewService: TreeviewService,
    private popUpService: PopUpServiceService,
    private http: HttpClient
  ) { }

  ngOnInit(): void {
    this.apiData = this.popUpService.getData(); //this is api data called to display top level nodes
    console.log('apiData Data:', this.apiData);

    this.apiData = JSON.parse(this.apiData);

    this.treeviewService.fetchJsonData().subscribe((jsonData: any) => {
      console.log('JSON Data:', jsonData[this.apiData[0].type]);

      const combinedData: TreeNode[] = this.apiData.map((item: any) => ({
        name: item,
        children: this.createTreeChildren(item.id, jsonData[this.apiData[0].type])
      }));

      this.dataSource.data = combinedData;
      console.log('DataSource:', this.dataSource.data);
    });
  }

  createTreeChildren(parentId: string, childrenData: any[]): TreeNode[] {
    return childrenData.map((child: string) => ({
      name: { name: child },
      parentId: parentId // Add parentId to each child node
    }));
  }

  hasChild = (_: number, node: TreeNode) => !!node.children && node.children.length > 0;


  onParentToggle(node: TreeNode): void {
    console.log("Toggling node:", node.name?.['id']);

    if (this.treeControl.isExpanded(node)) {
      this.treeControl.collapse(node);
    } else {
      this.treeControl.expand(node);
    }

    if (this.hasChild(0, node)) {
      this.assignParentToChildren(node);
    }
  }

  onChildToggle(node: TreeNode): void {
    console.log('Child Node parentType:', node);
    console.log('Child Node parentID:', node.parentId);
    console.log('Child Node name:', node.name['name']);

    if (this.treeControl.isExpanded(node)) {
      this.treeControl.collapse(node);
    } else {
      this.treeControl.expand(node);

      // Fetch sub-child nodes using childDetailapi
      this.treeviewService.childDetailapi(node.name['name'], node.parentId || '')
        .subscribe(response => {
          console.log('detail view Response:', response);

          // Create sub-child nodes
          const subChildren: TreeNode[] = response.map((subChild: any) => ({
            name: subChild,
            parentId: node.parentId,
          }));

          // Check if node already has children, if so, add the new ones
          if (node.children) {
            node.children.push(...subChildren);
          } else {
            node.children = subChildren;
          }

          // Refresh the data source to update the view
          this.dataSource.data = this.dataSource.data.slice();
        }, error => {
          console.error('API Error:', error);
        });
    }
  }


  findParentNode(childNode: TreeNode): TreeNode | null {
    for (const parentNode of this.dataSource.data) {
      if (parentNode.children && parentNode.children.some(child => child.name['name'] === childNode.name['name'])) {
        return parentNode;
      }
    }
    return null;
  }

  assignParentToChildren(parentNode: TreeNode): void {
    if (parentNode.children && parentNode.children.length > 0) {
      parentNode.children.forEach(childNode => {
        childNode.parentDetails = parentNode;
        this.assignParentToChildren(childNode);
      });
    }
  }

  getIconColor(node: any): string {
    switch (node.type) {
      case 'trail':
        return 'green';
      case 'port':
        return 'purple';
      case 'ne':
        return 'orange';
      default:
        return 'RGB(146,206,18)';
    }
  }
}
 

treeview service


@Injectable({
  providedIn: 'root'
})
export class TreeviewService {

   private jsonUrl = 'assets/properties.json';

  constructor(private http: HttpClient) { }

   fetchJsonData(): Observable<any> {
     return this.http.get<any>(this.jsonUrl);
   }


   childDetailapi(childType: string, parentId: string): Observable<any> {
    let apiUrl = '';

    switch (childType) {
      case 'Trail':
        apiUrl = `http://localhost:8080/pipe/locationId/${parentId}`;
        console.log(apiUrl);
        break;
      case 'Physical Device':
        apiUrl = `http://localhost:8080/physicalDevice/locationId/${parentId}`;
        
        console.log(apiUrl);
        break;
      case 'Leased Line':
        apiUrl = `http://localhost:8080/leasedLine/locationId/${parentId}`;
        
        console.log(apiUrl);
        break;
      default:
        throw new Error('Unknown child type');
    }

    return this.http.get(apiUrl);
  }
  

}

How do I get React CountUp to count from a previous number?

I am new to React and am using the React CountUp to animate a number counting up, eg:

<CountUp end={totalAmount} />

This works – whenever totalAmount is changed CountUp will animate a count from 0 to whatever the new number is.

However, I want to animate it to count from whatever the previous number was. For example if the totalAmount changes from 70 to 100 I want the animate just to count from 70. As it is now, whatever totalAmount changes to it will always start at 0.

I see there is an update prop available, but I am unsure how to use it. I have tried:

<CountUp end={totalAmount} update={totalAmount} />

I see there is a way to do this in a “hook”, but to be honest have no idea how to incporporate a hook into my broader React component.

Would anyone be able to point me in the right direction at all?

How to capture Tab + Escap key combinations in angular?

When the user pressed Tab + Escape key then I wanted to call my function but I couldn’t capture this combination. If this combination is not possible then I want one combination with Escape key but those combination are not used in Windows, Ubuntu and Mac.

I tried like this:

@HostListener('window:keydown', ['$event'])
async onkeyDown($event: KeyboardEvent) {
  if($event.key === 'Tab' && $event.code === 'Escape') {
    console.log('Tab + Escape keys pressed');  
  }
} 

I want to capture Tab + Escape key combination.

html and php load child select using parent select

i need some help in loading the child select based on the master select. Like i want to load the states based on the country select in the first place.

<div class="form-group">
<label for="customerID" class="col-sm-3 control-label">Customer</label>
<div class="col-sm-9">
<select class="form-control" name="countryName[]" id="countryrName">
<option value="">~~SELECT~~</option>
<?php
$countrySql = "SELECT * FROM countries WHERE transactionstatus='1' and companyid='1'";
$countryData = $connect->query($countrySql);

while($row = $countryData->fetch_array()) {                                            
echo "<option value='".$row['countryid']."' id='changeCustomer".$row['countryid']."'>".$row['countryname']."</option>";
} // /while 

?>

</select>
</div>
</div> <!--/form-group-->             
<div class="form-group">

Adding the highlightjs API interface to self in a web worker?

I’m coding a web worker in Typescript and this works:

onmessage = (e) => {
    importScripts(
      'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.10.0/highlight.min.js'
    );
    const language = e.data.language;
    const result = language
      ? (self as any).hljs.highlightAuto(e.data.code, { language })
      : (self as any).hljs.highlightAuto(e.data.code);
    postMessage(result.value);
  };

I’m curious if there is a way to type self more strictly with the types from @types/highlightjs?

Why do most components – or even the browser – only offer to set the locale but not regional formatting?

In MacOS, Windows and Linux you can set your preferred language, e.g. en-US but also choose a region for formatting.

For example, I’ve set my MacOS to en-US but with German formatting.

In JavaScript there’s no possibility to get both OS settings.

  • navigator.language returns en-US.
  • Intl.DateTimeFormat().resolvedOptions().locale returns en-GB (for whatever reason? Chrome’s language setting is en-US)

I’ve also noticed that MacOS is doing it wrong. In its menu bar it currently shows “Wed Sep 4” which is not in German formatting. When changing the OS language to “en-GB” it changes to “Wed 4. Sep” – so it’s clearly using the language setting and not my regional preference for formatting. Also, shouldn’t it be Mi 4. Sept. which would be the real German formatting?

Now, when it comes to using components, most of them only offer a locale, so any formatting is derived from the language.

Why do most components (or even apps) not allow you to set preferences for formatting? Is it uncommon for most people to use a language with a different regional formatting?

Or is my understanding of how it should work wrong?

Wikipedia scrolls up on mouse text selection

When I try to select a word of text in the top 5% of the page in any English Wikipedia article (Example page) in Chrome, the page automatically starts scrolling up, even if the mouse pointer is far from the top edge of the page. How can I prevent this unwanted scrolling with user CSS/JS?

Trying to select "MA Cantab" on the page

Same behavior in Firefox and Safari. This doesn’t happen in other wikipedias, like German.

Redux project delete button isn’t working

I’m working on redux project that has add to card button and delete item from card. The delete button isn’t working and when I check with console.log it’s adding item to card. I’m trying to fix it but it’s not working.

I’m adding the code that I have below

import { createSlice } from "@reduxjs/toolkit";

export const slice = createSlice({
  name: "recipeCart",
  initialState: {
    itemsInCart: []
  },
  reducers: {
    addItemToCard: (state, action) => {
      const timeId = new Date().getTime()
      state.itemsInCart.push({
        idFood: timeId,
        dishId: action.payload.dish.idFood,
        quantity: action.payload.quantity,
        totalPrice: action.payload.quantity * action.payload.dish.price
      })
    },
    removeItemFromCart: (state, action) => {
      state.itemsInCart = state.itemsInCart.filter(
        itemsInCart => itemsInCart.idFood !== action.payload.itemsInCartId
      )
    }
  }
})

export const getTotalPrice = state => {
  return state.recipeCart.itemsInCart.reduce((total, itemsInCart) => {
    return itemsInCart.totalPrice + total
  }, 0)
}

export const getCartItems = state => state.recipeCart.itemsInCart;
export const { addItemToCard, removeItemFromCart } = slice.actions;
export default slice.reducer
import dishesData from "../data/dishesData";
import { removeItemFromCart } from "../redux/cartSliceFood.js";
import { useDispatch } from "react-redux";

const CartItemFood = ({ itemsInCart }) => {
  const recipeDishes = dishesData.find(
    item => item.idFood === itemsInCart.dishId
  )
  const dispatch = useDispatch();
  console.log(recipeDishes)
    
  return (
    <div>
      <div className="headerCart">
        <div className="container-cart"> 
          <p className="cartPar">{recipeDishes.name}</p>
          <p className="cartPar">{itemsInCart.quantity} portion(s)</p>
          <p className="cartPar price">
            Price: ${recipeDishes.price * itemsInCart.quantity}
          </p>
          <span
            onClick={() => dispatch(removeItemFromCart({
              itemsInCartId: itemsInCart.id
            }))}
          >
            <img
              className="icon cartPar"
              src="https://img.icons8.com/material-outlined/48/000000/trash--v1.png"
              alt="icon"
            /> 
          </span>
        </div>
      </div>
    </div>  
  )
}

export default CartItemFood;
import { configureStore } from '@reduxjs/toolkit';
import dishes from './DessertComponent/redux/dishesSlice';
import cart from './DessertComponent/redux/cartSlice';
import recipeDishes from './FoodComponent/redux/dishesSliceFood';
import recipeCart from './FoodComponent/redux/cartSliceFood'

export const store = configureStore({
  reducer: {
    dishes: dishes,
    cart: cart,
    recipeDishes: recipeDishes,
    recipeCart: recipeCart
  }
})

Trouble getting a value from a website using Google Apps Script and Regex

I’m trying to get the value of the current week from the ESPN NFL schedule (https://www.espn.com/nfl/schedule). Week 1 is in the center of the wrapper in the top half of the page. I’m using GAS since I’ve connected this to google sheets/google forms. I’ve been able to get the values in the tables (the schedule), but I can’t get this value from outside the tables.

I’ve found a regex expression that should find the value that I want. I tested it using regex101 here: https://regex101.com/r/xDJCXT/1

var url = 'https://www.espn.com/nfl/schedule';
var html2 = UrlFetchApp.fetch(url).getContentText();
var regex = /class=["']bcustom--week is-activeb.*?range["]>(.*?)<//gm;
var weekNum = html2.match(regex);
console.log(weekNum);

However, my code is outputting “null” in the console

javascript in Adobe Animate frames

To learn and experiment with JavaScript I am using the following approach/structure:
I have individual blocks of code in several individual frames, all of them in one Action named layer.
This way I can have only one Animate file to contain all my testing.

On frame One I have the following code:

this.stop()  //this is optional HERE
alert("Frame ONE")

//frame number to go to
    var myFrame = nn //(I replace nn with either 5, 10, 15, 20, 25 etc)
//5 10 15 etc are the frame numbers where I have JS code

myFrame -= 1     //create.js => frame number - 1
this.gotoAndPlay(myFrame);

When I run the above code (CTRL+Enter) with any valid nn value, a new tab is opened BUT the expected code does not execute.

I am getting these error msgs in Chrome:

Uncaught SyntaxError: Unexpected token ‘)’ SandBoxt.js:3520
and
Uncaught ReferenceError: AdobeAn is not defined SandBoxt.html?10700:24
at init (SandBoxt.html?10700:24:11)
at onload (SandBoxt.html?10700:48:44)

My impression is that all (my currently fifteen blocks of) code in individual frames are checked regardless of which individual block I am trying to excute.
Nowhere do I have a 3520 line number. (This is, I guess, a cumulative line count).

I would like to hear from you people a suggestion on a clever/efficient way to find the offending line.
Thank you all very much in advance.

I am trying to comment each entire code in frame one by one but I still could not find the error.

How to click an element without navigating away from the page

I would like to ask whether it is there a way for you to select an element without going to be navigate away,

I am new to coding , I trying to automate the unfollowing button. in instagram

unfolllow

let say I wanted to unfollow all by dbclick the “following” , can I just run my code on homepage URL?

https://www.instagram.com/_chaeboll/ — home page url
https://www.instagram.com/_chaeboll/following/ — after clicking following

const unfollow = document.querySelectorAll("following")

unfollow.forEach(() => { runing the code to click the button})
  • as the element isnt in home page , it will returned undefined, but i hope there is away when something happen in background which navigate away to the following URL and execute the code.

I know u can use the deobfuscate/debuggger to find the function which are called to do the action, but it is to advance for me to find the function

Im building it as extension in content.js

if there is isnt , is there any resources that teaches the process of automating things for me to learn more about finding the way to deobfuscate