How do i address a successful transaction that should be rolled back when a subsequent write to the Firebase realtime database fails?

In a Firebase cloud function, i have the following batch write which i assume is not enough to avoid race conditions, and that i should be using a transaction instead:

const updates = {};
updates[`rooms/${request.data.roomId}/memberTotal`] = admin.database.ServerValue.increment(1); // Increment member total
updates[`members/${request.data.roomId}_${request.auth.uid}`] = {
  dateJoined: admin.database.ServerValue.TIMESTAMP,
  userId: request.auth.uid,
};
// Perform the batch update
try {
  await admin.database().ref().update(updates);
  // success
  return {
    success: true,
  }
} catch (error) {
  throw new functions.https.HttpsError("internal", "member set error", {details: error});
}

It is my understanding however, that in a transaction for the realtime database, i can only update one location in the database.

With that in mind, in the following revised code, i only insert the new member at another location subsequent to the transaction completing successfully, but this introduces an issue if the subsequent write fails, noted below:

try {
  const transactionResult = await admin.database().ref(`rooms/${request.data.roomId}`).transaction((currentRoomData) => {
    if (currentRoomData && currentRoomData.memberTotal !== undefined) {
      // Increment member total
      currentRoomData.memberTotal = (currentRoomData.memberTotal || 0) + 1;
      return currentRoomData;
    } else {
      // If the room doesn't exist or memberTotal is undefined, abort the transaction
      return undefined;
    }
  });

  if (transactionResult.committed) {
    // Perform the update for the member after the transaction
    const memberUpdate = {};
    memberUpdate[`members/${request.data.roomId}_${request.auth.uid}`] = {
      dateJoined: admin.database.ServerValue.TIMESTAMP,
      userId: request.auth.uid,
    };
    try {
      await admin.database().ref().update(memberUpdate);
      return { success: true };
    } catch (error) {

       // DO I ROLLBACK THE INCREMENTED FIELD HERE USING ANOTER TRANSACTION??
      
       throw new functions.https.HttpsError("internal", "member set error", { details: error });
    }
    
  } else {
    throw new functions.https.HttpsError("internal", "member set transaction aborted");
  }
} catch (error) {
  throw new functions.https.HttpsError("internal", "member set transaction error", { details: error });
}

What should i do if the subsequent write to members/${request.data.roomId}_${request.auth.uid} fails?

In that error case, the previous transaction would need to be rolled back given that this total represents the total number of members written to the /members location.

Does this suggest that i should initiate yet another transaction to rollback the total if the subsequent write fails? That does not seem practical to me and signals that i am approaching this all wrong.

What is the best approach for handling this scenario in the realtime database?

Is a batch write the only option i have if i need both locations to update atomically?

Doc inside the collection appears in italic font while saving into firebase

try {
// create a collection called ‘pactLists’
const pactListsCollection = collection(db, “pactLists”); // for keeping the records of created pacts by all users.

        // generate a unique id for the creating pact , it will be the invite code for that pact as well.
        const uniquePactId = uuidv4();
        setInviteCode(uniquePactId);

        // Create a document reference to the 'pactLists' collection with the uniquePactId
        const pactListDocRef = doc(pactListsCollection, uniquePactId);

        const creatorDetails = {
          address: account,
        };
        // Set the creatorDetails inside the 'pactLists' collection
        await setDoc(pactListDocRef, {
          creator: creatorDetails,
          // joiners: [], // Initialize an empty array to store joiner details
        });

        // Document updated successfully in pactLists
        console.log("pact details document successfully updated!");

        const memberDetails = {
          address: account,
          minimumPledgeAmount: enteredPledgeAmount,
          frequentPledging: selectedPledgeFrequency,
          pledgingDuration: selectedPledgeTerm,
        };
        // datas to set inside the createdPactDetails collection.
        const pactDetailsToSet = {
          pactName: pactName,
          membersCount: minMembers,
          inviteCode: uniquePactId,
          minimumPledgeAmount: minEthPledge,
          frequentPledging: selectedPledgeFrequency,
          pledgingDuration: selectedPledgeTerm,
          pactCreationDeadline: deadline,
          creatorId: account,
          joinStatus: "Waiting for other members to join",
          members: [memberDetails],
        };

        // Now, create the 'userPacts' collection
        const userPactsCollection = collection(db, "userPacts");
        // Create a document reference to the 'userPacts' collection using the user's MetaMask account address
        const userPactsDocRef = doc(userPactsCollection, account);

        // Create the 'AdminPacts' subcollection
        const adminPactsCollection = collection(
          userPactsDocRef,
          "AdminPacts"
        );
        // Create a document reference to the 'AdminPacts' subcollection using the uniquePactId
        const adminPactDocRef = doc(adminPactsCollection, uniquePactId);

        // Set the pactDetailsToSet inside the 'AdminPacts' subcollection
        await setDoc(adminPactDocRef, pactDetailsToSet);
        // Document updated successfully in 'AdminPacts'
        console.log(
          "AdminPact document successfully updated!",
          pactDetailsToSet
        );

        // Now, create the 'JoineePacts' subcollection
        const joineePactsCollection = collection(
          userPactsDocRef,
          "JoineePacts"
        );
        // Create a document reference to the 'JoineePacts' subcollection using the uniquePactId
        const joineePactDocRef = doc(joineePactsCollection, uniquePactId);

        // Set the pactDetailsToSet inside the 'JoineePacts' subcollection
        await setDoc(joineePactDocRef, memberDetails);

        // Document updated successfully in 'JoineePacts'
        console.log(
          "JoineePact document successfully updated!",
          memberDetails
        );
        setModalPageNumber(2);
      } catch (error) {
        console.log("Error updating pact creation document: ", error);
      }

