Can’t import named exports; error says that only default export is available

I’m trying to import functions from src/api/api to src/App.js.

Here are all of my import statements in App.js:

import React, { useEffect, useState, useRef } from 'react';

import { fetch_db_files_metadata } from './api/api';
import { fetch_uploads_metadata } from './api/api';
import { start_push_to_DB } from './api/api';
import { start_upload_deletion } from './api/api';
import { start_file_deletion } from './api/api';
import { start_file_download } from './api/api';

import './App.css';

Here are my function headers in api.js:

export const fetch_db_files_metadata = async () => {}
export const fetch_uploads_metadata = async () => {}
export const start_push_to_DB = async () => {}
export const start_upload_deletion = async (upload_deletion_list) => {}
export const start_file_deletion = async (file_deletion_list) => {}
export const start_file_download = async (file_download_list) => {}

There is no export{} or export default{} block at the bottom of api.js. api.js only contains the functions.

React.JS does not compile. Here are the error messages:

ERROR in ./src/App.js 59:32-55
Can’t import the named export ‘fetch_db_files_metadata’ (imported as ‘fetch_db_files_metadata’) from default-exporting module (only default export is available)

ERROR in ./src/App.js 64:34-56
Can’t import the named export ‘fetch_uploads_metadata’ (imported as ‘fetch_uploads_metadata’) from default-exporting module (only default export is available)

ERROR in ./src/App.js 69:33-49
Can’t import the named export ‘start_push_to_DB’ (imported as ‘start_push_to_DB’) from default-exporting module (only default export is available)

ERROR in ./src/App.js 79:34-55
Can’t import the named export ‘start_upload_deletion’ (imported as ‘start_upload_deletion’) from default-exporting module (only default export is available)

ERROR in ./src/App.js 88:35-54
Can’t import the named export ‘start_file_download’ (imported as ‘start_file_download’) from default-exporting module (only default export is available)

ERROR in ./src/App.js 96:32-51
Can’t import the named export ‘start_file_deletion’ (imported as ‘start_file_deletion’) from default-exporting module (only default export is available)

webpack compiled with 6 errors and 1 warning

I tried to remove the curly braces, which allows the app to compile but results in runtime errors stating that the functions are not functions when I try to call them.

Gemini-1.5-pro Node JS API: Error when send an image “Base64 decoding failed”

I am building a chat app with Gemini 1.5 pro Node JS API, when I try to send a message with an image I get this error:

