Inertiajs & Vue Component Library

I recently embarked on creating a custom component library in Vue 3, driven by the desire to repurpose some meticulously crafted UI components from a previous project I developed using the Laravel + Inertia + Vue 3 stack. In that project, I invested significant time and effort into refining the user interface, and I was so pleased with the outcome that I decided to extract these components into a standalone library. The goal was to ensure that the same high-quality, well-designed components could be easily reused across different projects without needing to start from scratch each time.

However, I’ve encountered a problem while integrating the library into my main project. Specifically, when I attempt to use Inertia’s <Link /> component, it throws an error, halting the process. This issue has become a roadblock, and I’m trying to understand how to resolve it so that I can fully leverage the components I’ve worked so hard to perfect.
Error when I click a link

This is my Link.vue component from the vue-inertia-core library.


<script setup>
import { Link } from "@inertiajs/vue3";
</script>

<template>
    <Link class="text-sm font-bold leading-tight">
        <slot></slot>
    </Link>
</template>

<style scoped></style>

This is the vite.config.js file of the vue-inertia-core library:

import { resolve } from "path";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": "/src",
      "@assets": "/src/assets",
    },
  },
  css: {
    postcss: resolve(__dirname, "postcss.config.js"),
  },
  build: {
    lib: {
      entry: resolve(__dirname, "src/index.js"),
      name: "VueInertiaCore",
      fileName: "vue-inertia-core",
    },
    rollupOptions: {
      external: ["vue"],
      output: {
        globals: {
          vue: "Vue",
        },
      },
    },
  },
});

and this is the vite.config.js file from the original project where I linked this package.

import laravel from "laravel-vite-plugin";
import vue from "@vitejs/plugin-vue";

const inDevelopment = process.env.NODE_ENV === 'development';

export default defineConfig({
    plugins: [
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
        laravel({
            input: [
                "resources/inertia/css/app.css",
                "resources/inertia/js/app.js",
            ],
            refresh: true,
        }),
    ],
    resolve: {
        alias: {
            "@": "/resources/inertia/js",
            "@assets": "/resources/inertia/assets",
            "@mosaict/vue-inertia-core": inDevelopment ? "@mosaict/vue-inertia-core-dev" : "@mosaict/vue-inertia-core",
            vue: "vue/dist/vue.esm-bundler.js",
        },
    },
});

Any help would be much appreciated. If you need more information, please tell me.

I tried to resolve those components manually but I don’t know what to do. I just want the component from the library to be able to work properly.

Set cursor pos in contenteditable innerHTML

I saw this question

Contenteditable Div – Cursor position in terms of innerHTML position

with an answer that worked perfectly, but now I just need something that can set cursor position while including length of element tags, or maybe something that would just count and add the length of tags before the pos I’m trying to set the cursor.

I tried using the regular method of setting cursor pos in a contenteditable but it didn’t work obviously as it doesn’t consider element tag lengths.

redo and undo functions are not working properly

I am working on drawing app project but when i added redo and undo functions to the app which did not work and undo is working but redo is not working

I tried to solve this problem and I changed the code of undo and redo and also save state function however still redo is not working properly

How to align Nivo Bar chart label position to end of bar?

Hi I am trying to align the labels of my bar chart to the far right of the bar but haven’t been able to do so yet. The docs for Nivo Bar suggests I use a labelPosition="end" property but on my code apparently, it does not exist.

Here is my current output

CURRENT OUTPUT

As you can see the labels are centred inside the bars, whereas the design its at the outside end of the bars.

Here is the design I need to follow

DESIGN

Below is my current code

import { ResponsiveBar, type ComputedDatum } from '@nivo/bar'
import { useTheme } from '@nivo/core'
import { Card } from 'antd'

 <Card
        title={`${direction} ${data?.length ?? 20} ${metric} by total units`}
        style={{ boxShadow: '0px 4px 4px rgba(0, 0, 0, 0.2)' }}
        bodyStyle={{
          height: '800px',
          padding: '32px',
        }}
        loading={isLoading}
      >
        <ResponsiveBar
          data={data ?? []}
          margin={{ top: 0, right: 15, bottom: 30, left: leftMargin }}
          padding={0.4}
          colors="#0E8156"
          layout="horizontal"
          isInteractive={true}
          axisTop={null}
          axisBottom={{
            tickSize: 4,
            tickPadding: 4,

            legend: 'units',
            legendPosition: 'middle',
            legendOffset: 40,
          }}
          axisLeft={{
            renderTick: ({ tickIndex, x, y }) => (
              <LeftTick
                x={x}
                y={y}
                text={data?.[tickIndex]?.name ?? ''}
                id={data?.[tickIndex]?.id ?? 0}
              />
            ),
          }}
          labelPosition="end" // PROP I AM TRYING TO USE BUT ERROR
          labelSkipWidth={12}
          labelSkipHeight={12}
          labelTextColor={{ from: 'color', modifiers: [['brighter', 10.0]] }}
          animate={true}
          onClick={handleSetQuery}
        />
      </Card>