This is how I am creating new collection and storing the data into my firebase account, but inside the collection “userPacts” the doc that I am referring in the following line : const userPactsDocRef = doc(userPactsCollection, account); seems to be stored in italic font, why this happens? also I was trying to fetch the details in my another component as follows:
useEffect(() => {
console.log(“Checking pact for account:”, account);

const checkUserPact = async () => {
  try {
    const userPactsCollection = collection(db, "userPacts");
    const userPactDocRef = doc(userPactsCollection, account);

    const userPactDoc = await getDoc(userPactDocRef);

    if (userPactDoc.exists()) {
      // User has a pact, you can use the data if needed
      console.log("User has a pact.");
      setUserHasPact(true);
    } else {
      // User does not have a pact
      console.log("User does not have a pact.");
    }
  } catch (error) {
    console.error("Error checking user pact:", error);
  }
};

checkUserPact();

}, [account]); even if the user account have created a pact, it shows “User does not have a pact.”

I want to fix the issue with doc saving in italic format while saving into firebase also, I want to fetch the details if the user has any “adminPacts” inside the “userPacts” collection.

Issue with Form Submission: Dropdown Values Empty

I am encountering an issue with obtaining values from a form that contains text fields and dropdown selects. When I submit the form, the values from the selected dropdowns are consistently empty (“”), regardless of whether I use serialize or serializeArray. What might I be overlooking?

Code Snippet – index.blade.php:

<!-- ... (previous code) ... -->

<form id="create-themebox-form" name="create-themebox-form" autocomplete="off">
    <div class="panel-body">
        <!-- ... (previous code) ... -->
        <div class="form-group has-feedback">
            <label class="themebox-form-label" for="themebox-form-category">Kategorie </label>
            <select class="form-control" name="category" id="themebox-form-category"
                    onchange="notEmptyValidate('themebox-form-category', 'themebox-form-category-status', 'themebox-form-category-icon')">
                <option value="" selected>Bitte Kategorie auswählen</option>
                @foreach ($categories as $category)
                    <option value="{{$category['id']}}">{{$category['name']}}</option>
                @endforeach
            </select>

            <span id="themebox-form-category-icon"></span>
            <span id="themebox-form-category-status" class="errorHeader">Kategorie wird benötigt!</span>
        </div>
        <!-- ... (remaining code) ... -->
    </div>
</form>

<!-- ... (remaining code) ... -->

Code Snippet – themebox-table.js:

$('#create-themebox-button').click(function () {
    document.getElementById('extra_text_create').value = $('#summernote_create').summernote('code');
    $.ajax({
        url: "../admin/createThemebox",
        type: 'POST',
        data: {themebox_data: $('#create-themebox-form').serializeArray()},
        success: function (response) {
            showSuccessModal("Themenkiste wurde erfolgreich erstellt");
        },
        error: function (xhr, status, error) {
            showFailureModal("Themenkiste konnte nicht erstellt werden", xhr);
        }
    })
});

Working with React for the first time; PropTypes values are undefined

