AlpineJS, Laravel – change variable in data without event

I have following code:

<ul
    x-cloak
    x-show="activeDropdown === '{{$key}}'"
    x-collapse
    class="sub-menu text-gray-500">

    @loop($value as $itemKey => $itemValue)
        <li>
            <a
                @if(request()->route()->getName() === $itemValue['tableRoute'])
                    class="active"
                    x-data="{ activeDropdown : '{{$key}}' }"
                @endif
                id="{{$key}}_{{$itemKey}}"
                href="{{route($itemValue['tableRoute'])}}">
                {{ $itemValue['label']  }}
            </a>
        </li>
    @endloop

</ul>

And AlpineJS code:

<script>
    document.addEventListener("alpine:init", () => {
        Alpine.data("sidebar", () => ({
            activeDropdown : null,
        }));
    });
</script>

The issue is that activeDropdown is not changed, and ul is hidden. What am I doing wrong here?

SvelteKit dynamic variable import not working

Im trying to dynamically import a description variable and i get the value ‘undefined’
+page.js:

await import(`../../../uploads/blog/${params.post}.svelte`)
                .then(async post => {
                    postdata = {
                        meta:{
                            date:(await import(`../../../uploads/blog/${params.post}.svelte`)).description
                        },
                        post: params.post,
                        page: post.default,
                        type: 'svelte'
                    }
                })

+sveltetest.svelte:

<script>
export const description = 'test'
import snarkdown from 'snarkdown'
let post = '##test for svelte pages n dynamic markdown can also be used inside the svelte code'
</script>
{@html snarkdown(post)}
{#each ['item 1', 'item 2', 'item 3', 'item 4'] as test}
<p>{test}</p>
{/each}

output:
{ meta: { date: undefined }, post: 'sveltetest', page: { render: [Function: render], '$$render': [Function: $$render] }, type: 'svelte' }

awaiting for api data then render react component

I am trying to make a slider component getting data from api but I can not figure it out how to get data first and then feed it to the component. As far as I can tell in my implementation, the component tries to render before data is pulled from the api.

  const [slides, setSlides] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    const dataFetch = async () => {
      const data = await (
        await fetch("http://localhost:5000/api/data")
      ).json();

      setSlides(data);
    };

    dataFetch();
  }, []);

  const prevSlide = () => {
    const isFirstSlide = currentIndex === 0;
    const newIndex = isFirstSlide ? slides.length - 1 : currentIndex - 1;
    setCurrentIndex(newIndex);
  };

  const nextSlide = () => {
    const isLastSlide = currentIndex === slides.length - 1;
    const newIndex = isLastSlide ? 0 : currentIndex + 1;
    setCurrentIndex(newIndex);
  };

  const goToSlide = (slideIndex) => {
    setCurrentIndex(slideIndex);
  };

Angular possible put child to component

i have maybe trivial question. I have my component (app-comp)

<div class="test">
  <ng-content select="content1"></ng-content>
  <ng-content select="content2"></ng-content>
</div>

I use this component in my component2.

<div>
  <div content1>Test</div>
</div>

Is here any option use app-comp like this:

<div>
 <content1>Test</content1>
</div>

It looks much better and it’s clear at a glance. Maybe I can’t and I’m asking nonsense here in which case I apologize. But I had a feeling I’ve seen this before and I can’t quite find it because I don’t know what exactly to call it. I understand that it might not be usable because that’s how components are used. On the other hand, I was thinking it’s inside another component, so it could be. Thank you very much.

document does not Upload to database from server (Mongoose)

Hello I have a simple server and a function to upload a song document to the mongoDB database. I get no errors at all when I use npm start to run the code, The successful connection message is logged, but the document doesn’t get added to the database. I have mongo db connected to vs code and I can even see collections/documents from within vs code so the connection is successful but the document just doesnt get added, if anyone knows a fix I would appreciate it. Thanks!

import mongoose from 'mongoose';
import 'dotenv/config';
mongoose.set('strictQuery', false);

mongoose.connect(
 process.env.MONGODB_CONNECT_STRING,
 { useNewUrlParser: true }
);