//ERROR Property 'labelPosition' does not exist on type 'IntrinsicAttributes & ResponsiveBarSvgProps<{ value: number; id: number; name: string; }>'.ts(2322)

Here is my package.json

"@nivo/bar": "^0.87.0",
"@nivo/calendar": "^0.87.0",
"@nivo/core": "^0.87.0",

Has anyone come across this error? Nivo docs seems to be giving incorrect prop information if they say to use labelPosition which doesn’t exist, or maybe I am using the wrong version. Is there any fix for this? Thanks

How to Auto-Size AG Grid Columns to Fit Cell Contents with a Max Width Restriction?

I’m working with AG Grid in JavaScript, and I want to implement the following behavior:

When the grid is first loaded, I want the columns to auto-size based on the content, but with a maximum width restriction.

How can I achieve this?

I’m aware of the fitCellContents option, which adjusts the column size according to the content:

autoSizeStrategy: {
    type: 'fitCellContents'
}

However, according to the Ag Grid documentation, using fitCellContents doesn’t allow setting a maximum column width.

Important:

  • I don’t want to use defaultMaxWidth in the column definition since I want users to be able to resize the columns later.

Problem with connecting my metamask to my dapp frontend

When I click on connect wallet button, my metamask wallet is opening and asking for permission to connect the wallet. However, even after I connect it, the application isn’t showing that there is no account connected.

This is my components/ManualHeader.js file:


import { useMoralis } from "react-moralis"
import { useEffect, useState } from "react"

export default function Header() {
const { enableWeb3, account, isWeb3Enabled } = useMoralis()
const [isConnected, setIsConnected] = useState(false)

    useEffect(() => {
        console.log("isWeb3Enabled:", isWeb3Enabled)
        console.log("account:", account)
        if (account && isWeb3Enabled) {
            setIsConnected(true)
        }
    }, [account, isWeb3Enabled])
    
    return (
        <div>
            {isConnected ? (
                <div>
                    Connected to {account.slice(0, 6)}...{account.slice(account.length - 4)}
                </div>
            ) : (
                <button
                    onClick={async () => {
                        try {
                            await enableWeb3()
                            console.log("Web3 Enabled")
                        } catch (error) {
                            console.error("Failed to enable Web3:", error)
                        }
                    }}
                >
                    Connect Wallet
                </button>
            )}
        </div>
    )

pages/ _app.js :


import Head from "next/head"
import { MoralisProvider } from "react-moralis"

export default function App({ Component, pageProps }) {
return (
<>
<Head>
<title>Smart Contract Lottery</title>
<meta name="description" content="Our Smart Contract Lottery"></meta>
</Head>
<MoralisProvider initializeOnMount={false}>
<Component {...pageProps} />
</MoralisProvider>
</>
)
}

My package.json:


{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"ethers": "^6.13.2",
"moralis-v1": "^1.13.0",
"next": "14.2.5",
"react": "^18",
"react-dom": "^18",
"react-moralis": "^1.4.2"
},
"devDependencies": {
"postcss": "^8",
"prettier": "^3.3.3",
"tailwindcss": "^3.4.1"
}
}

If anyone knows how to solve this, please help me with the issue. And also I’d appreciate if anyone suggest me a good alternate for react-moralis with connecting Web3 wallets in a React application.

Strapi Redis cache invalidation on entity update

Could you please help me out? I’m facing an issue with Redis caching.
When one entity in the Strapi collection is modified, Redis removes the entire cache for that entity, and everything gets reset.
P.S. Maybe it’s because we’re using the REST API?
I’ll leave the libraries we’re using on the project:
“strapi-plugin-redis”: “1.0.1”,
“strapi-plugin-rest-cache”: “4.2.8”,
“strapi-provider-rest-cache-redis”: “4.2.8”,

“The only thing I’ve found for solving this problem through the strapi-plugin-rest-cache is to add a ‘key’ in the config > provider > key: ‘key’, but that doesn’t seem to be helping.”

Filesnodejsnode_modulesnpmbinnode_modulesnpmbinnpm-cli.js’

Many web developers face Node.js issues, and one of the most frustrating is this:

npm –version
node:internal/modules/cjs/loader:1093
throw err;
^

