Can’t compile an optional Node.js dependency with Angular compiler

I’ve created an npm library containing code that looks like this:

let _Buffer: typeof Buffer;
let _require: NodeRequire;
let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void;

try {
  _Buffer = typeof Buffer !== undefined && Buffer;
  _require = typeof require !== undefined && require;

  if (_Buffer && _require)
    _readFile = _require('fs').readFile;
}
catch {}

I’ve managed to make parts of the above code work in other projects, like the optional dependency on Buffer. The use of require wasn’t something I’d tried before, and this is what’s now causing me grief. Angular is determined to try to resolve the dependency on fs, no matter how I try to hide it (including silly things like _require('f' + 's')), causing an error like this:

./node_modules/@tubular/astronomy/dist/fesm2015/index.js:3:300-4:1 – Error: Module not found: Error: Can’t resolve ‘fs’ in ‘/Users/kshetline/programming_projects/svc-ng/node_modules/@tubular/astronomy/dist/fesm2015’

What I’d most like to do is figure out a way to design the npm library so this isn’t an issue at all.

A less satisfactory solution would be to find a way to tell the Angular compiler to ignore this particular external dependency. That’s a difficult subject to google, however, because searches all come up with information regarding the Angular dependency injection system, not about this type of compile-time dependency.

The goal is to allow the library to have extra Node.js features when used in a Node.js environment, but still run smoothly in a browser when those features are not available.

Save the Promise.all into two variables

I have this code and I want save the result of Promise.all into two variables.
The problem is that I gets undefined when (this.data = data)

    const {data,recents} : any = await Promise.all([
      this.$store.dispatch('algo', input),
      this.$store.dispatch('algo', input)
    ])
    this.data = data
    this.recents = recents

Blockhash not found when sending transaction

When sending a transaction using Solana web3, it sometimes shows this error:
Error: failed to send transaction: Transaction simulation failed: Blockhash not found

What is the proper way of dealing with this error other than retrying for x amount of times?
Is there a way to guarantee this issue won’t happen when sending transactions?

What is the proper way to calculate price given checkboxes and quantity within React?

Customers are selecting restaurant items that have options like toppings. I’m using checkboxes to allow the customer to select what options, with each checkbox having the added price of the option inside of the HTML value attribute.

There is also a quantity component that uses a callback to modify a React state.

(example of checkboxes, and quantity selection)

The code I’ve come up with to handle all of this is as follows:

    const [basePrice, setBasePrice] = useState(0);
    const [price, setPrice] = useState(0);

    useEffect(() => {
        let insert = parseFloat(props.item.price);
        setBasePrice(insert.toFixed(2));
        setPrice(insert.toFixed(2));
        setQuant(1);
    }, [props.item])

    useEffect(() => {
        calcPrice();
    }, [quant])

    const calcPrice = () => {
        let checked = document.querySelectorAll('input:checked');
        let insert = parseFloat(basePrice);

        for (let i of checked) {
            insert += parseFloat(i.value);
        }

        insert *= parseFloat(quant);

        setPrice(insert.toFixed(2));
    }

calcPrice() is also called within the onchange attribute of the div containing all of the checkboxes. Anytime a customer clicks on a checkbox, it calls calcPrice().