It’s my first time working with React and I am trying to build a simple weather app to learn how components react with each other. I have a forecast.json file with the forecast information(temperature, date, humidity, wind speed, wind direction etc) and location.

I have built myself a ForecastDetails component that will display the values of these forecast variables and link it to my main app.jsx. The issue is every time I build my ForecastDetails component and try to render this component within my main App.jsx, I keep seeing PropType errors, which keep telling me the props I try to pass in the ForecastDetails component keeps coming back as undefined (I made sure they are required values through the importation of PropTypes).

Here is my main app.jsx file, which has the component ForecastSummaries(which takes the forecast value from a separate component called ForecastSummary)

import "../styles/App.css";
import React from "react";
import PropTypes from "prop-types";
import LocationDetails from "./locationDetails";
import ForecastSummaries from "./ForecastSummaries";
import ForecastDetails from "./ForecastDetails";

function App(props) {
  const { forecasts, location } = props;

  return (
    <div className="weather-app">
      <LocationDetails city={location.city} country={location.country} />
      <ForecastSummaries forecasts={forecasts} />
      <ForecastDetails forecasts={forecasts} />
    </div>
  );
}

App.propTypes = {
  // propType validation for forecasts data
  forecasts: PropTypes.arrayOf(
    PropTypes.shape({
      data: PropTypes.number,
      description: PropTypes.string,
      icon: PropTypes.string,
      temperature: PropTypes.shape({
        max: PropTypes.number,
        min: PropTypes.number,
      }),
    }),
  ).isRequired,

  location: PropTypes.shape({
    city: PropTypes.string,
    country: PropTypes.string,
  }).isRequired,
};

// In React, component names MUST START WITH CAPITAL LETTERS

export default App;

Here is my ForecastDetails component;

import PropTypes from "prop-types";
import React from "react";
import moment from "moment";

function ForecastDetails({ date, temperature, humidity, wind, description }) {
  return (
    <div className="forecast-details">
      <h1>Details</h1>
      <div className="forecast-details_date">
        {moment(date).format("ddd Do MMM")}
      </div>
      <div className="forecast-details_temperature">{temperature}&deg;C</div>
      <div className="forecast-details_humidity">{humidity}%</div>
      <div className="forecast-details_wind">{wind}mph</div>
      <div className="forecast-details_description">{description}</div>
    </div>
  );
}

ForecastDetails.propTypes = {
  date: PropTypes.number.isRequired,
  temperature: PropTypes.shape({
    min: PropTypes.number,
    max: PropTypes.number,
  }).isRequired,
  humidity: PropTypes.number.isRequired,
  wind: PropTypes.shape({
    speed: PropTypes.number,
    direction: PropTypes.string,
  }).isRequired,
  description: PropTypes.string.isRequired,
};

export default ForecastDetails;

For more context, here is the main index.js file that allows me to use the forecast data throughout my app and its components;

import React from "react";
import ReactDOM from "react-dom/client";
import "./styles/index.css";
import App from "./components/App";
import forecast from "./data/forecast.json";

const { location, forecasts } = forecast;

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App forecasts={forecasts} location={location} />
  </React.StrictMode>,
);

It should display the details below each Forecast Summary

ı know the error is somewhere in how I am passing these props between components. However, It’s really my first time with React so I don’t really know how to identify the error itself. Any help would be greatly appreciated.

Html object tag for svg find width

I have

<object
   data="${content}"
   type="image/svg+xml"
></object>

Where content is a svg.

Currently i am trying to figure this on elm.

    object
        [ Attr.attribute "data" "${content}"
        , Attr.type_ "image/svg+xml"
        ]
        []

QUESTION:
how can i find the width of the svg?

I tried in elm on "load" but it does not fire.
Javascript or elm solution welcomed, but i prefer elm

I tried on elm

on "change" decodeImgLoad

or

on "load" decodeImgLoad

but they do not get called at all.

When i used img instead of object it worked, but i want to have the svg set up correctly on the dom and not just as image.

In elm i can not reference the svg directly, i need img or object or to convert it into elm svg.
(to convert it into elm svg is not possible, as the svg is large)

Experiencing an error during code analysis for CASA requirements

The technology I utilized is a React Native mobile application.

Encountering an error while executing the command to run a Docker file, it yields the following error message:

Got error from NIX package

The command leading to the error is:-