Error: Cannot find module ‘C:Program Filesnodejsnode_modulesnpmbinnode_modulesnpmbinnpm-cli.js’
at Module._resolveFilename (node:internal/modules/cjs/loader:1090:15)
at Module._load (node:internal/modules/cjs/loader:934:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47 {
code: ‘MODULE_NOT_FOUND’,
requireStack: []
}

Node.js v19.9.0

how to fix :
**1- **add nodejs to your “C:Program Filesnodejs” in the user and system Environment Variables

2 – try to add new system variable go to Environment Variables–> in system variable section click “New” variable name : nodejs
varuable value : path to your nodejs in the program files example :”C:Program Filesnodejs”
click ok –> ok –> ok

3- if non of the above works try to remove nodejs from every point in your system and install it again , then try to repeat the same things in **1 and 2 **

How to getEXIF() from a video file?

I am using exif-js library to get EXIF data from images, which was successful.
I am trying the same but from video files now.

I have done some google search with vain.

Is there a counterpart library of exif-js for videos?

Thank you very much!

Warm Regards,
DoKtor.

JavaScript Doesn’t Always Load

I am trying to build a website, the JavaScript code that is supposed to add the sticky navigation menu when the header is not visible doesn’t work properly. It was working without any problems when I hosted the website locally; but, when I hosted the website on a server it doesn’t always work.

There are two JavaScript files for different stuff, one works flawlessly. The one that is causing problems is using JQuery, I surmise that maybe it is JQuery that is causing problems.

After reloading the site many times, it starts to work as intended. Also, this error shows up in console when this happens;

script.js:34 Uncaught ReferenceError: $ is not defined
    at script.js:34:5
(anonymous) @   script.js:34

Here are the codes that are causing problems.

The JavaScript file;

if (window.location.href.replaceAll(window.location.origin, '').replaceAll('/', '').length === 0 || window.location.href.includes("index.html")) {
    $(window).scroll
        (
            $(window).onload = function () {

                if ($(window).scrollTop() >= 300) {
                    $(window).innerWidth
                        (
                            function () {

                                if ($(window).innerWidth() < 460) {
                                    $('nav').addClass('fixed-header');
                                    $('nav div').removeClass('visible-title');
                                }
                                else {
                                    $('nav').addClass('fixed-header');
                                    $('nav div').addClass('visible-title');
                                }

                            }
                        );


                }
                else {

                    $('nav').removeClass('fixed-header');
                    $('nav div').removeClass('visible-title');
                }
            }
        );
} else {
    if ($(window).innerWidth() < 460) {
        $('nav').addClass('fixed-header');
        $('nav div').removeClass('visible-title');

    } else {
        $('nav').addClass('fixed-header');
        $('nav div').addClass('visible-title');
    }
}

The HTML file;

<!DOCTYPE html>
<html lang="tr">

    <head>
        <!-- Google tag (gtag.js) -->
        <script async
            src="https://www.googletagmanager.com/gtag/js?id=XXXXXX"></script>
        <script>
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());

        gtag('config', 'XXXXXX');
    </script>

        <script language="JavaScript" type="text/javascript" async src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <script language="JavaScript" type="text/javascript" async src="/script.js"></script>

        <script id="MathJax-script" async
            src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
        <title>Arşiv</title>
        <link rel="icon" type="image/x-icon" href="../RezonansLogo.png">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="../style.css">
    </head>

    <body>
        <header>
            <nav>
                <div class="site-title"><a
                        style="color:white; text-decoration: none"
                        href="../index.html"
                        target="_self">Rezonans Kulübü</a></div>
                <ul>
                    <li><a href="/sayfalar/yazilar.html">Yazılar</a></li>
                    <li><a href="/sayfalar/ekip.html">Ekip</a></li>
                    <ul>
                    </nav>
                </header>
                <section class="content">
                    <article>
                        <h1>Örnek.</h1>
                    </article>
                </section>
            </body>

        </html>

I tried loading the script inside the body tag but it didn’t helped at all. I tried downloading JQuery, it also didn’t solved the problem. I tried to remove the async tag, that somewhat worsened the issue. I also tried to incIude a JQuery fallback. I am out of ideas at this point.

Post Scriptum: I suppose these are very inefficient and absurd, sorry for that. Thank you in advance.

Getting weird error in Vue.js 3 while using i18n

I am working on a project where i18n is used, and the loader is ‘@intlify/vue-i18n-loader’. I am working with 2 languages: English and German. I am getting a weird error while running the app.

ERROR  Failed to compile with 1 error                                                                  2:59:59 PM

 error  in ./src/locales/de.json