the first useEffect() just resets the display price (setPrice(insert.toFixed(2)) and runs every time the user selects a different item.

The problem I’m having is that whenever the customer selects an option, increases the quantity, and then switches to a new item, it doesn’t display the right price. It calls the second useEffect() before let checked = document.querySelectorAll() has a chance to run, and uses the boxes checked from the last item.

price has the $3 from last item

I have spent a full week and a half trying to combine the quantity and checkboxes properly, and–knowing that I am more than likely too stupid to see the obvious solution–am asking for help on this.

Animate text with array

I’m trying to animate text with javascript using an array with time intervals e.g. t te tex text, I want it to cycle from 0 to 21 and back and I’m not entirely sure how to do it. Any help is muchly appreciated!

Why does “info()” not work even though the “read” field changes?

I have a factory function, where I am returning a Book Object. When I create an object of the Book and change a field value, this is not reflected in the method of the Object. Any idea why this may be happening?

const Book = (title, author, pages, read) => {
    const info = () => {
        if (read == true) {
            return `${title} by ${author} - ${pages} pages - already read`;
        } else {
            return `${title} by ${author} - ${pages} pages - not read yet`;
        }
    }
    return { title, author, pages, read, info }; 
}

I create a Book Object using let book = Book(title, author, pages, read);
And change the value of read by accessing the read field directly.
However, when I change the value of read, this is not reflected in the info method.

ShieldUI Grid Resizing

I’m currently evaluating the demo version of ShieldUI and have been playing with the grid control. I’ve bound to a local datasource and am trying to get column resizing working properly, but when I attempt to resize individual columns, there is a large jump as the column I am resizing is resized much larger and all the other columns are sized smaller. I’m guessing I have a CSS issue as the example on the ShieldUI site only changes the size between two adjacent columns, but can’t figure out what I need to change in my style rules to get the same behavior as the example. Here’s the code I’m using, with no additional styles defined other than linking to the full minimized ShieldUI CSS:

$("#grid1").shieldGrid({
    dataSource: {
        data: HRDataset
    },
    paging: {
        pageSize: 10
    },
    sorting: {
        multiple: false,
        allowUnsort: false
    },
    columns: [
        { field: "Employee_Name", title: "Employee Name", width: 30 },
        { field: "EmpID", title: "ID", width: 10 },
        { field: "Salary", title: "Salary", width: 20 },
        { field: "Position", title: "Position", width: 30 },
        { field: "State", title: "State", width: 10 },
        { field: "Zip", title: "Zip", width: 15 },
        { field: "Sex", title: "Sex", width: 10 },
        { field: "MaritalDesc", title: "Married", width: 10 }
    ],
    scrolling: true,
    resizing: true
});

Create kind of carousel Vue

So, I have a dashboard where I want to display some cards. There should only be four visible at a time and when clicking on the arrow you just want to move one step to the next card. So let’s say cards 1-4 are showing and when clicking the right arrow you should be able to see 2-5. Right now I only have that when you click the right arrow you jump pass 1-4 and go straight to 5-10.

So right now I have this:

computed: {
    cardsToDisplay(): Status[] {
        return this.cards.slice(this.page * 4, (this.page + 1) * 4)
    },
},
methods: {
    setCards(no: number) {
        this.page = this.page + delta
    },
},

And in the template the left and right arrow buttons look like this:

        <v-icon v-if="page !==" class="black--text font-weight-bold" 
          @click="setPage(-1)">
          chevron_left</v-icon>

        <v-icon
            v-if="columns.length > (page + 1) * 4"
            class="black--text font-weight-bold"
            @click="setPage(1)"
            >chevron_right</v-icon
        >

But how can I make it just move to the next card? 🙂

DrafJS editorState html conversion is different than what the editor window displays

I’m making a rich text editor widget for netlifyCMS. I’ve already tried react-draftjs-wysiwyg but netlifyCMS doesn’t seem to be able to handle styling through classNames. So I figured I would try my hand at figuring out draftjs.

On the left is my draftJS rich text editor. And at the very top right is the draftjs-to-html conversion. As you can see, the first line is bold, so that works fine. So at least I know that I am handling state somewhat correctly.

When I change font size, the editor seems to be able to preview that properly. But when I take the editorState and convert it to html it loses the fontSize. When I log the editorState converted html it just comes out as a normal p tag with no fontSize styling.

enter image description here

Here is my custom netlifyCMS widget

import React, { Component } from "react"
import MarkdownContent from "../page-blocks/MarkdownContent"

import {Editor, EditorState,convertToRaw, RichUtils} from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import 'draft-js/dist/Draft.css'
import createStyles from 'draft-js-custom-styles'

export class RichTextEditorControl extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
      isShowingFontSizeMenu: false,
    };
    // this.onChange = editorState => this.setState({editorState});
    this.handleKeyCommand = this.handleKeyCommand.bind(this);
}

