How to get an html anchor tag from an external markdown file frontmatter property in astro?

I am building a component in Astro, which I want to fill with markdown from an Astro content collection. It all works, but I cannot get the markdown link from the md frontmatter to work as an html anchor tag in the component file.

This is the md frontmatter code:

---
[some md properties]
link: '[name](url) '
---

some markdown text

I first reference the different contents from the markdown file with template string literals and then try to replace the markdown in the anchor tag with some regex, but it only displays the md string as a working link:

import { getCollection } from 'astro:content';
const projects = await getCollection('projects');
console.log(projects);
---

{
  projects.map((project) => (
    <>
      <div id='project_cards' class='bg-secondary rounded-[5px]'>
        <div class='project_card flex-col bg-secondary'>
          <img src={`${project.data.image}`} alt={`${project.data.title}`} />
        </div>
        <div class='project_card_description flex flex-col gap-[60px] p-[60px]'>
          <SectionTitle sec1={`${project.data.title}`} sec2='' />
          <p class='project_description'>{project.body}</p>
          <div class='social_links'>
            <a href={`${project.data.link}`}>{`${project.data.link}`}</a>
          </div>
        </div>
      </div>
    </>
  ))
}

<script>
  //md links to html anchor tags
  const md_social_link = `${project.data.link}`;
  // md replacement for anchor tags
  const html_social_link = md_social_link.replace(
    /[([^[]+)]((([^)]*)))/gim,
    '<a href="$3" target?"_blank">$1</a>'
    /**
     * '<a href="$3">$1</a>': This is the replacement string for the matched pattern. It's HTML code that will be used to replace the Markdown-style link.
     *
     * <a href="$3">$1</a>: This is an anchor tag (<a>). $3 and $1 are placeholders that refer to the capturing groups in the regex pattern:
     * $3: This refers to the URL captured by the second capturing group ((([^)]*)))).
     * $1: This refers to the link text captured by the first capturing group ([^[]+).s
     **/
  );

  //append to div ".social_links"
  console.log(html_social_link);
  let div_social_links = document.querySelector('.social_links');
  // Check if div_social_links is not null before using it
  if (div_social_links) {
    div_social_links.innerHTML = html_social_link;
  } else {
    // Handle the case where .social_links is not found
    console.error('Error: .social_links element not found.');
  }
</script>

In the script part, I get the following error when hovering on the template string: Cannot find name "project". I suppose that there must be a problem with correctly referencing the frontmatter property, but I don’t know how I can fix it to work with a markdown link.
How can I achieve to effectively split the markdown link so that I can use it for the anchor tag? Is this even possible?

Send message through websocket to specific users

I have a Java application built by Spring Boot, and a simple application run on browser by JavaScript .

I can broadcast message to all users, and now I want to send message to different users according to their identities, but there’s some problems.

I’m a newbie about websocket and Javascript, I’ve searched for plenty articles, but still can’t figure out where the problem is.

Can someone give me a hint? Very appreciate!

The way I used to send to specific users is

messageTemplate.convertAndSend()

And here is my Java code :

@Controller
public class GreetingWSController {

    private SimpMessagingTemplate messageTemplate;

    public GreetingWSController(SimpMessagingTemplate template) {
        this.messageTemplate = template;
    }

    @MessageMapping("/login")
    @SendTo("/topic/greetings")
    public GreetingWS login(HelloMessage message) throws Exception {
        if (...) {
            System.out.println("A player has logged in.");
            return new GreetingWS("Welcome! You are the " + HtmlUtils.htmlEscape(order.toString()) + "th user.");
        } else {
            return start();
        }
    }

    public void start() {
        messageTemplate.convertAndSend("/topic/greetings", "Let's play!");
    }
}

And Websocket config :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket");
    }
}

My browser can receive the GreetingWS object returned inside the if section, but can’t receive the message sent by

messageTemplate.convertAndSend("/topic/greetings", "Let's play!");

in start function.

Here is my Javascript code :

const stompClient = new StompJs.Client({
    brokerURL: 'ws://localhost:8080/gs-guide-websocket'
});

stompClient.onConnect = (frame) => {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/greetings', (greeting) => {
        showGreeting(JSON.parse(greeting.body).content);
    });
};

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    stompClient.activate();
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
});