docker run casascan m gitlab:fluidattacks/universe@trunk /skims scan {App Repo Name}/config.yaml

and my folder structure is :– scan

  1. scan>>Application Repo
  2. scan>>docker file
  3. scan>>Application Repo>>config.yaml
    Folder structure image

Here is my config.yaml file code

# Description:
#   Pick a name you like, normally the name of the repository.
# Example:
namespace: OWASP

# Description:
#   Omit if you want pretty-printed results,
#   Set to a path if you want CSV results.
# Optional:
#   Yes
# Example:
output:
  file_path: ./Fluid-Attacks-Results.csv
  format: CSV

# Description:
#   Working directory, normally used as the path to the repository.
# Example:
working_dir: ./mobileclient

# Description:
#   SAST for source code.
# Example:
sast:
  # Description:
  #   Target files used in the analysis.
  # Example:
  include:
    # Absolute path
    - .
    # Relative path to `working_dir`
    - .

# Description:
#  Reversing checks for Android APKs.
apk:
  # Description:
  #   Target files used in the analysis.
  # Example:
  include:
    # Absolute paths
    - KuntoResearchandroidappreleaseapp-release.apk
    # - /app/app-arm-debug.apk
    # - /app/app-x86-debug-Android5.apk
    # - /app/app-x86-debug.apk


# Description:
#   Findings to analyze.
#   The complete list of findings can be found here:
#   https://gitlab.com/fluidattacks/universe/-/blob/trunk/skims/manifests/findings.lst
# Optional:
#   Yes, if not present all security findings will be analyzed.
# Example:
# Description:
#   Language to use, valid values are: EN, ES.
# Optional:
#   Yes, defaults to: EN.
language: EN

Taking a reference of this file :- https://appdefensealliance.dev/casa/tier-2/ast-guide/static-scan

Image Upload & Editing: Implementing in-browser cropping and storing edited images on the server using MERN stack

I’m working on a project where I want to allow users to upload images, perform in-browser cropping, and store the edited images on the server. I’m using the MERN stack (MongoDB, Express.js, React, Node.js). I’ve implemented the basic functionality, but I’m struggling with adding in-browser cropping.

const express = require('express')
const cors = require('cors')
const multer = require('multer')
const path = require('path')
const app = express()
const mongoose = require('./db');
const ImageModel = require('./models/ImagesData')
app.use(cors())
app.use(express.json())
app.use(express.static('public'))
const storage = multer.diskStorage({
    destination:(req,file,cb)=>{
        cb(null,'public/Images')
    },
    filename:(req,file,cb)=>{
        cb(null,file.fieldname+"_"+Date.now()+path.extname(file.originalname))
    }
})

const upload = multer({
    storage:storage
})

app.post('/upload',upload.single('file'),(req,res)=>{
   ImageModel.create({image:req.file.filename})
   .then(result=>res.json(result))
   .catch(err => console.log(err))
})
app.get('/getImages',(req,res)=>{
    ImageModel.find()
    .then(Image=>res.json(Image))
    .catch(err=>console.log(err))
})

app.listen(4000,()=>{
    console.log("Server Running at port 4000")
})
import React, { useState, useEffect } from 'react';
import { useAuth0 } from "@auth0/auth0-react";
import axios from 'axios';

const Gallery = () => {
  const { user, logout } = useAuth0();
  const [file, setFile] = useState('');
  const [images, setImages] = useState([]);

  useEffect(() => {
    axios
      .get('http://localhost:4000/getImages')
      .then(res => setImages(res.data))
      .catch(err => console.log(err));
  },[]);

  const handleUpload = () => {
    const formData = new FormData();
    formData.append('file', file);
    
    axios
      .post('http://localhost:4000/upload', formData)
      .then(res => {
        console.log(res);
        setImages([...images, res.data.image]);
      })
      .catch(err => console.log(err));
  };

  const handleChange = (e) => {
    setFile(e.target.files[0]);
  };

  return (
    <div className="container mx-auto">
      <div className="flex justify-end">
        <button
          onClick={() => logout({ returnTo: window.location.origin })}
          className="bg-blue-500 text-white px-4 py-2 rounded-md"
        >
          Logout
        </button>
      </div>

      <div className="flex justify-center">
        <input type="file" onChange={handleChange} />
        <button
          onClick={handleUpload}
          className="bg-blue-500 text-white px-4 py-2 rounded-md"
        >
          Upload
        </button>
      </div>

      <br />

      <div className="grid grid-cols-3 gap-4">
        {images.map(image => (
          <img
            key={image.id}
            src={`http://localhost:4000/Images/${image.image}`}
            alt="image"
            className="object-fit cover rounded-lg h-48 w-full"
          />
        ))}
      </div>
    </div>
  );
};