const db = mongoose.connection;

db.once("open", () => {
   console.log("Successfully connected to MongoDB using Mongoose!");
});


// define the schema
const documentSchema = new mongoose.Schema({
 id: String,
 title: String,
 artist: String,
 genre: String,
 popularity: Number,
 date: Date
});

// Create the Document using the schema
const Document = mongoose.model('Document', documentSchema);


// Define the asynchronous function
async function createSong(id, title, artist, genre, popularity, dateString) {
 try {
   const date = new Date(dateString);
   // Create a new document instance
   const document = new Document({ id, title, artist, genre, popularity, date });
   // Save the document to the database
   await document.save();
 } catch (error) {
   console.log('Error uploading document:', error);
 } finally {
   //close the database connection
   mongoose.connection.close();
 }
}

createSong("ewfqwef", "test", "test", "test", 5, "2022-10-07")

What’s the correct way to use structured data jsonLD in Next.js 13 app-router?

I was trying to add structured data in my nextJS 13(app router) application but couldn’t find the correct method.

Next-seo package also gives errors

I tried next-seo but got this error:

Unhandled Runtime Error
Error: Cannot read properties of null (reading ‘useContext’)

While adding
To the layout.js in the app directory

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <NextSeo useAppDir={true} />
      </head>
      <body className={inter.className}>
        <Navbar />
        {children}
        {/* <GlobalContextProvider>{children}</GlobalContextProvider> */}
        <Analytics />
      </body>
    </html>

Time conflicts and empty messages – Realtime chat application

community.

Problem: I’m working on a real-time django chat application. When user messages it shows the right current time but, it’s gets changed to a different time on refershing the page.

Here are the snaps for your reference:
Real time chatting
After refreshing the page – Note-time has been changed on refreshing and some empty messages are coming as well

What i want is …. as a real-time chat application the time and empty message should not show on refreshing the page.

Here is the code that i’ve implemented:

message model

class Message(models.Model):
    room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE)
    user = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_added',)
Java Script

<script>
    const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
    const userName = JSON.parse(document.getElementById('json-username').textContent);
    const chatSocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/'
        + roomName
        + '/'
    );

    chatSocket.onclose = function(e) {
        console.log('onclose')
    }

    chatSocket.onmessage = function(e) {
        const data = JSON.parse(e.data);

        if (data.message) {
            const currentTime = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
            const messageHTML = `
                <div class="message ${data.username === userName ? 'self' : 'other'}">
                    <div class="message-content">
                        <b>${data.username}</b>: ${data.message}
                    </div>
                    <div class="message-time">
                        ${currentTime}
                    </div>
                </div>
            `;
            document.querySelector('#chat-messages').innerHTML += messageHTML;
        } else {
            {% comment %} alert('The message was empty!') {% endcomment %}
        }

        scrollToBottom();
    };

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function(e) {
        if (e.keyCode === 13) {
            document.querySelector('#chat-message-submit').click();
        }
    };

    document.querySelector('#chat-message-submit').onclick = function(e) {
        e.preventDefault()

        const messageInputDom = document.querySelector('#chat-message-input');
        const message = messageInputDom.value;

        console.log({
            'message': message,
            'username': userName,
            'room': roomName
        })

        chatSocket.send(JSON.stringify({
            'message': message,
            'username': userName,
            'room': roomName
        }));

        messageInputDom.value = '';

        return false
    };

    /**
    * A function for finding the messages element, and scroll to the bottom of it.
    */
    function scrollToBottom() {
        let objDiv = document.getElementById("chat-messages");
        objDiv.scrollTop = objDiv.scrollHeight;
    }

    // Add this below the function to trigger the scroll on load.
    scrollToBottom();
</script>

I can’t recieve an object in Navigation

I am new in learning react native and trying to send an object when user clicked on Flatlist row to display the product in the ProductDetail.tsx but i got an error “undefined is not a function” …
I defined the navigation on App.tsx

import React from 'react';
import Home from './Home';
import ProductDetail from './ProductDetails';
import {
  SafeAreaView,
  useColorScheme,
} from 'react-native';