{
field: 'contents[0].parts[2].inline_data.data',
description: `Invalid value at 'contents[0].parts[2].inline_data.data' (TYPE_BYTES), Base64 decoding failed for "data:image/jpeg;base64,/9j/4QAWRXhpZgAATU0AKgAAAAgAAAAAAAD/7QAwUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAABMcAnQAB1BpY29DVEYcA...The rest of the base64 data

NOTE: The error prints a big chunk of the base64 data in the terminal, so i can’t get all the way up to the beggining of the error that’s why you’re seeing parts[2] instead of parts[1].

Here is the code:

if (msg.attachments.size > 0) {
  let imageParts = [];
  let index = 1;

  msg.attachments.forEach((attachment) => {
    var request = require("request").defaults({ encoding: null });

    let image;

    request.get(attachment.url, async function (error, response, body) {
      if (!error && response.statusCode == 200) {
        image = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString("base64");
        var mimeType = attachment.contentType;
        imageParts.push({
          inlineData: {
            data: image,
            mimeType,
          },
        });

        if (msg.attachments.size === index) {
          const generatedContent = await model.generateContent([
            msg.content,
            ...imageParts,
          ]);

          msg.reply(generatedContent.response.text());
        } else {
          index++;
        }
      }
    });
  });
}

Typescript Classes use a static method in a base class typed for any children classes

I am trying to write a wrapper for web components which allows you to use them in JSX by referencing their key; implicitly this will also register the custom element if not done so already so that you don’t forget to.

Is it possible to have some abstract base class which defines a static method, and have children classes which extend this class, and have correct typing when accessing the method.

For example:

abstract class Base {
  static _key: string

  static get key() {
    console.log(this._key)

    return this._key
  }
}

class Child extends Base {
  static _key = "child" as const
}

// Want key to be of type "child", not string
const key = Child.key

If possible, I would prefer to do something like this (because this would allow me to type the props without having to modify IntrinsicElements everywhere), but I’m noticing a similar problem

abstract class Base {
  static _key: string

  static Render(props: any) {
    return "jsx-representation-of-element"
  }
}

class Child extends Base {
  static _key = "child" as const
}

// Some other file, test.tsx
// Expecting that the type is inferred to need Child's props, not Base's
const Component = <Child.Render />

I have been able to get around this by adding static key: typeof this._key to Child but this would require me adding it everywhere, so hoping I can find a solution which doesn’t require this.

For the first part, I looked into using this as a parameter but this can’t be done on getters. I realise I could solve this by making it a normal method, and then calling it once outside the component function, referencing that variable inside the jsx tag, but that seems quite verbose.
I also tried making Base take a generic parameter and returning this in Base.key, ignoring the error about static members and generic types, but this just made the type T (effectively any)

For the second part, I was able to use the this parameter, but as mentioned, the Child.Render function thinks the this type is Base because it’s not been called yet.
Something like

abstract class Base {
  static _key: string

  static Render<T extends typeof Base>(this: T, props: Props<T>) {
    return "jsx-representation-of-element"
  }
}

Obviously, once I call Child.Render(), the types are fine, but this won’t work if using inside a jsx tag.

Is there some tsconfig option I can use to make it default to Child‘s this?

Server-side datatable implementation: how to read the date in dd/mm/yy format from the controller for search

As the title suggests, I am implementing server-side datatable.

I am having a problem with the global search to read birthDate in dd/mm/yy format.

I can only read the date in y-m-d format (i.e. the default date of the db).

This is my code:

        // get data from user_dummies table
        $query = DB::table('user_dummies')->select('*');

        // Global Search
        $search = $request->search;
        $query = $query->where(function ($query) use ($search) {
            $query->orWhere('firstName', 'like', "%" . $search . "%");
            $query->orWhere('lastName', 'like', "%" . $search . "%");
            $query->orWhere('age', 'like', "%" . $search . "%");
            $query->orWhere('birthDate', 'like', "%" . $search . "%");
            $query->orWhere('role', 'like', "%" . $search . "%");
        });

I tried to write the code corresponding to the birthDate put below but I get an error from datatable,

i.e. DataTables warning: table id=datatable – Ajax error.

 $query->orWhere(date('d/m/y',strtotime('birthDate')), 'like', "%" . $search . "%");

Can someone tell me how to do this?

Trouble triggering an Incisor app event with more than one argument

I’m having trouble triggering an Incisor app event with more than one argument.

The console output:

spinResult Defined

spinResult Callback Added

5

undefined (I expect this to read “7777”)

TestAppEvent: CODE VALIDATION FAILED: ‘string=’ expects the parameter ‘string’ to be type ‘string’, but type ‘undefined’ was provided.

How do I get multiple arguments to be available in my callback function?

class ProjectMain
{
    init()
    {
        this.text = new TextAssembly();
        this.text.string = "Build It Once.";

    // Define the event here
        nc.defineAppEvent("spinResult");
        console.log("spinResult Defined");

    // Add the callback for the "spinResult" event
        nc.appEvents.spinResult.addCallback(this, "spinResultCallback");
        console.log("spinResult Callback Added");

    // Trigger the event with multiple arguments
        nc.appEvents.spinResult.trigger(5, "7777");
    }


    /**
    * spinResultCallback
    */
    spinResultCallback(resultData, message)
    {
        console.log(resultData);
        console.log(message);// this should read "7777"
        
        this.text.string = message;

    }
}

creating a multi dimensional array from a two dimensional array

this is what i have and i want to turn it into a multi dimensional array

var calculateDates = function(date1, date2) {
  var dt1 = new Date(date1);
  var dt2 = new Date(date2);
  return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())) / (1000 * 60 * 60 * 24));
}

var startDate = ["10 Jan 1982", "05 Mar 1990", "28 Dec 2001"];
var endDate = ["25 Jan 1982", "06 Mar 1990", "02 Jan 2002"];

var totalDays = 0;

for (var i = 0; i < startDate.length; i++) {
  var days = calculateDates(startDate[i], endDate[i]);
  console.log("Number of days between", startDate[i], "and", endDate[i], "is", days);
  totalDays += days; 
}

console.log("Total number of days:", totalDays);

Problem trying to show an iframe of a website that scales

I am trying to create a website that will show an iframe on the site, which has a panel at the side of it. The main thing that i need is for the iframe to render the website as if it was on a 1920px monitor, regardless of the resolution used by the website viewer. I have attached a few quick mockup images to try explain this, as you can see, when the user drags the window, the iframe site will shrink but keep the same proportions width wise, and scale out, so you can see more of the site at the bottom. Therfore if the user was using 1368×768 as you can see in the other mockup, they would still see how the website would be rendered at 1920px .

I apologise if this is confusing, i have been trying for the last 2 days, but i can never get it to constantly fill the container in which the iframe is in, there are always gaps, or it doesnt scale, or reverts to tablet/mobile versions, all of which i am trying to avoid.

Does anybody have any advice for me, any pointers in which I can try, really appreciate any help

How it should look on a 1920×1080 monitor

How it should look on a 1920×1080 monitor if shrunk in

How it should look on 1368×768 resolution

In terms of code i have tried so many things, the most “successful” is using js, this is what i did, but it didnt work as i liked.

function adjustIframeScale() {
if (iframe && container) {
    const containerWidth = container.getBoundingClientRect().width;
    const scale = (containerWidth * 2) / 1920;
    
    iframe.style.transform = `scale(${scale})`;
    iframe.style.transformOrigin = '0 0';
    
    container.style.height = `${1080 * scale}px`;
    
    // Log values for debugging
    console.log('Scale values:', {
        containerWidth,
        scale,
        scaledHeight: 1080 * scale
    });
}

Trigger file download after fetching the data in an efficient way

Is there any other cross-browser way to trigger a file download after fetching the data using fetch? For now I’m using

const response = await fetch(url);
const blob = await response.blob();
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = 'file';
document.body.appendChild(a);
a.click();
a.remove();

But it first fetches whole file into memory. Is there any way to do it without putting it all into memory first?

problem with fetch.then not completing before response data expected from .then being used in JavaScript [duplicate]

I’m working on a small webapp using nodeJS and express. Client-side script includes the following:

let firstList = []
 
fetch(`${baseUrl}canList`, {
    method: 'GET'
}).then((response) => {
    response.json().then((jsonResponse) => {
        firstList = jsonResponse
    }).catch((err) => {
        console.log(`Error: ${err}`)
    })
})

after fetching data for a second list, The script sets up event listeners for a text input field and a button. Next, I’m trying to use the content of the firstList in the following function:

function start() {
    listBox.innerText = ''
    listContainer = document.createElement('div')
    listContainer.classList.add('text-container')
    listBox.append(listContainer)  
    firstList.forEach(el => {
        const div = document.createElement('div')
        div.innerText = el
        document.querySelector('.text-container').appendChild(div)
    })
    addstyle()

}
start()

My problem is that the .then( response)… handler has not executed to populate the firstList array. instead the .then only starts executing after running through the client script. So the start function iterates over an empty array

otherwise, everything works just fine after this, . The button is used to switch between presenting the first list and second list using a CSS text animation. and the input text field can be used to and an element to be currently displayed list, which is posted back to the node express app and appended to the file accessed using the fetch operations. However,because the start function runs before the array is populated neither list is displayed until the button is clicked.

I’ve tried wrapping the fetch in an async function and then using await as well as writing the fetch .then chain without using the arrow function. I only started learning JavaScript/ node/CSS about a month ago, so please forgive my awkward description

Use external js to trigger click event in Next.js component

I’ve been tasked with making some manual updates in a UI that was built with Next.js. There is an element in the UI that repeats about 1 million times (not really but you get the idea) and I need to click the element to toggle the state.

The selector for the element is easy. I wrote const el = document.querySelector('some-selector') in the console and was able to log out the correct element. Only problem is that when I execute el.click() the element state is not toggled. I also tried el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: false })); with no luck.

For example, I believe Nike’s website uses Next.js. If you go to the home page and open the console, you can select the swoosh icon with this: const swoosh = document.querySelector('.swoosh'). What I need to is to simulate a click on that element from the console.

I assume the problem here is that under the hood, the next.js component has a custom click handler and for whatever reason it is not being triggered unless I physically click the element. Anyone know how I can call the actual next.js click handler with code?

nextjs application goes unresponsive

I am building a nextjs application where i have multiple tabs , table to display data etc. whenever the table code is uncommented the freezing of the code occurs which stops only when i close the tab. tested on browsers: chrome and edge.
i have a very identical code which works absolutely correct.

here is the code

"use client";

import React, { useState, useMemo, Suspense, useCallback, useEffect } from "react";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Tabs, TabsList, TabsTrigger } from "~/components/ui/tabs";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "~/components/ui/table";
import {
  ColumnFiltersState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import {
  Eye,
  Download,
  Pencil,
  Trash2,
  Plus,
  Search,
  ArrowUpDown,
  Import,
} from "lucide-react";
import { Module } from "./types";
import { columns } from "./columns";
import UpdateModuleCard from "./update-module-card";
import QuestionDrawer from "./questionDrawer";
import { useRouter } from "next/navigation";
import { api } from "~/trpc/react";
import CreateModuleCard from "~/components/content/modules/module/questions/CreateModule";

export default function ModulesPage({
  params,
}: {
  params: {
    moduleId: string;
    levelId: string;
    courseId: string;
    country: string;
  };
}) {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = useState({});
  const [searchQuery, setSearchQuery] = useState("");
  const [showUpdateModule, setShowUpdateModule] = useState(false);
  const [selectedModule, setSelectedModule] = useState<Module | null>(null);
  const [selectedTab, setSelectedTab] = useState("questions");
  const [createModule, setCreateModule] = useState(false);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [language, setLanguage] = useState("swedish");

  const {
    data: questions,
    isLoading,
    isError,
  } = api.content.fetchLevel.useQuery({
    id: params.levelId,
    language: language,
    type: "questions",
  });
  const router = useRouter();

  useEffect(() => {
    console.log(params, "params");
    console.log(language, "language");
  }, []);

  
  const table = useReactTable({
    data: questions?.questions || [],
    columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
    },
  });

  const handleTabChange = useCallback((tab: string) => {
    setSelectedTab(tab);
    if (tab === "questions") {
        router.push(
            `/content/country/${params.country}/courses/${params.courseId}/modules/module/${params.moduleId}/level/${params.levelId}/questions`,
        );
    } else if (tab === "theory") {
        router.push(
            `/content/country/${params.country}/courses/${params.courseId}/modules/module/${params.moduleId}/level/${params.levelId}/theory`,
        );
    }
}, [params, router]);


const handleLanguageChange = (value: string) => {
  setLanguage(value as 'swedish' | 'english')
  console.log(value, "value");
};

const handleSearch = (event: React.ChangeEvent<HTMLInputElement>)=>{
  const value = event.target.value
  setSearchQuery(value)
  table.getColumn('name')?.setFilterValue(value)
}

const handleEdit = () => {
  const selectedRows = table.getFilteredSelectedRowModel().rows
  if (selectedRows.length === 1) {
    setSelectedModule(selectedRows[0].original)
    setShowUpdateModule(true)
  }
}

const handleUpdateModule = (e: React.FormEvent) => {
  e.preventDefault()
  // Handle module update logic here
  setShowUpdateModule(false)
}

const handleRowClick = (row: Module) => {
  setSelectedModule(row)
  setIsDrawerOpen(true)
}


  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (isError) {
    return <div>Error</div>;
  }

  return (
    <>
      {showUpdateModule && selectedModule ? (
        <UpdateModuleCard
          module={selectedModule}
          onClose={() => setShowUpdateModule(false)}
        />
      ) : (
        <div className="flex p-8">
          <div
            className={`flex-grow transition-all duration-300 ${isDrawerOpen ? "pr-96" : ""}`}
          >
            <div className="mb-6 flex items-center justify-between">
              <h1 className="text-2xl font-bold">
                {selectedTab === "questions" ? "Questions" : "Theory"}
              </h1>

              <div className="flex space-x-2">
                <Button onClick={()=>{setCreateModule(true); }}>
                  <Plus className="mr-2 h-4 w-4" /> Create{" "} Question
                  {/* {selectedTab === "questions" ? "Question" : "Theory"} */}
                </Button>

                <Button variant="outline">
                  <Import className="mr-2 h-4 w-4" />
                  Bulk Import
                </Button>
              </div>
            </div>

            <Tabs
              value={selectedTab}
              onValueChange={handleTabChange}
              className="mb-6"
            >
              <TabsList>
                <TabsTrigger value="theory">Theory</TabsTrigger>
                <TabsTrigger value="questions">Questions</TabsTrigger>
              </TabsList>
            </Tabs>
            <div className="mb-4 flex items-center justify-between">
              <div className="relative flex items-center">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-500" />
                <Input
                  placeholder="Search..."
                  value={searchQuery}
                  // onChange={handleSearch}
                  className="pl-8 pr-8"
                />
                <Button variant="outline" size="icon" className="ml-2">
                  <ArrowUpDown className="h-4 w-4" />
                </Button>
              </div>
              <div className="flex items-center space-x-2">
                <Button variant="outline" size="icon">
                  <Eye className="h-4 w-4" />
                </Button>
                <Button variant="outline" size="icon">
                  <Download className="h-4 w-4" />
                </Button>
              </div>
            </div>

            <div className="mb-6 flex space-x-2">
              <Tabs
                defaultValue={"swedish"}
                value={language}
                onValueChange={handleLanguageChange}
                className="mx-1 w-full"
              >
                <TabsList>
                  <TabsTrigger value="swedish">Swedish</TabsTrigger>
                  <TabsTrigger value="english">English</TabsTrigger>
                </TabsList>
              </Tabs>
            </div>

            {Object.keys(rowSelection).length > 0 && (
              <div className="mb-4 flex space-x-2">
                <Button variant="outline" size="sm">
                //  onClick={handleEdit}
                 >
                  <Pencil className="mr-2 h-4 w-4" /> Edit
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  className="text-red-500 hover:text-red-700"
                >
                  <Trash2 className="mr-2 h-4 w-4" /> Delete
                </Button>
              </div>
            )}

            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  {table.getHeaderGroups().map((headerGroup) => (
                    <TableRow key={headerGroup.id}>
                      {headerGroup.headers.map((header) =>
                        <TableHead key={header.id}>
                          {header.isPlaceholder
                            ? null
                            : flexRender(
                                header.column.columnDef.header,
                                header.getContext(),
                              )}
                        </TableHead>
                      ))}
                    </TableRow>
                  ))}
                </TableHeader>
                <TableBody>
                  {table.getRowModel().rows?.length ? (
                    table.getRowModel().rows.map((row) => (
                      <TableRow
                        key={row.id}
                        Data-state={row.getIsSelected() && "selected"}
                        onClick={() => handleRowClick(row.original)}
                      >
                        {row.getVisibleCells().map((cell) => (
                          <TableCell key={cell.id}>
                            {flexRender(
                              cell.column.columnDef.cell,
                              cell.getContext(),
                            )}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={columns.length}
                        className="h-24 text-center"
                      >
No results.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>

            <div className="flex items-center justify-between space-x-2 py-4">
              <div className="flex-1 text-sm text-muted-foreground">
                {/* {table.getFilteredSelectedRowModel().rows.length} of{" "}
                {table.getFilteredRowModel().rows.length} row(s) selected. */}
              </div>
              <div className="space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  // onClick={() => table.previousPage()}
                  // disabled={!table.getCanPreviousPage()}
                >
                  Previous
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  // onClick={() => table.nextPage()}
                  // disabled={!table.getCanNextPage()}
                >
                  Next
                </Button>
              </div>
            </div>
          </div>
        { (isDrawerOpen && selectedModule) &&  
        <QuestionDrawer
            isOpen={isDrawerOpen}
            onClose={() => setIsDrawerOpen(false)}
            question={selectedModule}
          />
        }
        </div>
       )} 
      { createModule &&
        // <Suspense fallback={<div>Loading...</div>}>
          <CreateModuleCard
            open={createModule}
            setOpen={setCreateModule}
            levelId={params.levelId}
          />
        // </Suspense>
      )}
    </>
  );
}

here is creating components

"use client";
import React, { useEffect, useState } from "react";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { Switch } from "~/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "~/components/ui/select";
import { Dialog, DialogContent, DialogFooter } from "~/components/ui/dialog";
import Image from "next/image";
import { api } from "~/trpc/react";
import Tiptap from "~/components/global/tiptap";
import { ScrollArea } from "~/components/ui/scroll-area";

export default function CreateModuleCard({
  open,
  setOpen,
  levelId,
}: {
  open: boolean;
  setOpen: (open: boolean) => void;
  levelId: string;
}) {
  const [newItemData, setNewItemData] = useState<Record<string, any>>({});
  const [options, setOptions] = useState<{ text: string; isCorrect: boolean }[]>(
    [],
  );
  const [newOption, setNewOption] = useState<string>("");
  const {
    data: languages,
    isLoading,
    isError,
  } = api.global.fetchAllLanguages.useQuery();
  const createLevelQuestion = api.content.createLevelQuestion.useMutation();

  // useEffect(() => {
  //   if (open && module) {
  //     console.log("Module:", module);
  //     setNewItemData(module);
  //   }
  // }, [open, module]);

  const handleAddOption = (event: React.FormEvent) => {
    event.preventDefault();
    if (newOption.trim() !== "") {
      setOptions([...options, { text: newOption, isCorrect: false }]);
      setNewOption("");
    }
  };

  const handleDeleteOption = (index: number) => {
    setOptions(options.filter((_, i) => i !== index));
  };

  const handleCorrectToggle = (index: number) => {
    setOptions((prevOptions) =>
      prevOptions.map((option, i) =>
        i === index ? { ...option, isCorrect: !option.isCorrect } : option,
      ),
    );
  };

  const handleInputChange = (
    key: string,
    value: string | File | null | boolean | string[],
  ) => {
    console.log(newItemData, "newItemData");
    setNewItemData((prev) => ({ ...prev, [key]: value }));
  };

  const onUpdate = async () => {
    
    console.log(newItemData);
    await createLevelQuestion.mutateAsync({
      levelId: levelId,
      languageId: newItemData.language,
      explanation: newItemData.content,
      question: newItemData.question,
      options: options,
      isHidden: newItemData.isHidden,
    });
    setOpen(false);
  };

  if (isError) return <div>Error</div>;

  return (
    <Dialog open={open} onOpenChange={setOpen} modal={false}>
      <DialogContent className="flex flex-col sm:max-w-[500px] max-h-[700px]" >
        <ScrollArea className="flex-grow overflow-auto">
          <form className="space-y-4">
            <div className="flex space-x-4">
              <div className="flex-1">
                <Label htmlFor="thumbnail">Thumbnail</Label>
                <div className="mt-1 flex items-center">
                  {newItemData.thumbnail && (
                    <Image
                      width={32}
                      height={32}
                      src={newItemData.thumbnail!}
                      alt="Thumbnail"
                      className="mr-4 h-16 w-16 rounded"
                    />
                  )}
                  <Label
                    htmlFor="file-upload"
                    className="cursor-pointer rounded-md bg-white font-medium text-blue-600 hover:text-blue-500"
                  >
                    <span>Upload a file</span>
                    <Input
                      id="file-upload"
                      name="file-upload"
                      type="file"
                      className="sr-only"
                      onChange={(e) =>
                        handleInputChange(
                          "thumbnail",
                          e.target.files?.item.name![0],
                        )
                      }
                    />
                  </Label>
                </div>
              </div>
            </div>

            {/* Dynamic Titles, Slug, and Language */}
            <div className="flex-1">
              <Label htmlFor="slug">Slug</Label>
              <Input
                id="slug"
                value={newItemData.slug}
                onChange={(e) => handleInputChange("slug", e.target.value)}
              />
            </div>
            <div className="flex-1">
              <Label htmlFor="language">Language</Label>
              {isLoading ? (
                <div>Loading...</div>
              ) : (
                <Select
                  value={newItemData.language?.id} // Change to id
                  onValueChange={(value) =>
                    handleInputChange("language", value)
                  } // value will be the id now
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select a Language" />
                  </SelectTrigger>
                  <SelectContent>
                    {languages!.map((lang) => (
                      <SelectItem key={lang.id} value={lang.id}>
                        {" "}
                        {/* Store id instead of name */}
                        {lang.name!}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
            <div className="flex-1">
              <Label htmlFor="language">Question</Label>
              <Tiptap
                className="mt-3 h-[100px]"
                message={""}
                handleMessageChange={(message) =>
                  handleInputChange("question", message)
                }
                isLoadingMessage={false}
                hotReload={false}
              />
            </div>
            <div className="flex-1">
              <div className="mt-4">
                <Label htmlFor="options">Options</Label>
                <div className="mt-2 flex space-x-2">
                  <Input
                    value={newOption}
                    onChange={(e) => setNewOption(e.target.value)}
                    placeholder="Add new option"
                  />
                  <Button type="button" onClick={handleAddOption}>
                    Add Option
                  </Button>
                </div>
                <ul className="mt-4 space-y-2">
                  {options.map((option, index) => (
                    <li key={index} className="flex items-center space-x-2">
                      <Input
                        value={option.text}
                        onChange={(e) =>
                          setOptions((prevOptions) =>
                            prevOptions.map((opt, i) =>
                              i == index
                                ? { ...opt, text: e.target.value }
                                : opt,
                            ),
                          )
                        }
                      />
                      <label class="flex items-center">
                        <input
                          type="checkbox"
                          checked={option.isCorrect}
                          onChange={() => handleCorrectToggle(index)}
                        />
                        <span className="ml-2">Correct</span>
                      </label>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDeleteOption(index)}
                      >
                        Delete
                      </Button>
                    </li>
                  ))}
                </ul>
              </div>
              <Label htmlFor="language">Answer Description</Label>
              <Tiptap
                className="mt-3 h-[250px]"
                message={""}
                handleMessageChange={(message) =>
                  handleInputChange("content", message)
                }
                isLoadingMessage={false}
                hotReload={false}
              />
            </div>
            {/* Additional form inputs */}
            <div className="mt-4 flex items-center space-x-2">
              <Switch
                id="is-hidden"
                defaultChecked={false}
                checked={newItemData.isHidden}
                onCheckedChange={(checked) => {
                  handleInputChange("isHidden", checked);
                }}
              />
              <Label htmlFor="is-hidden">Is Hidden</Label>
            </div>
            <div className="mt-4 flex items-center space-x-2">
              <Switch
                id="is-practice"
                defaultChecked={false}
                checked={newItemData.isPractice}
                onCheckedChange={(checked) => {
                  handleInputChange("isPractice", checked);
                }}
              />
              <Label htmlFor="is-practice">Is Practice</Label>
            </div>
          </form>
        </ScrollArea>
        <DialogFooter>
          <Button type="submit" onClick={()=>{onUpdate()}}>
            Update
          </Button>
          <Button variant="outline" onClick={() => setOpen(false)}>
            Cancel
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

Optional path not working properly in ElysiaJS

I’m trying to implement an optional path, but it doesn’t seem to work. I have the following:

.get('/api/xxx/:param1/:id?', ({ params: { id } }) => `id ${id}`) 

When id is not defined, so /api/xxx/1234, it returns NOT_FOUND (instead of id undefined). (but /api/xxx/1234/1 works properly)

.get('/api/:id?', ({ params: { id } }) => `id ${id}`)

This works if id is undefined, but it is obviously not what I want. I also want :param1 (and possibly more params)

This seems so basic but I can’t get it to work.

Why am I getting a TypeError when adding console.log to my code

I have the following code that works fine:

const user = {
    hello() {
        console.log("Hi:", this)
    }
}

const commonJs = (user) => function() {
    (0, user["hello"])()
}

commonJs(user)()

However, when I add console.log("Running"), I get the error Uncaught TypeError: console.log(...) is not a function:

const user = {
    hello() {
        console.log("Hi:", this)
    }
}

const commonJs = (user) => function() {
    console.log("Running")
    (0, user["hello"])()
}

commonJs(user)()

I don’t understand why this happens since I thought adding a simple console.log would not cause any issues.

I noticed that when I add a semicolon (;) after console.log("Running"), the error disappears:

const user = {
    hello() {
        console.log("Hi:", this)
    }
}

const commonJs = (user) => function() {
    console.log("Running");
    (0, user["hello"])()
}

commonJs(user)()

But I don’t understand why the error occurs without the semicolon.

How can I simulate firefox animation behaviour on chrome when using calcMode=”linear”?

I have two charts, the first one plots two functions, predators and prey. Each containing a circle with an animateMotion that goes along the function path.

The other chart is a phase curve generated by the functions. There is also a circle with an animateMotion that goes along.

Markers on the first graph should have constant speed with respect to X axis. The marker on the second graph should follow along the Y values of the first ones.

On firefox, using calcMode="linear" makes it work:
firefox linear animation.

On chrome, calcMode="linear" behaves the same way as calcMode="paced", so speed is constant along the curve:
chrome “linear” animation.

Including a somewhat ‘minimal’ piece of code, I kept the axis on so it’s easier to understand what’s going on.

<script src="https://d3js.org/d3.v4.js"></script>

<div style="min-width: 100px; max-width: 450px; width:100%">
    <div id="prey_predator_chart" style="width:100%;">
    </div>
    <div id="prey_predator_phase_chart" style="width:100%;">
    </div>
</div>
<script>
let prey_predator = {
    prey_color: "blue",
    predator_color: "green",
    phase_curve_color: "red",
    draw_graph: function() {
        // set the dimensions and margins of the graph
        var margin = {top: 0, right: 40, bottom: 40, left: 40},
            width = 450 - margin.left - margin.right,
            height = 400 - margin.top - margin.bottom;

        var total_width = width + margin.left + margin.right;
        var total_height = height + margin.top + margin.bottom;

        // line graph
        var svg_pop = d3.select("#prey_predator_chart")
            .append("svg")
                .attr("viewBox", "0 0 " + total_width + " " + total_height)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        // phase graph
        svg_pop_phase = d3.select("#prey_predator_phase_chart")
            .append("svg")
                .attr("viewBox", "0 0 " + total_width + " " + total_height)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


        var xDomain = [0,40];
        var yDomain = [0,30];

        var prey_c = {i_density: 10, growth: 1.1, death: 0.4}
        var predator_c = {i_density: 10, growth: 0.1, death: 0.4}
        
        var yScale = d3.scaleLinear().range([height,0]).domain(yDomain);
        var xScale = d3.scaleLinear().range([0,width]).domain(xDomain);

        var yScale_phase = d3.scaleLinear().range([height,0]).domain(yDomain);
        var xScale_phase = d3.scaleLinear().range([0,width]).domain(yDomain);

        var eps = 0.0005
        var x_space = d3.range(xDomain[0], xDomain[1], eps)

        var prey_growth = function(current_prey, current_predator, eps) {
            return prey_c.growth*eps*current_prey - prey_c.death*current_prey*eps*current_predator
        }
        var predator_growth = function(current_prey, current_predator, eps) {
            return predator_c.growth*current_prey*eps*current_predator - predator_c.death*eps*current_predator
        }

        var preys = []
        var predators = []
        preys = [prey_c.i_density]
        predators = [predator_c.i_density]

        x_space.forEach((_, i) => {
            preys.push(preys[i] + prey_growth(preys[i], predators[i], eps))
            predators.push(predators[i] + predator_growth(preys[i], predators[i], eps))
        });

        var c_preys = d3.line()
                .x(function(i) { return xScale(x_space[i]) })
                .y(function(i) { return yScale(preys[i]) })

        var c_predators = d3.line()
            .x(function(i) { return xScale(x_space[i]) })
            .y(function(i) { return yScale(predators[i]) })

        var c_phase = d3.line()
            .x(function(i) {return xScale_phase(preys[i])})
            .y(function(i) {return yScale_phase(predators[i])})

        predators_curve = svg_pop.append('path')
            .attr('stroke', this.predator_color)
            .attr('fill', 'none')
            .attr('stroke-width', 2).attr('d', c_predators(d3.range(0, x_space.length, 1)));

        predators_marker = svg_pop.append('circle')
            .attr('r', 3)
            .attr('stroke', this.predator_color)
        predators_marker.append('animateMotion')
            .attr('repeatCount', 'indefinite')
            .attr('fill', 'freeze')
            .attr('calcMode','linear')
            .attr('dur', '10s')
            .attr('path', c_predators(d3.range(0, x_space.length, 1)));

        preys_curve = svg_pop.append('path')
            .attr('stroke', this.prey_color)
            .attr('fill', 'none')
            .attr('stroke-width', 1).attr('d', c_preys(d3.range(0, x_space.length, 1)));
            
        preys_marker = svg_pop.append('circle')
            .attr('r', 3)
            .attr('stroke', this.prey_color)
        preys_marker.append('animateMotion')
            .attr('repeatCount', 'indefinite')
            .attr('fill', 'freeze')
            .attr('calcMode','linear')
            .attr('dur', '10s')
            .attr('path', c_preys(d3.range(0, x_space.length, 1)));

        phase_curve = svg_pop_phase.append('path')
            .attr('stroke', this.phase_curve_color)
            .attr('stroke-width', 1)
            .attr('fill', 'none').attr('d', c_phase(d3.range(0, x_space.length, 1)));
        phase_marker = svg_pop_phase.append('circle')
            .attr('r', 3)
            .attr('stroke', this.phase_curve_color)
        phase_marker.append('animateMotion')
            .attr('repeatCount', 'indefinite')
            .attr('fill', 'freeze')
            .attr('calcMode','linear')
            .attr('dur', '10s')
            .attr('path', c_phase(d3.range(0, x_space.length, 1)));

        bottomAxis = svg_pop.append("g").attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(xScale));
        bottomAxis.append("text")
                .attr("class", "axis-title")
                .attr("y", 25)
                .attr("dy", ".71em")
                .attr("x", (width+margin.left)/2)
                .style("text-anchor", "end")
                .attr("fill", "black")
                .text("Tiempo");

        leftAxis = svg_pop.append("g")
                .call(d3.axisLeft(yScale));
        leftAxis.append("text")
                .attr("class", "axis-title")
                .attr("transform", "rotate(-90)")
                .attr("y", -30)
                .attr("dy", ".71em")
                .attr("x", -(height-margin.bottom)/2)
                .style("text-anchor", "end")
                .attr("fill", "black")
                .text("Densidad");

        bottomAxis_phase = svg_pop_phase.append("g").attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(xScale_phase));
        bottomAxis_phase.append("text")
                .attr("class", "axis-title")
                .attr("y", 25)
                .attr("dy", ".71em")
                .attr("x", (width+margin.left)/2)
                .style("text-anchor", "end")
                .attr("fill", "black")
                .text("Densidad presa");

        leftAxis_phase = svg_pop_phase.append("g")
                .call(d3.axisLeft(yScale_phase));
        leftAxis_phase.append("text")
                .attr("class", "axis-title")
                .attr("transform", "rotate(-90)")
                .attr("y", -35)
                .attr("dy", ".71em")
                .attr("x", -(height-margin.bottom)/2)
                .style("text-anchor", "end")
                .attr("fill", "black")
                .text("Densidad predador");
        diag_phase = svg_pop_phase.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 1)
            .attr('stroke-dasharray', '5,5')
            .attr('x1', xScale_phase(yDomain[0]))
            .attr('y1', yScale_phase(yDomain[0]))
            .attr('x2', xScale_phase(yDomain[1]))
            .attr('y2', yScale_phase(yDomain[1]))
    }
}
prey_predator.draw_graph();
</script>

Did a manual synchronization using keyTimes and keyPoints, and this does work for the first chart, but I don’t know how to calculate the values for the second one.
This also is a bit cumbersome given how firefox just works.

        get_curve_points = function(curve, n) {
            var points = []
            for (var i = 0; i < n; i++) {
                points.push(curve.node().getPointAtLength(i * curve.node().getTotalLength() / n))
            }
            if (points.length > n) {
                points.pop()
            }
            return points;
        },
        n = 50
        points = get_curve_points(preys_curve, n)
        xs = points.map(p => p.x)
        var min_x = d3.min(xs);
        var max_x = d3.max(xs);
        xs = xs.map(x => (x - min_x) / (max_x - min_x));
        keyTimes = xs.reduce((acc, x) => acc + x + ';', '') + "1"
        keyPoints = d3.range(0,1,1/n).reduce((acc, x) => acc + x + ';', '') + "1"
        preys_marker.append('animateMotion')
            .attr('repeatCount', 'indefinite')
            .attr('fill', 'freeze')
            .attr('calcMode','linear')
            .attr('dur', '10s')
            .attr('keyTimes', keyTimes)
            .attr('keyPoints', keyPoints)
            .attr('path', c_preys(d3.range(0, x_space.length, 1)));


        predators_curve = svg_pop.append('path')
            .attr('stroke', this.predator_color)
            .attr('fill', 'none')
            .attr('stroke-width', 2).attr('d', c_predators(d3.range(0, x_space.length, 1)));

        predators_marker = svg_pop.append('circle')
            .attr('r', 3)
            .attr('stroke', this.predator_color)

        points = get_curve_points(predators_curve, n)
        xs = points.map(p => p.x)
        var min_x = d3.min(xs);
        var max_x = d3.max(xs);
        xs = xs.map(x => (x - min_x) / (max_x - min_x));
        keyTimes = xs.reduce((acc, x) => acc + x + ';', '') + "1"
        keyPoints = d3.range(0,1,1/n).reduce((acc, x) => acc + x + ';', '') + "1"
        predators_marker.append('animateMotion')
            .attr('repeatCount', 'indefinite')
            .attr('fill', 'freeze')
            .attr('calcMode','linear')
            .attr('dur', '10s')
            .attr('keyTimes', keyTimes)
            .attr('keyPoints', keyPoints)
            .attr('path', c_predators(d3.range(0, x_space.length, 1)));


        phase_curve = svg_pop_phase.append('path')
            .attr('stroke', this.phase_curve_color)
            .attr('stroke-width', 1)
            .attr('fill', 'none').attr('d', c_phase(d3.range(0, x_space.length, 1)));
        phase_marker = svg_pop_phase.append('circle')
            .attr('r', 3)
            .attr('stroke', this.phase_curve_color)
        

        phase_marker.append('animateMotion')
            .attr('repeatCount', 'indefinite')
            .attr('fill', 'freeze')
            .attr('calcMode','linear')
            .attr('dur', '10s')

Embed custom GTM (Google Tag Manager) (from clients) in Flutter app access

Scenario:
I have a CRM application made in Flutter/Dart that generates a landing page for the web.
Flutter for the web uses CanvasKit to render and sends a javascript code to the client’s browser.

Requirement:
My users need to count the accesses to this landing page using Google Tag Manager.

I need each client/user to be able to track/count landing page accesses in their own Google Tag Manager accounts.
That’s why I need a way for the CRM application made in Flutter to dynamically consider each client’s Tags. That’s why I believe that using a plugin or package may not be the solution.

Problem:
In the backend, I have a text field where I insert the javascript code snippet from Google Tag Manager that the client sent me. So I’m going to retrieve it to use in my Flutter application, but it seems that CanvasKit doesn’t correctly embed the “external” JS (coming from the text field, which is the GTM JS).

Has anyone experienced this issue?