export default Gallery;

The current setup allows users to upload images, but I need assistance in integrating an in-browser cropping tool and ensuring that the cropped image is stored on the server. I’m looking for guidance or examples on how to integrate a cropping tool like react-image-crop into my existing React component and modify the server-side code to handle the cropped image.

Any help or examples would be greatly appreciated! Thank you.

Why does my jest suite throw a parsing error after adding i18n to my Vuejs project?

After adding i18n (v9.6.5) to my project, jest (v27.0.5) fails with a not too helpful error message.
The error starts occuring once i use i18n in files, the translation itsself works flawlessly, it’s just jest that breaks.

Error:
Test suite failed to run
Jest encountered an unexpected token

Details:

C:UserslazIdeaProjectsblindg-frontendnode_modules@mdifontcssmaterialdesignicons.css:2
@font-face {
^

SyntaxError: Invalid or unexpected token

  1 | // Styles
> 2 | import "@mdi/font/css/materialdesignicons.css";
    | ^
  3 | import "vuetify/styles";
  4 |
  5 | // Vuetify

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (src/plugins/vuetify.js:2:1)
  at Object.<anonymous> (src/main.js:4:1)
  at Object.<anonymous> (src/components/DudsView/DudDialog.vue:8:1)
  at Object.<anonymous> (tests/unit/components/DudDialog.spec.js:2:1)

My jest config in package.json (removed previous fix attempts):

"jest": {
    "preset": "@vue/cli-plugin-unit-jest",
    "moduleFileExtensions": [
      "vue",
      "js",
      "json",
      "jsx",
      "ts",
      "tsx",
      "node"
    ],
    "transform": {
      "^.+\.vue$": "@vue/vue3-jest",
      "^.+\.js$": "babel-jest"
    },
    "transformIgnorePatterns": [
      "<rootDir>/node_modules/"
    ],
    "moduleNameMapper": {
      "^lodash-es$": "lodash",
      "^mock-data(.*)$": "<rootDir>/tests/mock-data",
      "axios": "axios/dist/node/axios.cjs",
      "^@vueuse/integrations/useJwt(.*)$": "@vueuse/integrations/useJwt.cjs"
    },
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{js,vue}",
      "!src/main.js"
    ]
  }

I’ve already tried:

  • change way i18n is setup/created in main.js
  • added transform and moduleNameMapper to jest config in package.json
  • update i18n version

how to extract text(ONLY) from the syncfusion documentEditor using angular

I am using angular and I would like to extract the text from documentEditor and save it to a field in my DB . I am using the SaveAsBlob that is mentioned in the documentation. please note the txt saveAsBlob method is being called after another saveAsBlob method which is successfully saving a DOCX .

Error

ERROR TypeError: Cannot read properties of undefined (reading ‘length’)

at TextExport.writeTable (ej2-documenteditor.es5.js:114144:40)

at TextExport.writeBody (ej2-documenteditor.es5.js:114120:22)

at TextExport.writeHeaderFooter (ej2-documenteditor.es5.js:114169:18)

at TextExport.writeHeadersFooters (ej2-documenteditor.es5.js:114161:14)

at TextExport.writeInternal (ej2-documenteditor.es5.js:114104:18)

at TextExport.saveAsBlob (ej2-documenteditor.es5.js:114066:14)

at ej2-documenteditor.es5.js:119255:48

at new ZoneAwarePromise (zone.js:1411:21)

at DocumentEditor.saveAsBlob (ej2-documenteditor.es5.js:119250:16)