onEditorStateChange = (editorState) => {
    this.setState({editorState});
    this.props.onChange(editorState)
};

// allows user to ctrl+b, ctrl+i, etc...
handleKeyCommand(command, editorState) {
    const newState = RichUtils.handleKeyCommand(editorState, command);

    if (newState) {
    this.onEditorStateChange(newState);
    return 'handled';
    }

    return 'not-handled';
}
_onBoldClick (e) {
  e.preventDefault()
  this.onEditorStateChange(RichUtils.toggleInlineStyle(
          this.state.editorState, 'BOLD'))

}
_onItalicClick (e) {
  e.preventDefault()
  this.onEditorStateChange(RichUtils.toggleInlineStyle(
          this.state.editorState, 'ITALIC'))
}
_onFontDropDownClick (e) {
  e.preventDefault();
  this.state.isShowingFontSizeMenu = !this.state.isShowingFontSizeMenu
  this.onEditorStateChange(this.state.editorState) //force re render to display drop down
}
_setFontSize(e, value, styles) {
  e.preventDefault()
  //remove current font size at selection
  const newEditorState = styles.fontSize.remove(this.state.editorState)
  //toggle dropdown
  this.state.isShowingFontSizeMenu = !this.state.isShowingFontSizeMenu
  //set editorState to display new font size
  this.onEditorStateChange(styles.fontSize.add(newEditorState, value))
}

render() {
  const {styles, customStyleFn} = createStyles(['font-size'])
  //map array of integers to display options for dropdown
  const fontSizes = [8, 10, 12, 14, 16, 18, 20, 24, 28, 32, 38, 46, 54, 62, 72]
  const fontSizeOptions = fontSizes.map(fontSize => (
          <div
              key={`font-size-${fontSize}`}
              onMouseDown={e => this._setFontSize(e, `${fontSize}px`, styles)}
          >{fontSize}</div>
      ))
    return (
        <div style={{marginTop:"20px"}}>
          {/* toolbar */}
          <div>
            <button onMouseDown={this._onBoldClick.bind(this)}>B</button>
            <button onMouseDown={this._onItalicClick.bind(this)}>I</button>
            <button
                onMouseDown={this._onFontDropDownClick.bind(this)}
            >
              Font Size
            </button>
                {/* open or close menu if the button is pressed. */}
                {this.state.isShowingFontSizeMenu ?
                    <div>
                        {fontSizeOptions}
                    </div> : null
                }

          </div>
          <div style={{border:"1px solid black", borderRadius:"2px", padding:"5px", marginTop:"20px"}}>
            <Editor
                editorState={this.state.editorState}
                handleKeyCommand={this.handleKeyCommand}
                onChange={this.onEditorStateChange}
                customStyleFn={customStyleFn}
            />
          </div>
        </div>
    );
}
}

export const RichTextEditorPreview = ({ value }) => {
  console.log(draftToHtml(convertToRaw(value.getCurrentContent())))
  return <MarkdownContent content={draftToHtml(convertToRaw(value.getCurrentContent()))} />
}

How to implement section wipe from ScrollMagic into horizontal website?