import {
  Colors,
} from 'react-native/Libraries/NewAppScreen';

import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';


function App(): JSX.Element {
 
  const Stack = createStackNavigator()
 
  const MyStack = () => {
    return (
      <NavigationContainer>
        <Stack.Navigator
             screenOptions={{
            
          }}
>
          <Stack.Screen
            name="Home"
            component={Home} 
            options={{headerShown: false}}
          />
             <Stack.Screen name="ProductDetail" component={ProductDetail}  
             options={{title: 'Product Detail'}}
             />

        </Stack.Navigator>
      </NavigationContainer>
    );
  };

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };
  const isDarkMode = useColorScheme() === 'dark';

  return (
     <MyStack />
  );
}


export default App;

And here is the Home.tsx code

function Home(): JSX.Element {


  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const [shops, setShops] = useState<any[]>([]);
  const nav = useNavigation()

  useEffect(() => {
    fetch('https://dummyjson.com/products')
      .then((response) => response.json())
      .then((result) => {
        setShops(result.products);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);
  
  return (
    
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
     <Text style = {styles.highlight}>Techno Shop</Text>
     <ShopList 
     shops={shops}
     navigation={nav}
     />

      
    </SafeAreaView>
  );
}

The ShopList.tsx Code

interface ShopListProps {
shops: any[];
navigation:any
}

class ShopList extends Component<ShopListProps> {

    
      render() {
        const { shops } = this.props;
        const nav = this.props.navigation;

        return (
    
            <FlatList
              data = {
                shops
              }
              renderItem={({ item, index }) => 
                 <ShopListRow 
                  shop={item} 
                  index={index} 
                  navigation={nav}
              
                />        
    
              }
              keyExtractor={item => item.id}
              initialNumToRender={16}
              extraData={this.state}
            />

    
         
        );
      }
}

export default ShopList;

From the ShopListRow.js i should navigate to ProductDetails.tsx with the product object
and here is the code of ShopListRow.js

export default class ShopListRow extends Component {
  infoPressed = () => {
    this.props.navigation.navigate('ProductDetail', {
      shop: this.props.place
    })
  }
  
    render() {

        const {
          shop,
          index
        } = this.props

        return (
          <TouchableHighlight onPress={this.infoPressed}>
          <View key={shop.id} style={{ backgroundColor: index % 2 === 0 ? '#D3E3EA' : '#B3E3DA' }}>
    
            <View style={styles.row}>
              
              <View style={styles.edges}>
                <Text style={styles.sectionTitle}>{shop.title}</Text>
                <Text style={styles.buttonText}>{shop.description}</Text>

              </View>
    
              <View >
                
                <View 
                  style={styles.button}
                  
                >

                 <Image source={{uri: shop.thumbnail}} Image style={{ margin: 5, height: 120, width: 120 }} />

                </View>
    
    
              </View>
            </View>
    
          </View>
          </TouchableHighlight>
        )
      }
}

and the code of ProductDetails.tsx where i got the error

interface PropsNav {
 // navigation: NavigationScreenProp<NavigationState, NavigationParams>
 navigation:any
}

  //function ProductDetail(): JSX.Element {
    export default class ProductDetail extends Component<PropsNav> {


      render(){
         
       const navigation = this.props.navigation;
       var shop = navigation.getParam('shop');
         return (
 
             <View  style={{ backgroundColor: '#D3E3EA' ,flex : 1}}>
                 
               <Text>{shop}</Text>
             </View>
         )
     }
 
   }

 // export default ProductDetail;

Thanks…

What needs to be done to make the Bootstrap 5.3.0 Collapsible button show in this simple web page?

I’ve tried to create a simple web page that uses the Bootstrap (version 5.3.0) Collapsible and I cannot get it to work no matter what I try.
All I want is a Collapsible that ‘holds’ a few links in it which are shown when you click it.
But when that didn’t work I simplified it to just a list of strings (code shown below) but the problem is still there.
The problem is that the Collapsible button does not show no matter what I try.
The <span class="navbar-toggler-icon"></span> is not visible. I’ve added ‘X’ to both sides
of it just so there is an indication where that invisible button is.
Anyone knows how to fix that, make the Collapsible button visible?
Thanks.
Here’s the code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <title>Simple Bootstrap Page</title>
</head>
<body>
  <header class="bg-primary text-white text-center py-3">
    <div class="container">
      <div class="row">
        <div class="col-md-4">
          <div class="left-header">
            <h3>Left Header</h3>
          </div>
        </div>
        <div class="col-md-4">
          <div class="central-header">
            <h3>Central Header</h3>
          </div>
        </div>
        <div class="col-md-4">
          <div class="right-header">
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNav">
              X<span class="navbar-toggler-icon"></span>X
            </button>
          </div>
          <div class="collapse" id="collapsibleNav">
            <div class="card card-body">
              <ul class="nav">
                <li class="nav-item">Item 1</li>
                <li class="nav-item">Item 2</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

  <main class="container mt-4">
    <h2>Main Content</h2>
    <p>This is the main content of the page.</p>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

React native default RTL support on multi language app

I have two languages react native app en and ar. App default language is ar. I have override native code to set language layout to rtl. Also I am using react-native-restart for switch the language.

Initally first page load it’s working fine and loaded arabic as default language and layout rtl. When I switch the language to en it’s not working and layout remain same rtl. It didn’t forceRTL to false after restart application.

When I remove forceRTL from native code than it’s working fine if default language is en but not working if set default language is ar.

How can I switch the language as default ar language?

i18n.js

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "../lang/en.json";
import ar from "../lang/ar.json";
import { I18nManager } from "react-native";

i18n.use(initReactI18next).init({
compatibilityJSON: "v3",
lng: I18nManager.isRTL ? "ar" : "en",
fallbackLng: I18nManager.isRTL ? "ar" : "en",
resources: {
en: en,
ar: ar,
},
interpolation: {
escapeValue: false, // react already safes from xss
},
});

export default i18n;

index.js

const changeDirection = (value) => {
I18nManager.forceRTL(value);
RNRestart.Restart();
};


{I18nManager.isRTL ? (
    <ButtonTypeA
      clickEvent={() => {
        changeDirection(false);
      }}
      title={"EN"}
    />
  ) : (
    <ButtonTypeA
      clickEvent={() => {
        changeDirection(true);
      }}
      title={"AR"}
    />
  )}

MainActivity.java

@OverRide
public void onCreate() {
super.onCreate();
I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance();
sharedI18nUtilInstance.forceRTL(this,true);
sharedI18nUtilInstance.allowRTL(this, true);
}

When hover on column bar the tooltip is not showing different colors in highchart

When hover on column bar the tooltip should show two colors for OKR for the year and Year to date but it is showing same colors.
I am using this script.

tooltip: { 
                formatter: function() {  
                      
                    let xAxisValue = this.point.name;  
                    let yAxisValue = this.y;
                    let xAxisName = this.series.name;
                    
                    if(hasMultipleCols){
 
                        if(typeof chartArrayData[1] != 'undefined') {
 
                            yAxisValue =  chartArrayData[1].data[this.point.index]; // this.point.name == undefined ? this.point.y : this.point.name
                            xAxisValue =  chartArrayData[0].data[this.point.index];
                            xAxisName  =  chartArrayData[0].name;
                            yAxisName =   chartArrayData[1].name;
                        }
                         
                     }
                     return `<span style="color:${this.color}">●</span> ${yAxisName }: <b>${ yAxisValue}</b><br/><span style="color:${this.color}">●</span> ${xAxisName}: <b>${xAxisValue }</b>`;
                     
                },  
            }

Please attachment

enter image description here
Please guide me.

Thanks

how to create table of contents with quill js

Is there any way to automatically list header tags as a table of content (TOC) in quilljs. I do search it but coudln’t find anything useful.

One can add id to header tags with the folloing code but how to create links to them?

let Header = Quill.import('formats/header');
Header.create = function(value) {
let header = document.createElement('h1');
header.id = 'some-unique-id';
  return header;
};

Is there a version or alternative of .appendChild() that lets you insert the element at a certain position instead? [duplicate]

I have a <div>that I’m procedurally adding elements to, but I want to insert them to the beginning of the <div> so that the newest elements appear at the top of the <div>, displacing existing elements downward. What is the best way to do this? Image provided for reference:

Previously, I used .appendChild() to add elements to <div>s but that only creates elements at the end of the <div>.

JavaScript for Chrome extensions

Good afternoon. I have questions about working with the Chrome API and I can’t find good manuals, or I just don’t understand what it says. I need to write an extension (manifest V3), which, by clicking on the button, replace each word of the web page with the word “meow”. There is a design and HTML basis and it can not be changed. But the JavaScript code is executed only inside the extension itself, and it needs to be executed in the active tab. I absolutely do not understand how to arrange it. I hope my description is not too crooked, I use a translator. I’ll attach the code.

background.html

<!DOCTYPE html>
<html>  
<body>
  <link rel="stylesheet"href="background.css"> 
  <h1 class="Mtr">meow translate</h1>
  <img src="catze.png" width="181" height="179" class="cat">
  <button id="trans">Meow-meow</button>
  <script src="background.js"></script>
</body>
</html>

background.css

body {
  margin: 0;
  width: 240px;
  height: 292px;
  background-color: #FF9BAA;
  display: flex;
  flex-direction: column;
  align-items: center;
}

#trans {
  width: 140px;
  height: 21px;
  font-family: 'Quiet Meows';
  font-size: 15px;
  line-height: 17px;
  background-color: #FF8295;
  border-radius: 15px;
}

.Mtr {
  font-family: 'Quiet Meows';
  font-weight: 400;
  font-size: 20px;
  line-height: 23px;
  color: #000000;
}

.cat {
  margin-bottom: 15px;
}

Manifest.json



{
    "name": "Meow Translator",
    "description": "Extract all images from current web page",
    "version": "1.0",
    "manifest_version": 3,
    "icons": 
    {
        "48":"icon48.png",
        "128":"icon128.png"
    },
    "action": {
        "default_popup":"background.html"
    },
    "permissions": ["scripting", "activeTab"],
    "background":{}
}

Background.js

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("trans").addEventListener("click", replaceWords);
});
function replaceWords() {
      var elements = document.getElementsByTagName('*');
      for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        var text = element.innerHTML;
        var words = text.split(' ');
        for (var j = 0; j < words.length; j++) {
          words[j] = 'meow';
        }
        element.innerHTML = words.join(' ');
      }
    }