at TestWritingAnswertemplateComponent.saveToTrackingTable (test-writing-answertemplate.component.ts:965:35

HTML

<ejs-documenteditorcontainer [serviceUrl]='"https://ej2services.syncfusion.com/production/web-services/api/documenteditor/"'

   style="display:block" (contentChange)="onContentChange()" height="800" width="100%" #documentEditor [enableToolbar]=true [isReadOnly]=false [enableEditor]=true >

</ejs-documenteditorcontainer>

TS

ngOnInit(): void {



        setInterval(() => {

         this.saveTestAnswerDoc(); // this method is successfully saving the DOCX using saveAsBlob method

          this.saveToTrackingTable();

        }, 30000);

  }



public saveToTrackingTable(){

    const reader = new FileReader()

    this.container.documentEditor.enableTextExport = true;

    this.container.documentEditor.saveAsBlob('Txt').then((exportedDocument: Blob) => {

    reader.onload = (e) => {

      this.readerResult = reader.result.toString();

      console.log(reader.result.toString());

      this.saveTrackingAnswersLocal(reader.result.toString());

    }

    reader.readAsText(exportedDocument);

    this.container.documentEditor.saveAsBlob('Txt').then((exportedDocument: Blob) => {

    reader.onload = (e) => {

      this.readerResult = reader.result.toString();

      console.log(reader.result.toString());

      this.saveTrackingAnswersLocal(reader.result.toString());

    }

    reader.readAsText(exportedDocument);

  }

)

}

)

     console.log(this.readerResult);

     if(!this.readerResult){

      console.log("retreiving tracking text.....");

      //this.sendStudentAnswerTextData();

     }

      var stud:StudentTestAnswer;

      stud = {

      id:this.testId,

      studentId:this.studentId,

      accomodation:true,

      fullScreenClosed:false,

      answerText:this.readerResult,

      keyPress :false,

      offline:false,

      leftExamArea:false,

      fileName:"FileName",

      timeRemaining :"00:00",

      testId:this.testId,}

      this.studentTestWriteService.saveAnswersInterval(stud)

     .subscribe((data) => {

          console.log(data);

      })

      //this.contentChanged = false;

      console.log("finished saving")

}

getting wrong output on my tic tac toe negamax algorithm

I’ve been learning computer gaming, I have successed on minimax algorithm with tic tac toe. but the negamax algorithm always gives the wrong move. can anyone tell me what’s wrong with my code?

static negamax(board, alpha, beta, maxmizingPlayer) {
    const emptyCells = this.getEmptyCells(board);
    if (this.isGameOver(board) || emptyCells.length === 0) {
      const score = this.evaluate(board);
      return { score : maxmizingPlayer? score : -score };
    }
    let bestMove =  { score:  -Infinity };
    for (let i = 0; i < emptyCells.length; ++i) {
      const { x, y } = emptyCells[i];
      board[y][x] = maxmizingPlayer ? this.mySymbol : this.opSymbol;
      const move ={
        score: -this.negamax(board, -beta, -alpha, !maxmizingPlayer).score
      };
      board[y][x] = this.emptySymbol;
      move.x = x;
      move.y = y;
      if (move.score >= bestMove.score) {
        bestMove = move;
      }
      alpha = Math.max(alpha, bestMove.score);
      if (beta <= alpha) {
        break;
      }
    }
    return bestMove;
  }

static evaluate(board) {
    if (this.isWining(board, this.mySymbol)) {
      return Infinity;
    }
    if (this.isWining(board, this.opSymbol)) {
      return -Infinity;
    }
    return 0;
  }

In a Nuxt3 application, the header information does not change even when using useHead

I am creating an application using Nuxt3’s SSR mode.
In that application, even though I am using useHead, the header information of the pages in the pages directory does not change.
I confirmed that it did not change by verifying the source of the page in Chrome.
On the other hand, the source code that can be confirmed with the developer tool after the page is displayed was rewritten.
I would like you to tell me how to solve it.

Here is a part of my source code.
If you’d like to know my other code, please let me know.

import { defineNuxtConfig } from 'nuxt/config'
import removeConsole from 'vite-plugin-remove-console'

export default defineNuxtConfig({
  nitro: {
    baseURL: process.env.NUXT_PUBLIC_SITE_DOMAIN,
    prerender: {
      crawlLinks: true,
      failOnError: false,
    },
  },
  css: [
    '@/assets/scss/main.scss',
    '@mdi/font/css/materialdesignicons.css',
    '@/assets/scss/style.scss',
  ],
  modules: ['nuxt-simple-sitemap', 'nuxt-simple-robots', '@kgierke/nuxt-basic-auth', 'nuxt-jsonld'],
  build: {
    transpile: ['vuetify'],
  },

  typescript: {
    shim: false,
    strict: true,
  },
  devtools: {
    enabled: true,
  },
  vite: {
    ssr: {
      noExternal: ['vuetify'],
    },
    define: {
      'process.env.DEBUG': false,
    },
    server: {
      watch: {
        usePolling: true,
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/assets/scss/global" as g;',
        },
      },
    },
    plugins: [removeConsole()],
  },
  app: {
    head: {
      htmlAttrs: {
        lang: 'ja',
      },
      charset: 'utf-8',
      viewport: 'width=device-width,viewport-fit=cover',

      meta: [
        {
          name: 'og:locale',
          content: 'ja_JP',
        },

        { property: 'og:type', content: 'website' },
        {
          property: 'og:image:width',
          content: '1200',
        },
        {
          property: 'og:image:height',
          content: '630',
        },
      ],
    },
  },

  site: {
    url: process.env.NUXT_PUBLIC_SITE_DOMAIN,
  },
  basicAuth: {
    enabled: process.env.BASIC_ENABLED === 'true',
    users: [
      {
        username: process.env.BASIC_ID ?? '',
        password: process.env.BASIC_PASSWORD ?? '',
      },
    ],
  },
})
<script setup lang="ts">
useHead({
  title: 'testtitle',
  link: [{ rel: 'canonical', href: computed(() => domain.value + route.path) }],
})
</script>
<script setup lang="ts">
useHead({
  title: 'test-hoge-title',
})
</script>

