How to make a link preview blot in Quill editor on link paste?

When user pastes a link into editor, the link should be converted to preview (title, image, description, etc.)

First created a PreviewBlot

const REGEXP_URL = /https?://[^s]+/g;

export class PreviewBlot extends Link {
  static blotName = 'preview';
  static className = 'ql-preview';
  static tagName = 'div';

  static create(value: string): HTMLElement {
    console.log('should create preview');  // not called on 2nd approach
    const node = super.create(value);
    // Fetch metadata and append to node
    fetch(`http://localhost:3000/opengraph?url=${encodeURIComponent(value)}`)
      .then(response => response.json())
      .then(metadata => {
        const preview = document.createElement('div');
        preview.innerHTML = `
          <img src="${metadata.image}" alt="${metadata.title}" />
          <h3>${metadata.title}</h3>
          <p>${metadata.description}</p>
        `;
        node.appendChild(preview);
      });
    return node;
  }
}

Next you need to intercept that user pastes a link:

quill.clipboard.addMatcher(Node.TEXT_NODE, (node, delta) => {
    if (node.nodeName !== '#text') {
      return delta;
    }
    const textNode = node as Text;
    const matches = textNode.data.match(REGEXP_URL);
    if (matches && matches.length > 0) {
      console.log('USING MATCHER');
      const ops = [];
      let str = textNode.data;
      matches.forEach(match => {
        const split = str.split(match);
        const beforeLink = split.shift();
        ops.push({insert: beforeLink});
        console.log('should push preview');
        ops.push({insert: match, attributes: {preview: match}});
        str = split.join(match);
      });
      ops.push({insert: str});
      delta.ops = ops;
    }
    return delta;
  });

The matcher is called when you cut text from editor and paste in back.

The matcher is not called when you copy a link from browser’s address bar and paste the link into editor.

I consider this may be a bug in Quill.

So I tried 2nd approach:

quill.on('text-change', delta => {
    const ops = delta.ops;
    const insert = ops?.[ops.length - 1]?.insert;
    const matches = typeof insert === 'string' && insert.match(REGEXP_URL);
    if (matches && matches.length > 0) {
      console.log('USING EVENT');
      const ops = [];
      let str = insert;
      for (const match of matches) {
        const split = str.split(match);
        const beforeLink = split.shift();
        ops.push({insert: beforeLink});
        ops.push({insert: match, attributes: {preview: match}});
        str = split.join(match);
      }
      ops.push({insert: str});
      delta.ops = ops;
    }
  });

But this time the PreviewBlot is not inserted despite we change ops in delta to create the preview.

Working example: https://stackblitz.com/edit/stackblitz-starters-ctmwke?file=src%2Findex.html

Case 1: copy a link from browser’s address bar and paste into editor – doesn’t work

Case 2: cut link from editor and paste it back – the proper PrewiewBolt is inserted

How to generate package-lock.json back in a date?

I’m trying to modify a JS/node project which has package.json but not package-lock.json file committed. The author also does not have the original package-lock.json because newer versions has been developed.

However, generating a new package-lock.json makes the project failure to run, due to changes in the dependencies. This is because the generation happens now and uses the up-to-date (compatible) dependencies.

So, is there a way to generate a package-lock.json as if it was generated back at a specific date/time in history, using the up-to-date dependencies back then?

How do I change env variables after getting build?

I am dealing with a project written with SvelteKit. In some cases, I need to change the .env files when there is a change in the servers I get the build from and I need to get the build every time I change it. What I’m wondering is that I can make changes to appsettings.json even after I get the build in my ASP.NET project and I just need to restart it through IIS. How can I do the same thing in SvelteKit and how can I access it from inside?

Vue Router not finding query params

Vue 3, Vue Router 4, web hash history router

I have a url with a query param that gets inserted, but Vue seems to ignore it and it’s causing weird redirect issue for my application.

For example:

Is: Https://example.com/?foo=bar#/

Should be: Https://example.com/#/?foo=bar

I don’t know why the #/ is getting stuck on the end and Vue must be looking after that to find any query params, so that seems to be why it’s not being found. Any ideas?

Error: Pica: cannot use getImageData on canvas, make sure fingerprinting protection isn’t enabled

I am trying to use pica (//cdn.jsdelivr.net/gh/nodeca/pica/dist/pica.js) in my service-worker using the following code, but get the error Error: Pica: cannot use getImageData on canvas, make sure fingerprinting protection isn't enabled when I call pica.resize():

(file was sourced from a UI )

service-worker.js:

    const imageBitmap = await createImageBitmap(file);
    const { newWidth, newHeight } = getNewDimensions(imageBitmap.width, imageBitmap.height, maxWidth, maxHeight);

    const picaCanvas = new OffscreenCanvas(newWidth, newHeight);
    picaCanvas.width = newWidth;
    picaCanvas.height = newHeight;
    const picaCtx = picaCanvas.getContext('2d');
    picaCtx.drawImage(imageBitmap, 0, 0, newWidth, newHeight);

    const resizingCanvas = new OffscreenCanvas(newWidth, newHeight);
    const resizer = pica({ features: ['wasm', 'ww'] });

    await resizer.resize(picaCanvas, resizingCanvas, { // <------ ERROR OCCURS HERE
        quality: 3 //  [0='box', 1='hamming', 2='lanczos2', 3='lanczos3']
    });

The code is creating the [OffscreenCanvas]Canvas so why do I get a fingerprint error – and how I work around this (remembering that this is coming from a service-worker)?

React js with flask production bulid

I am trying to build a React application with an Apache2 server, and we have communicated with the Flask backend. it will not be communicating with the web UI.

we want to best solution of react build app comunication with flask server

Back button not working after history.push from message eventlistener (window.postmessage)

We have two types of pages on our website – react pages and iframe pages (in django template).

We are handling redirection from iframe pages to react pages through window.postMessage.

In django template javascript code:

window.parent.postMessage(JSON.stringify(postData), "https://" + main_domain);

In react code:

let { name } = useParams();

useEffect(() => {
  function handleMessage(e, originName) {
    if (originName === "from_iframe1") {
      props.history.push("next_url1");
    }
    else if (originName === "from_iframe2") {
      props.history.push("next_url2");
    }
  }
  
  if (name === "react_url1") {
    window.addEventListener("message", e => handleMessage(e, "from_iframe1"), false);
  }
  else if (name === "react_url2") {
    window.addEventListener("message", e => handleMessage(e, "from_iframe2"), false);
  }
  else {
    window.removeEventListener("message", e => handleMessage(e, "others"), false);
  }
}, [name]);

The problem is that the browser stack is behaving in a very weird manner. After first redirection, it takes 2 clicks to go back. Next, it takes 4 clicks and then 6 clicks.

On using history.replaceState, it works perfectly on first redirection. But after that, it goes back multiple pages instead of one.

Please let me know if there is any known solution to this problem or some other approach we can try. Also, please mention if there is any other information needed.

Is it possible to use a global error handler to show a react error component instead of a broken component

I use the react-error-boundary library, is there no way to make a global error component in it, so that when any component breaks, an error component is substituted instead, while IT is IMPORTANT that the application continues its work, only the broken component is replaced. Maybe you should use another library for this?

The main thing is not to wrap each component in error boundary, but the entire application and the problem area itself should be wrapped in error boundary.

When an error occurs in any component in the application, it does not break with a white screen, the non-working component is replaced by ErrorComponent.

I will be glad of any help.

This code is not suitable for the solution:

export const App = withErrorBoundary(() => (
    <div className="maincontainer">
        <Provider store={store}>
            <Router history={routerHistory}>
                <Localization>
                    <Navigation />
                </Localization>
            </Router>
        </Provider>
    </div>
), {
    onError: (...params) => {
        console.log("params", params)
    },
    FallbackComponent: ErrorBoundary
})

How to add Microsecond, Nanosecond data and how to format Ticks, tooltip in LightningChart js

I am using the LightningChart JS (trial version) in my Angular 17 application. I am trying to plot a linear-highPrecision multi-channel real time data in microseconds & nanoseconds using WebSockets. I am using a line chart and in it I am using time tick strategy.

The issue that I am facing is that when I plot microsecond data, the format of the ticks labels and tooltip shows information of X axis in milliseconds instead of showing in microseconds. It also shows the hours part in a weird format e.g. 441186.59.59.108. The same goes for the nanosecond data. It is shown in the attachment below.

My Current Result

The JSON I receive from the API is like this

[
    {
        "X": "2020-04-30T23:59:58.500001",
        "Y": 295
    },
    {
        "X": "2020-04-30T23:59:58.500002",
        "Y": 293
    },
    {
        "X": "2020-04-30T23:59:58.500003",
        "Y": 294
    },
    {
        "X": "2020-04-30T23:59:58.500004",
        "Y": 294
    }
]

I have almost 50K data points for microsecond and 10M data points for nanosecond channels.

My expected result is that when I plot microsecond data then ticks and tooltip should show data in microsecond e.g. 23:59:58.500001 and for nanosecond it should show 23:59:58.500000001.

HTML not doing what isn’t supposed to [closed]

I’m trying to add a box at the bottom middle of my screen that’s centered and each line goes as much as it wants unless it reaches the full screen then it goes to a new line, I should have coded it correctly out for some reason the max-width isn’t working, the text always goes to 710px then goes puts a line break, no matter what I put the max-width as it always put a line break right there, and no the text that goes there doesn’t have line breaking in it so it can’t be that.

.newalertbox {
  position: fixed;
  bottom: 30px;
  right: 50%;
  background-color: rgba(0, 255, 255, 0.8);
  padding: 5px;
  border-radius: 5px;
  z-index: 1001;
  margin: 0 auto;
  box-sizing: border-box;
  font-weight: bold;
  max-width: 75%;
  width: auto;
  overflow: hidden;
  align-items: center;
  text-align: center;
  transform: translate(50%);
  font-size: 12px
}
<div class="newalertbox">
  <span id="newalerttext"> Special Weather Statement has been issued by NWS Binghamton NY at 1:14pm (Wind= 45 MPH Hail=0.75in) </span>
</div>

State’s content only being set after i press ctrl + s

I am trying to organize the content of an array (that is also a state) and then, take this organized data to set this value into another state.
The problem is that even inserting the process into a promise and making the set state into then() function the state isnt getting updated correctly.

I wrote a console.log to show the content and it just show up if i save my code again making a CTRL + S in my code editor.

You can take a look in the code… I don’t know whats wrong.

async function organizaBairros(){
        const pedBairro = {};

        const processPedidos = (pedidos, status) => {
            pedidos.forEach(pedido => {
                const bairro = pedido.nbl_bairro;
                if (!pedBairro[bairro]) {
                    pedBairro[bairro] = {
                        totalNotasA: 0,
                        totalNotasP: 0,
                        totalNotasS: 0,
                        totalValueA: 0,
                        totalValueP: 0,
                        totalValueS: 0
                    };
                }
                if (status === 'A') {
                    pedBairro[bairro].totalNotasA += 1;
                    pedBairro[bairro].totalValueA += pedido.nbl_total_nota;
                } else if(status === 'P') {
                    pedBairro[bairro].totalNotasP += 1;
                    pedBairro[bairro].totalValueP += pedido.nbl_total_nota;
                } else if(status === 'S') {
                    pedBairro[bairro].totalNotasS += 1;
                    pedBairro[bairro].totalValueS += pedido.nbl_total_nota;
                }
            });
        };
    
        Promise.all([
            processPedidos(jsonPedidosA, 'A'),
            processPedidos(jsonPedidosP, 'P'),
            processPedidos(jsonPedidosS, 'S')
        ]).then(() => {
            console.log(pedBairro)
            setPedidosBairro(pedBairro);
        }).catch(error => {
            console.error('An error occurred:', error);
        });
    }

Child item overlaps border of parent item

I have the following issue in React Native:

enter image description here

As you can see there is a white line between the child item and its parent and I cannot determine the cause. The line stays even if I apply absolute positioning with width = 100% on the child item.

Here is the code:

<Pressable style={ [ styles.mealItem, index === dataProps?.item.mealNutrients.length - 1 ? { borderBottomWidth: 0 } : {}, { backgroundColor: mealNutrient.eaten === null && !dataProps.isAfter ? COLOR_MAP.white : (mealNutrient.eaten === true ? COLORS.completed : COLORS.failed) } ] }
           onPress={ () => onNutrientCheckedChanged(mealNutrient.id)}
           key={ mealNutrient.id }>
           {
                loadingId !== null && loadingId === mealNutrient.id ?
                <View style={ [styles.mealItemCheckbox, { borderColor: 'transparent', backgroundColor: 'transparent' }] }>
                    <MaterialIndicator size={16} color={ COLOR_MAP.black } />
                </View>
                :
                (
                    mealNutrient.eaten === null && !dataProps?.isAfter
                    ?
                        <View style={ styles.mealItemCheckbox } />
                    :
                    mealNutrient.eaten === true ? <Icon name="checkmark-circle-sharp" size={24} color={COLOR_MAP.success} /> : <Icon name="close-circle-outline" size={24} color={COLOR_MAP.alert} />
                )
            }
            <View style={ { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', width: '100%', columnGap: 4 } }>
                <Text style={ [styles.mealItemTitle, { color: mealNutrient.eaten === null && !dataProps?.isAfter ? COLOR_MAP.black : (mealNutrient.eaten === true ? COLOR_MAP.success : COLOR_MAP.alert), minWidth: '75%', maxWidth: '75%' }] }>{ mealNutrient.name }</Text>
                <Text style={ [styles.mealItemTitle, { color: mealNutrient.eaten === null && !dataProps?.isAfter ? COLOR_MAP.black : (mealNutrient.eaten === true ? COLOR_MAP.success : COLOR_MAP.alert) }] }>{ mealNutrient.quantity + ' ' + mealNutrient.measuringUnit }</Text>
            </View>
</Pressable>
const containerStyle = {
                        backgroundColor: 'rgba(104, 214, 151, 0.2)',
                        borderWidth: 1,
                        borderColor: COLOR_MAP.success,
                        borderRadius: 4,
                        flexDirection: 'column',
                        justifyContent: 'space-between',
                        minHeight: 120,
                        overflow: 'hidden'
                       };
const statusContainerStyle = {
                         borderBottomLeftRadius: 4,
                         borderBottomRightRadius: 4,
                         backgroundColor: COLOR_MAP.success,
                         flexDirection: 'row',
                         columnGap: 4,
                         padding: 8,
                       };

I’ve tried absolute position of the child with no success. I’ve tried moving the item with a margin but it moves it too much.

Unmatched route on react-native

Hello, I have a project structured like the picture. I want to go from GetStarted.js to Instruction.js. I’m using the following code:

                <View>
                    <TouchableOpacity style={styles.button} 
                        onPress={() => router.push('./Instructions.js')}
                    >
                        <Text style={styles.buttonText}>
                            Welcome
                        </Text>
                    </TouchableOpacity>
                </View>

but I get an Unmatched Route error. I’ve tried with differents folders and it works.
I don’t understand which one is the correct code to switch to a file.js in the same folder. (In this case ‘components’.
I’m pretty sure it’s a simple solution but I can’t find it.