The written word replacement function replaceWords in the JS file, works only inside the extension, that is, all the words specifically of the extension interface are replaced with “meow”, I don’t know how to make the code work on the active tab at the time of pressing the button. The extension is written for Chromium-based browsers.

Resolving a library projects SASS files from an application in the same workspace?

Is it possible to resolve SASS contained in a workspace library using an approach that is similar to resolving ts files from an application within the same workspace? For context I’ll setup a real workspace as follows:

ng new theme-workspace --create-application=false
cd theme-workspace
ng g library theme
mkdir projects/theme/src/lib/styles
touch projects/theme/src/lib/styles/index.scss
ng g application playground

Within the directory projects/sass/src/lib/styles we will add the following content to index.scss.

$color: red;

And in order to include the style assets we need to update ng-package.json with an asset block like this:

  "assets": [
    { "input": "src/lib/styles", "glob": "**/*.scss", "output": "styles" }
  ]

If we build this project library like this:

ng build theme

We see that dist/theme/styles contains index.scss.

We can access the generated ts component ThemeComponent like this from the playground.

import { ThemeComponent } from 'theme';

When using @use to import the SASS index.scss module is it possible to use a similar namespace?

For example if we try this from the playground styles.scss module it fails:

@use `theme/styles` as t;

This is the error.

SassError: Can't find stylesheet to import.
  ╷
2 │ @use 'theme/styles' as t;

Now we could resolve by using a relative file import, but I’m curious whether there’s a “Shorthand” way of doing it that uses the library name space?