I researched, but there was little information about Nuxt3.

Swiper slider grid shows incorrect order

I was making slider using Swiper and React.js.
I want to show 2 items in per page.
But it shows the items with incorrect order.
Swiper version: 10.0.0
React version: 18

Here is my code.

<Swiper
  ref={swiperRef}
  spaceBetween={0}
  allowTouchMove={true}
  touchMove={true}
  slidesPerView={1}
  grid={{
    fill: 'row',
    rows: 2,
  }}
  pagination={{
    type: 'fraction'
  }}
  className="mySwiper"
  modules={[Grid, Pagination]}
  onInit={(swiper) => {
    setPagination(swiper?.pagination?.el?.outerText)
  }}
  onSlideChange={onChangeSlider}
>
  {results?.map((item, index) => (
    <SwiperSlide key={index}>
      <div className="bg-[#e2e2e2] py-4 my-2 text-[#010101]">{index + 1}</div>
    </SwiperSlide>
  ))}
</Swiper>

Expected result:

First page
1
2

Second page
3
4

third page
5

Current result

First page
1
4

Second page
2
5

Third page
3

If I remove grid.fill, result is

1
2
3
4
5

How can I fix this?

How to customize Recharts Pie Chart?

I have a pie chart that i want to show two things, the store name and the percentage. Currently, my chart looks like this
enter image description here

In the outer label, the Loja part, how can I change the font color to be just one color?
The inner label, the percentage, how can I move the label to the larger part of the slice, so it will have more space to show the number?

My Chart Code

<ResponsiveContainer width="100%" height="100%">
  <PieChart margin={{ right: 10, left: 10 }}>
    <Pie
      data={chartData}
      dataKey="value"
      nameKey="name"
      outerRadius={90}
      label={(entry) => entry.name}
      cx="50%"
      cy="50%"
    >
      <LabelList dataKey="showValue" position="insideRight"/>
      {chartData.map((entry, index) => (
        <Cell
          key={`cell-${index}`}
          fill={`rgba(131, 54, 235, ${100 - index * 6}%)`}
          fontWeight={300}
        />
      ))}
    </Pie>
  </PieChart>
</ResponsiveContainer>

Why string is converting into date javascript?

I have one grid in which I have to show the product name, Date of Purchase, and comment.
I have a string message that I have to display in the comment section as the grid is common component so, i have checked that if the record is date Type or not for that i am using const dateObject = new Date(val);

So, Date as string “17-Nov-2023″ is converting correctly but the given text is also converting to the date that I don’t want.
const msg=”The product has been updated on 16-Nov-2023”

What I want is that when i will pass the string const msg=”The product has been updated on 16-Nov-2023″ to const dateObject = new Date(val); it should return false as an invalid date.
some detail

with js , How to drag and drop the entire Row box inside the Column box

I created an html file with 2 button (add row, add column) to add Row-box and column-box. To create row-box click add row button , to add column-box inside the row, click add column and then click any added row-box and can drag column-box to another row-box also. I am looking for a solution to drag the entire row-box inside to another column-box.