Async JS constructor via static “create” method – TypeScript types problem

I am working on the universal abstraction/base of the async constructor and it works fine with JavaScript.

But I’m stuck with correct TypeScript types, it should work like this:

const a: AnyClass = await AnyClass.create();

It works fine in JavaScript, but TypeScript types are wrong (missing at the moment).

Example of the similar class called DbConnection:

class DbConnection extends AsyncConstructor<[serverId: number, url: string]> {
    #serverId: number;
    #connection: Connection;

    protected constructor(serverId: number, url: string) {
        super(serverId, url);
        this.#serverId = serverId;
    }

    protected override async constructorAsync(serverId: number, url: string): Promise<void> {
        this.#connection = await DB.connect(url);
    }
}

The base class is:

class AsyncConstructor<CtorParams extends any[]> {
    protected constructor(...args: CtorParams) {}

    protected async constructorAsync(...args: CtorParams): Promise<void> {
        return Promise.resolve();
    }

    // =-->>> MISSING TYPES FOR THE NEXT METHOD: <<<--=
    static async create(...args: CtorParams) {
        const res = new this(...args);
        await res.constructorAsync(...args);
        return res;
    }
}

What type to specify for the return of the create method?

SignalR with ReactJs, 1 server multiple clients

I have an ASP.net web api BE server that uses signalR to send messages. Now the issue is that I have multiple clients listening to the same server. How can I have a unique key per client where BE sends message to only this client and FE listen to messages only dedicated to them?

my .net code:

the hub:

public class TestChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

the controller

    private readonly IHubContext<TestChatHub> _hubContext;

    public SignalRController(IHubContext<TestChatHub> hubContext)
    {
        _hubContext = hubContext;
    }

    [HttpPost("send")]
    public async Task<IActionResult> SendMessage(string user, string message)
    {
        await _hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
        return Ok();
    }

and my reactjs code:

import React, { useEffect, useState } from 'react';
import * as signalR from '@microsoft/signalr';