So far I built a horizontal scrolling page in html and css in reference to this article (https://redstapler.co/pure-css-horizontal-scrolling-website-tutorial/). Now I want to include wiping between two sections on the first slide using Scroll Magic (https://scrollmagic.io/). Unfotunatly I’m not being able to connect both code snippts together. Can somebody help me with this? I basically want the section .panel.first to be slided onto .slide.one while scrolling to then go forward to the next slide.

$(function () { // wait for document ready
    // init
    var controller = new ScrollMagic.Controller({vertical: false});

    // define movement of panels
    var wipeAnimation = new TimelineMax()
        .fromTo("section.panel.first", 1, {y: "-100%"}, {y: "0%", ease: Linear.easeNone}); // in from top

    // create scene to pin and link animation
    new ScrollMagic.Scene({
            triggerElement: ".slide.one",
            triggerHook: "onLeave",
            duration: "100%"
        })
        .setPin(".slide.one")
        .setTween(wipeAnimation)
        .addIndicators() // add indicators (requires plugin)
        .addTo(controller);
});
body {
  margin: 0;
  padding: 0;
}

/* horizontales scrollen */
.slide {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.wrapper {
  display: flex;
  flex-direction: row;
  width: 400vw;
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
}

.outer-wrapper {
  width: 100vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

::-webkit-scrollbar {
  display:none;
}

/* Seite 1 - Startseite */
.one {
  background-color: #FFB111;
  width: 100vw;
}

.panel {
    height: 100%;
    width: 100%;
    position: absolute;
}

.panel.first {
    background-color: black;
}
/* Seite 2 */
.two {
  background-color: #FD5145;
  width: 100vw;
}

/* Seite 3 */
.three {
  background-color: #87B6A7;
  width: 100vw;
}

/* Seite 4 */
.four {
  background-color: #305252;
  width: 100vw;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js"></script>
  </head>
  <body>
    <div class="outer-wrapper">
      <div class="wrapper">
        <div class="slide one">
          <section class="panel first">

          </section>
        </div>
        <div class="slide two"></div>
        <div class="slide three"></div>
        <div class="slide four"></div>
      </div>
    </div>
  </body>
</html>

Display text when timer reaches 0s, and add 0 before 1-9s

I want to display some text once the timer goes to 0:00, and when the timer is anywhere in between 1-9s, I want to display a 0 in front of the seconds, e.g. 1:04 instead of 1: 4. How would I do this?

const timeSpan = document.getElementById('timer');
var sec = 600 / 60;
const mins = sec;
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;


setInterval(() => {
  var currentTime = new Date().getTime();
  var distance = deadline - currentTime;
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);


  timeSpan.innerHTML = minutes + ':' + seconds;
  
}, 500)

How to use quills setSelection?

I am writing a custom module for quilljs. It is a simple text macro replacement tool.

ie type “.hi”, it will replace it with “hello”.

I have everything working, but the last step is meant to reposition the cursor at the end of the inserted text, but it leaves the cursor in the original location.

the problem is with line #31 quill.setSelection(…), here is the Quill setSelection API docs

// Implement and register module
Quill.register('modules/quicktext', function(quill, options) {
  
  let cache = '';
 
  quill.on('text-change', (delta, oldDelta, source) => {
    if (source === 'api') {
      console.log("changing", source) 
     return
    }
    let lastkey = delta.ops[delta.ops.length - 1]?.insert || '';
    if (delta.ops[delta.ops.length - 1]?.delete) { // handle delete key
      cache = cache.slice(0,-1);
      return
    }
    if (lastkey && lastkey !== " ") {
      cache += lastkey;
      console.log("cache", cache, "lastkey",lastkey)
    } else if (cache) { // avoid initial call
      console.log("cache", cache, "lastkey",lastkey)
      reps.forEach(rep => {
        console.log("rep check", cache, rep[cache])
        if (rep[cache]) {
          console.log("triggered")
          let caret = quill.getSelection().index
          let start = caret - cache.length - 1;
          console.log("doing", caret + (rep[cache].length - cache.length))
          quill.deleteText(start, cache.length, 'silent');
          quill.insertText(start, rep[cache], 'silent');
          console.log(`caret at ${caret}, moving forward ${rep[cache].length - cache.length} spaces, to position ${caret+rep[cache].length - cache.length}.`)
          quill.setSelection(caret + (rep[cache].length - cache.length),0, 'silent');
          // why does above not work?
          console.log("done")
        }
      })
      cache = '';
    }
  });
});

let reps = [
  {".hi": "hello"},
  {".bye": "goodbye"},
  {".brb": "be right back"}
];

// We can now initialize Quill with something like this:
var quill = new Quill('#editor', {
  modules: {
    quicktext: {
      reps: reps 
    }
  }
});

Code can be run here: Codepen

Rendering a new input filed for a specific task in ReactJs

I am tryin’ to build the Ecommerece admin dashboard by myself, and I am facing some challenges.
I want to add a product into the products table, but this product is having variants (for e.g. a cloths product has size and color variants). so The only way to add a variant is by adding a product menu itself.

I have a variant name input field that describes the name for the specific variant (for e.g. the color) and I have a variant type input field that describes the type of color (for e.g. red, green, yellow..etc).
I want to render the input field from the user perspective in order to maintain the perfect user experience.

so to add a variant I will have to add its name in this field:

variant name

then after writing the variant name, another input field will pop up which is the description for that variant name (one variant may have more than one type)

variant type

the problem is how to do this process of adding types for the user, in other words, how to render the input fields depending on the need of the user for variant names.

and after the user clicked the SAVE button, I want to extract the variants in a javascript object like this:

"variants": [
{
"id": "1",
"type": "color",
"name": "اللون",
"variants": [
{
"id": "11",
"name": "white",
"label": "#FFFFFFFF"
},
{
"id": "12",
"name": "black",
"label": "0xFF000000"
},
{
"id": "13",
"name": "red",
"label": "FFCC0000"
},
{
"id": "14",
"name": "blue",
"label": "2986cc"
}
]
},

I wrote this code this far.

import { Field, Form, Formik } from 'formik';
import React, { useEffect, useState } from 'react';

const VariantsTable = () => {
 

  const variantsVals = {};
  return (
    <>
      <Formik
        initialValues={{
          variantName: '',
        }}
      >
        {({ values }) => (
          <div>
            <Form>
              <div className="mb-4  content-center">
                <h5>Product details</h5>
                <Field
                  className="shadow appearance-none border rounded w-full py-2 px-3 mt-4 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                  name="variantName"
                  type="text"
                  placeholder={'Variant Name'}
                />
                {values.variantName && (
                  <Field
                    className="shadow appearance-none border rounded w-full py-2 px-3 mt-4 mr-8 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    name="variantType"
                    type="text"
                    placeholder={'Variant type'}
                  />
                )}
                {values.variantType && (
                  <Field
                    className="shadow appearance-none border rounded w-full py-2 px-3 mt-4 mr-8 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    name="variantType"
                    type="text"
                    placeholder={'variant type'}
                  />
                )}
              </div>
              <button
                className="bg-buttonsColor hover:bg-maincolor text-black font-bold py-2 px-4 rounded focus:outline-none  focus:shadow-outline"
                type="submit"
                onClick={() => {
                  variantsVals['variantName'] = values.variantName;
                  variantsVals['variantType'] = values.variantType;
                  variantsVals['id'] = 1;

                  console.log(values);
                }}
              >
                save
              </button>
            </Form>
          </div>
        )}
      </Formik>

export default VariantsTable;

I hope I find some helpful answers because I am really stuck at this point.
Thanks in advance.

Publish a site created with Gatsby using FileZilla

I have a website created with Gatsby and the hosting is Tophost. Is it possible to publish the site via FileZilla?
I have already tried but all javascript file transfers fail on FileZilla.Is this a solvable problem or is it not possible to use FileZilla to publish sites created with Gatsby?

Prevent jump to top on anchor click

I’m trying to prevent the page jump when clicking on a link.

function anchorClick() {
    e.preventDefault();
    id = window.location.hash.substring(1);
    $('.map_tabs').attr("style", "display:none");
    
    if ( $('.map_tabs#' + id).length ) {
        $('.map_tabs#' + id).attr("style", "display:block");
    } else {
        $('.page-link#contact-us').attr("style", "display:block")
        $('.page-link#contact-us h2').text(id + ' Coming Soon');
    }
}   

$(document).ready(anchorClick);
$(document).on("click", "#mybase" , anchorClick);   

I’ve tried adding e.preventDefault() but it’s not stopping the page jump.