Module parse failed: Cannot parse JSON: Unexpected token 'e', "export def"... is not valid JSON while parsing 'export default {
  "bch": {
    "bps": ('
File was processed with these loaders:
 * ./node_modules/@intlify/vue-i18n-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
Error: Cannot parse JSON: Unexpected token 'e', "export def"... is not valid JSON while parsing 'export default {
  "bch": {
    "bps": ('
    at JsonParser.parse (/Users/mohitchandel/Documents/front-end/node_modules/webpack/lib/json/JsonParser.js:54:10)

The weird thing is that I have never exported the JSON file mentioned in the Error and the file is in pure JSON format.

Here is my vue.config.js

const CircularDependencyPlugin = require("circular-dependency-plugin");
const ReplaceInFileWebpackPlugin = require("replace-in-file-webpack-plugin");
const webpack = require("webpack");
const path = require("path");

process.env.VUE_APP_VERSION = require("./package.json").version;

module.exports = {
    chainWebpack: (config) => {
        config.optimization.minimizer("terser").tap((args) => {
            args[0].terserOptions.output = {
                ...args[0].terserOptions.output,
                comments: false, // exclude all comments from output
                ascii_only: true,
            };
            return args;
        });
        config.module
            .rule("i18n")
            .test(/.json$/)
            .include.add(path.resolve(__dirname, "src/locales"))
            .end()
            .use("@intlify/vue-i18n-loader")
            .loader("@intlify/vue-i18n-loader")
            .end();
    },
    pluginOptions: {
        webpackBundleAnalyzer: {
            analyzerMode: process.env.VUE_APP_MODE === "production" ? "disabled" : "static",
            openAnalyzer: false,
        },
        i18n: {
            locale: "en",
            fallbackLocale: "en",
            localeDir: "locales",
            enableInSFC: true,
        },
    },
    configureWebpack: {
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "src"),
            },
            fallback: {
                stream: require.resolve("stream-browserify"),
                assert: require.resolve("assert/"),
                http: require.resolve("stream-http"),
                https: require.resolve("https-browserify"),
                os: require.resolve("os-browserify/browser"),
                url: require.resolve("url/"),
            },
        },
        plugins: [
            new webpack.ContextReplacementPlugin(/date-fns[/\]/, new RegExp(`[/\\](en|de)[/\\]index.js$`)),
            new CircularDependencyPlugin({
                exclude: /a.js|node_modules/,
                failOnError: true,
                allowAsyncCycles: false,
                cwd: process.cwd(),
            }),
            new ReplaceInFileWebpackPlugin([
                {
                    dir: "dist/static/img",
                    files: ["sheet.json", "sheet_holiday.json"],
                    rules: [
                        {
                            search: '"image": "sheet.png"',
                            replace: '"image": "sheet.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                        {
                            search: '"image": "characters.png"',
                            replace: '"image": "characters.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                        {
                            search: '"image": "mall.png"',
                            replace: '"image": "mall.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                        {
                            search: '"image": "sheet_holiday.png"',
                            replace: '"image": "sheet_holiday.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                    ],
                },
            ]),
        ],
    },
    publicPath: "/",
    outputDir: "dist",
    runtimeCompiler: true,
    assetsDir: "static",
    productionSourceMap: false,
};

And here is my de.json

{
    "bch": {
        "bps": "Bytes pro Sekunde",
        "ctps": "{'@'}:btc.ctps",
        "difficulty": "{'@'}:btc.difficulty",
        "fiatPrice-usd": "{'@'}:btc.fiatPrice-usd",
        "halving": "{'@'}:btc.halving",
    },
    ....
}

Loading MongoDB Atlas collection into ram for each network request

I have a fixed size dataset (it won’t grow).

Here are the figures:

STORAGE SIZE: 190.13MB
LOGICAL DATA SIZE: 253.71MB
TOTAL DOCUMENTS: 53452
INDEXES TOTAL SIZE: 1.44MB

I don’t like the fact that I am loading the whole dataset into RAM for each network request

const data = await collection.find().toArray();

I could cache the table contents with a global variable.
I would like to know what are the optimal solutions for this case?
FYI. I need the entire table for each request to do comparator logic.

DataGrid. How change background color of header?

I need to change this white background Image Ref

<DataGrid
    rows={users}
    columns={columns}
    disableColumnMenu={true}
    hideFooter={true}
    loading={isLoading}
    autoHeight={true}
    sx={{
      boxShadow: 2,
      border: 2,
      borderColor: "#292524",
      "& .MuiDataGrid-cell": {
        color: "white",
        borderColor: "#292524",
      },
      "& .MuiDataGrid-columnHeader": {
        backgroundColor: "#0c0a09",
        color: "#75706c",
      }
    }}
/>

& .MuiDataGrid-columnHeader changes the color, but only of inner header cells

DataGrid. How change backround color of header?

enter image description here
Need to remove repaint or remove this white background

<DataGrid
    rows={users}
    columns={columns}
    disableColumnMenu={true}
    hideFooter={true}
    loading={isLoading}
    autoHeight={true}
    sx={{
      boxShadow: 2,
      border: 2,
      borderColor: "#292524",
      "& .MuiDataGrid-cell": {
        color: "white",
        borderColor: "#292524",
      },
      "& .MuiDataGrid-columnHeader": {
        backgroundColor: "#0c0a09",
        color: "#75706c",
      }
    }}
/>

& .MuiDataGrid-columnHeader changes color, but only of inner header cells