function App() {
  const [connection, setConnection] = useState(null);
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const newConnection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:7238/chat', {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .withAutomaticReconnect()
      .build();

    setConnection(newConnection);

    newConnection.start()
        .then(() =>console.log('SignalR Connected'))      
        .catch(err => console.log('SignalR Connection Error: ', err));

    newConnection.on('ReceiveMessage', (user, message) => {
      setMessages(prevMessages => [...prevMessages, { user, message }]);
    });

    return () => {
      newConnection.stop();
    };
  }, []);

  return (
    <div>
      <div>
        <h1>Received Messages:</h1>
        {messages.map((msg, index) => (
          <div key={index}>
            <strong>{msg.user}</strong>: {msg.message}
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;

what are the modifications needed in the code to achieve my requirements?

BJSpell and contenteditable div – Trying to position the error marks

I’m creating a basic spellchecker that uses the BJSpell.js library.

I’ve found I cannot reliably update the contenteditable div with the results without losing focus and/or cursor position. I’ve tried many, many ways to set the cursor back to where it was pre-check, but nothing works.

The current method is to apply a transparent element over the div, then set the marking in that.
This works, but the problem is the marks do not move with the text. For example, if I write ‘colour’ then it fails the check against a US dictionary, which is what I want. It marks the word in my hovering element at the position of the word. Also fine.

But if I then move that word, either by adding text before it or putting it onto a new line with Enter, the error mark stays floating where is originally was.
I don’t know how to move the mark to the position the word is now in.

Here is the code so far:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawcdn.githack.com/maheshmurag/bjspell/master/BJSpell.js"></script>
Test my wordz
<div id='my_editing_div' contenteditable='true' spellcheck='false' style='width:500px;height:300px;border:1px solid black;'></div>
.word-check {
  color: transparent;
}

.word-error {
  border-bottom: 3px solid orange;
}
var dictionary = 'https://rawcdn.githack.com/maheshmurag/bjspell/master/dictionary.js/en_US.js';
var lang = BJSpell(dictionary, function() {
  //
});

const containsBadWord = word => {
  const found = lang.check(word);
  return found;
}

const processSpellCheck = text => {
  const allWords = text.split(/b/);
  const newContent = allWords.map((word, index) => {
    word = word.replace(/[0-9]/g, '');
    word = word.replace(/[^ws]|_/g, '');
    var text = word;
    if(!containsBadWord(word.toLowerCase())) {
      text = $("<span />")
        .addClass("word-error")
        .text(word);
    }
    return text;
  });
  return newContent;
}

function initalizeSpellcheck(editorRef) {
  var editorSize = editorRef.getBoundingClientRect();
  
  var spellcheckContainer = $("<div />", {})
    .addClass("word-check")
    .prop("spellcheck", "false");
 
  var spellcheckSpan = $("<div />")
    .addClass("word-check-text-content")
    .css({
      width: editorSize.width,
      height: editorSize.height,
      position: "absolute",
      zIndex: -1
    });
  
  spellcheckContainer.append(spellcheckSpan);
  spellcheckContainer.insertBefore(editorRef);
  
  $(editorRef).on("keyup.spellcheck", function(event) {
  if(event.keyCode == 32||event.keyCode == 13){
      var newText = $(event.target).text();
      var newContent = processSpellCheck(newText);
        $(".word-check .word-check-text-content").text("");
        $(".word-check .word-check-text-content").append(newContent);
        }
  });
}

$(document).ready(function() {
  var editor = document.querySelector("#my_editing_div");
  initalizeSpellcheck(editor);
});

I can’t see how to include a code snippet This is running on a JSFiddle here.

If you enter some text with a non-US word that word highlights. But try moving the position of that word, or hitting Enter a few times then type again, and you’ll soon see the problem.

How do I fix this positioning issue?

RxJS@6 fromFetch with catchError does not catching the errors

I wanted to use the fromFetch method from RxJS in vanilla JS to improve pure fetch calls in legacy code.

It looks like this:

fromFetch(`${requestUrl}`, {
  method: 'GET',
  headers: {
    Authorization: `Bearer ${token}`
  },
  selector: (response) => response.json(),
}).pipe(
  catchError((err) => {
    // Do something with the error, then throw a custom error:
    return throwError('My Custom Error Message');
  }),
);

And in the place where I subscribe to this looks like:

observable.subscribe({
  next: () => {},
  error: () => {
    // Handle errors
  },
});

After all these error handling, sometimes (I have no idea why), but error message appears on the screen:
enter image description here

How should I catch the error from the fetch? Maybe the error is coming from the selector: (response) => response.json() and I should move it out and handle the error there?

how to horizontally Scrolling to specfic point in a slider

I’m creating a piano key style slider where once an element is clicked its grows in width. This creates a problem where if i click an item that is close to the edges of the screen or is already being cut of by the edge, the content is out of view and the user needs to scroll left or right to see the content.

My question is this: Is there a way to get an element in a slider, once, clicked, to move to a specific point past the left edge of the screen? For example have it position itself (with smooth transitions) 50px to the right of the far left edge of the screen?

this is what I’ve tried


<div id="slider-container">
  <div class="slider-content">
      <div class="cards-wrapper" id="card-wrapper">
        <div class="card slide-1 ">
          <div class="card-content">
          <div class="slider-hidden-text">
            content goes here
          </div>
        </div>
      </div>
  </div>


  <div class="slider-controls-wrapper">
    <div class="controls">
      <img id="left-arrow" src="">
      <img id="right-arrow" src="">        
    </div>    
  </div>
</div>

Javascript:


const buttonRight = document.getElementById("right-arrow");
const buttonLeft = document.getElementById("left-arrow");
const slider = document.getElementById("card-wrapper");
const sliderCards = document.querySelectorAll('.card');buttonLeft.addEventListener("click", ()=> {
    slider.scrollLeft -= 400;
});buttonRight.addEventListener("click", ()=> {
    slider.scrollLeft += 400;
});sliderCards.forEach((item) => {
    item.addEventListener('click', () => {
             if (item.classList.contains('active')) {
                  item.classList.remove('active')             }
                 else {
                    document.querySelectorAll('.card').forEach((el) => {
                    el.classList.remove('active');
                    });                    item.classList.add('active');
                    item.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});                 };
            });    });

Puppeteer page evaluate with node-html-parser

I am using puppeteer to automate-test a page, yet I want to do the DOM parsing with the npm node-html-parser, here is a sample code :

var { parse }    = require( 'node-html-parser');
const puppeteer = require('puppeteer');

var browser = await puppeteer.launch({ headless:true,
executablePath: chromium.path
});

const page = await browser.newPage();
await page.goto(myURL, {timeout: 0, waitUntil: 'domcontentloaded'});
var domm = await page.evaluate(() => { return document.querySelector('*').outerHTML.toString() });
const dom = parse(domm);

console.log(dom.querySelectorAll('div.myClass div')[0].querySelectorAll("a")[0].href); //this returns error or null

so when I parse it through puppeteer, the .href attribute doesn’t work. Normally it does.
If I try to log the anchor tag, I get something like the following

console.log(dom.querySelectorAll('div.myClass div')[0].querySelectorAll("a")[0]); 

...more stuff above
  childNodes: [
    HTMLElement {
      parentNode: [Circular *1],
      childNodes: [Array],
      rawAttrs: 'class="clickOn"',
      voidTag: [VoidTag],
      nodeType: 1,
      rawTagName: 'span',
      id: '',
      _parseOptions: {},
      classList: [DOMTokenList]
    }
  ],
  rawAttrs: 'class="clickOn" href="/clickedPath"',                  
  voidTag: VoidTag {
    addClosingSlash: false,
    voidTags: Set(28) {
      'area',
      'AREA',
      'base',
      'BASE',
...more stuff down below

If i try to log the rawAttrs, i get this like below

console.log(dom.querySelectorAll('div.myClass div')[0].querySelectorAll("a")[0].rawAttrs) //output below 

class="clickOn" href="/clickedPath"

So it means that the parser somehow fails to parse some attributes when I am passing through evaluation of puppeteer.. I need to use the parser for performance for later use. How can I parse the .href or what is called rawAttrs with this parser, or somehow fix it through the puppeeteer ?

Angular Okta-SignIn-Widget – observe event or hook when Allowed into an application or not

Right now, everything is working great – just need to be able to subscribe, or find an event or hook so I can log a successful login vs:

user is not assigned to the client application

Now these both come back from Okta as a success because the user is Authenticated, but not necessarily a user with access to said application. We have users that can be part of one or many applications, my question is:

How do I hook into the widget to whether or not a user has logged in successfully, and is there a way to tell if this error pops up (ie not allowed to use said Okta application)?

Object.FromEntries is not creating json array as it is supposed to

Im working on a webscraper in Node.js and trying to create a JSON array from it.
Ive created a map in the way it is explained in the documentation like this:

// GET ALL TEXT VALUES
    const innerTexts = await page.evaluate(
      () => {
        const nodes = [...document.querySelectorAll('.result-page-list-results #wt-watches .article-item-container.article-image-carousel')];
        const texts = nodes.map(node => [
          ['title', node.querySelector('.article-item-container > a > div > .text-sm.text-sm-md')?.innerText.trim()],
          ['reference', node.querySelector('.article-item-container div div .text-sm.text-sm-md.text-bold')?.innerText.trim()],
          ['price', node.querySelector('.article-item-container > a > div > .d-flex.justify-content-between > div > .text-bold')?.innerText.trim()],
          ['shipping', node.querySelector('.article-item-container > a > div > .d-flex.justify-content-between > div > .text-muted')?.innerText.trim()],
          ['location', node.querySelector('.article-item-container > a > div > .d-flex.justify-content-between > div > button > span')?.innerText.trim()],
          ['images', node.querySelector('.article-item-container > a img').getAttribute("src").trim()],
          ['link', 'https://www.chrono24.nl' + node.querySelector('.article-item-container > a').getAttribute("href").trim()],
          ['shop', 'Chrono24'],
        ]);
        return texts;
      }
    );

This correctly forms the array and it looks the way I need it to convert it into a json array. I then use Object.FromEntries to create a json array from it. As you can see, it does not translate correctly and almost looks like it just ignores some quote marks and skips most of the data.
Does anybody know why this happens?

{
  'title,SBGE285 Mistflake': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,SBGE285': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring drive SBGE285 (NEW)': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring Drive GMT SBGE285': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,SBGE285 Grand Seiko Evolution 9 Collection 9R66 NEW watch': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring Drive GMT Ref SBGE285': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring drive watch SBGE285': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring drive SBGE285 SBGE285G': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  "title,Spring drive men's watch SBGE285": [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,41mm Titanium Case Silver Dial Titanium Bracelet SBGE285 NEW - Warranty: 2024': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring Drive': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring Drive GMT Titanium EVOLUTION 9 (SBGE285G)': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,SBGE285 SBGE285G Spring drive watch': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Grand Seiko Evolution 9 Collection': [ 'reference', 'Seiko GS' ],
  'title,SBGE285G': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring Drive GMT Titanium': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,"Mistflake" Spring Drive GMT Titanium Caliber 9R66 SBGE285': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,グランドセイコー エボリューション9 コレクション スプリングドライブ GMT / GRANDSEIKO EVOLUTION 9 COLLECTION SPRINGDRIVE GMT': [ 'reference', 'Seiko GS' ],  
  'title,Spring Drive SBGE285': [ 'reference', 'Grand Seiko Evolution 9 Collection' ],
  'title,Spring Drive GMT': [ 'reference', 'Grand Seiko Evolution 9 Collection' ]
}

I tried cleaning up the values with trim() and deleting breaks but this has not worked. I am using Puppeteer to do the scraping.

How To Dismiss Parent Navigator In React Native?

I have a layout as per the below;

const CheckoutStack = createNativeStackNavigator();
export default function CheckoutLayout() {
  return (
    <CheckoutStack.Navigator
      initialRouteName="Checkout"
      screenOptions={{ headerShown: true }}>
      <CheckoutStack.Screen
        name="Checkout"
        component={CheckoutScreen}
        options={{
          headerShadowVisible: false,
          headerTitle: "",
          headerRight: () => <CloseButton />,
        }}
      />
      <CheckoutStack.Screen
        name="PaymentSuccess"
        component={PaymentSuccessScreen}
        options={{
          headerShown: false,
          presentation: "fullScreenModal",
        }}
      />
    </CheckoutStack.Navigator>
  );
}

I am currently in the PaymentSuccessScreen and I want to dismiss both the current screen AND the CheckoutScreen. Essentially dismiss the CheckoutLayout. How do I do this?

I have tried;

navigation.dispatch(StackActions.pop(2));
navigation.dispatch(StackActions.popToTop());

Here is how I present the CheckoutLayout;

  <AuthorizedStack.Screen
    name="CheckoutLayout"
    component={CheckoutLayout}
    options={{
      presentation: "fullScreenModal",
      headerShown: false,
    }}
  />

ReferenceError: “y” is not defined [closed]

so i was following this tutorial (https://www.youtube.com/watch?v=JEEcbVjLyr0&list=PLpmb-7WxPhe0ZVpH9pxT5MtC4heqej8Es&index=7) and i had an issue

code :

const fs = require('fs');
const path = require('path');

module.exports = (directory, foldersOnly = false) => {
   let fileNames = [];

   const files = fs.readdirSync(directory, { withFileTypes: true });

   for (const file of files) {
    const filePath = path.join(directory, file.name);

    if (foldersOnly) {
        if (file.isDirectory()) {
            fileNames.push(filePath)
        }
    } else {
        if (file.isFile()) {
            fileNames.push(filePath)
        }
    }
   }

   return fileNames;
}

error :

there was an error: ReferenceError: getAllFiles is not defined 

To validate the dropdown fields of multiply rendered single component

I have a component say return card
in which i have used two custom dropdown components

Also I am using return card component in page

We are using vee-validate to validate forms

I am using two variable to assign the defineComponentBinds for field reference and passing it to the return card component

The problem is :

I am rendering the return card component using v-for
when validated it is applying for all components, even trying with index
it must apply only to those selected one and also the dropdown to those selected one

Project: nuxt3

Thanks!

I am using two variable to assign the defineComponentBinds for field reference and passing it to the return card component

The problem is :

I am rendering the return card component using v-for
when validated it is applying for all components, even trying with index
it must apply only to those selected one and also the dropdown to those selected one