When clicking add row , the row-box appending to the ‘contentBox‘ id Container

jsfiddle

HTML:

<div class="wrapper">

      <div class="main-content">

        <div class="header">
          <button class="add-row" onclick="addRow()">Add Row +</button>
          <button class="add-column" onclick="addCol()">Add Column +</button>
        </div>

        <div class="content-box" id="contentBox">

        </div>

      </div>

    </div>

JS:


// Row Addition
var i=0;
let newColNode = null;

function addRow() {    
    const row = document.createElement('div');
    row.className = 'row-block';
    row.id = "b" + ++i;
    document.getElementById('contentBox').appendChild(row);
    row.addEventListener('click', function (event) {
        if(newColNode != null)
        row.appendChild(newColNode);
        newColNode = null
    });
    row.addEventListener('dragover', dragOver); 
    row.addEventListener('dragenter', dragEnter); 
    row.addEventListener('dragleave', dragLeave);
    row.addEventListener('drop', Drop);
}

// Row Addition

function addCol() {
    const col = document.createElement('p');
    col.className = 'column-block';
    col.setAttribute('draggable', true);
    col.textContent = `Column`;
    newColNode = col;
    col.addEventListener('dragstart', dragStart); 
    col.addEventListener('dragend', dragEnd); 
}

// drag and drop

var p = document.getElementsByTagName('p');
var choice = document.getElementsByClassName('row-block');
var dragItem = null;

for (var i of p) {
    i.addEventListener('dragstart', dragStart);
    i.addEventListener('dragend', dragEnd);
}

function dragStart() {
    dragItem = this;
    setTimeout=(()=>this.style.display = "none", 0)
}

function dragEnd() {
    setTimeout=(()=>this.style.display = "none", 0)
    dragItem = null;
}

for(j of choice){
    j.addEventListener('dragover', dragOver); 
    j.addEventListener('dragenter', dragEnter); 
    j.addEventListener('dragleave', dragLeave);
    j.addEventListener('drop', Drop);
}

function Drop(){
    this.append(dragItem);
}

function dragOver(e){ 
    e.preventDefault();
}

function dragEnter(e){
    e.preventDefault();
}

function dragLeave(){
    // this.style.borderColor = "none";
}

CSS:

* {
    box-sizing: border-box;
}

.wrapper {
    float: left;
    width: 100%;
    height: 100vh;
}

body {
    padding: 0;
    margin: 0;
    position: relative;
}

.sidebar {
    float: left;
    width: 300px;
    background: #03A9F4;
    height: 100%;
    padding: 10px;
}

.main-content {
    float: left;
    width: calc(100% - 300px);
    height: 100%;
    background: #fafafa;
}

.each-draggable-item {
    width: 100%;
    height: 40px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    border: 1px solid #ccc;
    background: white;
    margin-bottom: 10px;
    border-radius: 6px;
}


.header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
}

.content-box {
    width: 100%;
    height: calc(100% - 60px);
    padding: 15px;
}


button {
    background: #000;
    border: 0;
    padding: 0 20px;
    height: 40px;
    margin-left: 10px;
    font-weight: 600;
    color: white;
    cursor: pointer;
}

.row-block {
    width: 100%;
    border: 2px dashed #848484;
    padding: 20px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-bottom: 20px;

}

.row-block:hover {
    border-color: #2654d1;
}

.column-block {
    position: relative;
    width: 100%;
    min-height: 1px;
    padding-right: 10px;
    padding-left: 10px;
    margin: 0 10px;
    -ms-flex-preferred-size: 0;
    flex-basis: 0;
    -webkit-box-flex: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
    max-width: 100%;
    border: 2px dashed #848484;

    background-color: #dedede;
    padding: 20px;
}
.column-block:first-child {
    margin-left: 0;
}
.column-block:last-child {
    margin-right: 0;
}
.container .ex-moved {
    background-color: #e74c3c;
}
.container.ex-over {
    background-color: rgba(255, 255, 255, 0.3);
}
.handle {
    background-color: rgba(0, 0, 0, 0.4);
    cursor: move;
    margin-right: 5px;
    padding: 0 5px;
}
.sidebar .column-block {
    min-height: auto;
    margin: 0 0 20px;
    background: white;
    border: 1px solid #ccc;
}
.column-block h5 {
    margin: 0;
}

Attaching the js fiddle along with this.

https://jsfiddle.net/gph82mfa/