#StackBounty: #javascript #html #dom Reorder columns in an HTML form

Bounty: 100

I have the following HTML structure for a form (simplified):

<form class="form">
  
First
Last
Whatever
</div>
City
</div>
Country
Phone
</div> </form>

As I don’t have any control over the output, I need to reorder the columns by using JavaScript:

const form = (() => {
  const colClassName = 'formCol';
  const rowClassName = 'formRow';
  const clearClassName = 'clear';

  function createRow(elForm) {
    const elRow = document.createElement('div');
    const elClear = document.createElement('div');
    elRow.className = rowClassName;
    elClear.className = clearClassName;
    elRow.appendChild(elClear);
    elForm.insertAdjacentElement('beforeEnd', elRow);

    return elRow;
  }

  function moveColumn(elForm, elRow, colName) {
    const elCol = elForm.querySelector(`.${colClassName}[data-id='${colName}']`);
    elRow.insertAdjacentElement('afterbegin', elCol);
  }

  function removeEl(el) {
    el.parentNode.removeChild(el);
  }

  function reorder(elForm, order) {
    const elRows = elForm.querySelectorAll(`.${rowClassName}`);
    const maxRows = Math.max(elRows.length, order.length);
    let elCol;

    for (var i = 0; i < maxRows; i++) {
      if (order[i]) {
        if (!elRows[i]) {
          elRows[i] = createRow(elForm);
        }

        if (!Array.isArray(order[i])) {
          moveColumn(elForm, elRows[i], order[i]);
        } else {
          for (j = order[i].length - 1; j >= 0; j--) {
            moveColumn(elForm, elRows[i], order[i][j]);
          };
        }
      } else {
        elCol = elRows[i].querySelector(`.${colClassName}`);

        if (!elCol) {
          removeEl(elRows[i]);
        }
      }
    }
  }

  return {
    reorder,
    // other functions for form
  };
})();

form.reorder(document.querySelector('.form'), [
  ['Last', 'City'],
  'First',
  'Country',
  'Phone',
]);

It does the following:

  • Reorders the elements as specified in the array (multiple columns).
  • Does not delete columns if they are not in the array (see column “Whatever”).
  • Creates new rows if necessary and deletes empty rows

While that works as is (see https://jsfiddle.net/6cy4mjvd/), I don’t know if there are ways to improve readability / code in general, e.g. it feels wrong how I currently create new rows and modify elRows and also that I pass elForm to all helper functions… and probably a few other spots.

Btw. I plan on adding other functions other than reorder to modify the form. That’s why I return an object (line // other functions for form) in the function.


Get this bounty!!!

#StackBounty: #javascript #reactjs #react-native #redux #react-redux Paginate date-specific results from an API with React and Redux

Bounty: 150

I want to show some news in my React app using Redux.

The problem is that I want to show the news for individual dates and I want to paginate the news.

In my API I print

{
  pagination: {
    count: 1000,
    size: 10,
    page: 1,
    pages: 100
  },
  news: [
    ..
  ]
}

I know how to make a simple pagination, but I don’t know how the API should work if I want to be able to show news for different dates in my app.

Until now (without dates), I have just kept a state news and pagination in my Redux reducer, and then checked if the page number equals the total number of pages to determine whether it should try loading more news.

But now that I potentially have many different dates and I want to keep all the news in the Redux store, I don’t know how to structure it.

I can keep my API as it is, since filtering with GET parameter ?date=15-09-2017 will just decrease the number of news in the API result.

But would it still be possible to just keep all the news in an array in a news variable in my reducer or do I have to structure it to be something like

news: {
  '15-09-2017': {
    news: [...],
    pagination: {}
  },
  ...
}

in order to keep track of the pagination for every single date?


Get this bounty!!!

#StackBounty: #javascript #pdf #jspdf jsPDF justify text

Bounty: 50

I’m trying to apply some changes on jsPDF library to be able to justify text.

I’m having trouble to find the right value for Tw (word spacing).

In jspdf.js (L:1413) I have added this code:

if (align) {
    ...                
    else if (align === 'justify') {
       left = x;
    }
    else {
        throw new Error('Unrecognized alignment option, use "center" or "right".');
    }
    prevX = x;
    text = '(' + da[0];

    var pdfPageWidth = this.internal.pageSize.width;
    var wordSpacing;
    if( align === 'justify' ) {
        var fontSize = this.internal.getFontSize();
        var nWords = da[0].trim().split(/s+/).length;
        var textWidth = this.getStringUnitWidth(da[0].replace(/s+/g, '')) * fontSize / this.internal.scaleFactor;
        var spaceWidth = this.getStringUnitWidth(' ') * fontSize / this.internal.scaleFactor;
        wordSpacing = (Math.max(0, (pdfPageWidth - textWidth) / Math.max(1, nWords - 1)) / spaceWidth);
        wordSpacing += ' Twn';
        text = wordSpacing + text;
    }
    ...
}

The idea was to extract the space width by doing (pageWidth – textWidth) / numberOfWords -1. I can’t get the correct word space.

Is there an encoding problem?

Thanks for your help.


Get this bounty!!!

#StackBounty: #javascript #jquery Trigger event upon jQuery being loaded

Bounty: 50

I’m merging the use of the YouTube iFrame API and jQuery loaded in through a script tag that has the defer flag set. The defer flag must be set as the client has a perfect Google page insight score and wishes to maintain that score.

The YouTube API, upon being fully loaded and ready for use, immediatley calls a function that I define onYouTubeIframeAPIReady. It will then later call onPlayerReady upon the player being fully loaded and rendered.

I wish to use jQuery in this function, but just using jQuery inside the onPlayerReady function will be creating a race condition (hoping the jQuery library has finished loading by the time onPlayerReady gets called).

It occured to me a workable solution would be to use the onPlayerReady function to set a variable before calling a function that tests for both the player and jQuery. Another function sets a variable upon jQuery being ready and calls the same test function.

I have some code that works, but the part that checks for jQuery seems messy to me, and also introduces a small amount of extra unneccessary delay. I was wondering if anyone knows of a better way to run something the instant jQuery becomes available. Basically, are there callbacks for jQuery becoming available built into the library itself?

My current code is as follows:

var ready = {
    'jquery': false,
    'youtube' false
},
testJQueryLoaded;

testJQueryLoaded = function() {
    if(typeof jQuery == 'undefined') {
        window.setTimeout(function() {
            testJQueryLoaded();
        }, 25);
        return;
    }

    ready.jquery = true;
    postLibraryLoad();
};

testJQueryLoaded();

function onYouTubeIframeAPIReady() {
    // Stuff
};

function onPlayerReady() {
    ready.youtube = true;
    postLibraryLoad();
};

function postLibraryLoad() {
    if(!ready.jquery || !ready.youtube) {
        return;
    }

    // More stuff
};


Get this bounty!!!

#StackBounty: #javascript #google-api #gapi How to upload files to Google drive using gapi and resumable uploads?

Bounty: 50

I’m trying to follow this guide for doing resumable uploads on Google Drive through Google Api’s.

This is my code, you can see it makes 2 requests as the guide asks to, the first part creates the metadata, and then we use the location for starting uploading the files with the session created by the first request.

        const file = new File(['Hello, world!'], 'hello world.txt', { type: 'text/plain;charset=utf-8' });
        const contentType = file.type || 'application/octet-stream';

        const reqMetadata = gapi.client.request({
            'path': 'upload/drive/v3/files',
            'method': 'POST',
            'params': { 'uploadType': 'resumable' },
            'headers': {
                'X-Upload-Content-Type': file.type,
                'X-Upload-Content-Length': file.size,
                'Content-Type': 'application/json; charset=UTF-8'
            },
            'body': {
                'name': file.name,
                'mimeType': contentType,
                'Content-Type': contentType,
                'Content-Length': file.size
            }
        });

        reqMetadata.execute((respMetadata, rawRespMetadata: any) => {
            const locationUrl = JSON.parse(rawRespMetadata).gapiRequest.data.headers.location;

            const reader = new FileReader();

            reader.onload = (e) => {
                const reqFile = gapi.client.request({
                    'path': locationUrl,
                    'method': 'PUT',
                    'headers': {
                        'Content-Type': file.type,
                        'Content-Length': file.size
                    },
                    'body': reader.result
                });

                reqFile.execute(respFile => {
                    console.log(respFile);
                });
            };

            reader.readAsArrayBuffer(file);
        });

What’s the problem?

Well, seems that the Google Api library does not like the File / byte array as body on their gapi.client.request and they’re truncating it away see image

What’s the correct way to pass the file? I tried both body: file and body: reader.result but same result

PS: gapi is already fully authenticated & initialized with auth2, I’m able to create files / directory.


Get this bounty!!!

#StackBounty: #javascript #reactjs #animation #svg #react-native Animating react-native-svg dash length of a <Circle />

Bounty: 200

Hey everyone I’m trying to achieve effect similar to: https://kimmobrunfeldt.github.io/progressbar.js
(circle one)

I was able to successfully animate some svg elements before using setNativeProps approach, but it is failing for me this time with dash length, below is a gif demonstrating current behaviour (circle is change from full to semi full when it receives new props):

enter image description here

Essentially I am trying to animate this change instead of it just flicking in, below is full source for this rectangular progress bar, basic idea is that is uses Circle and strokeDasharray in order to show circular progress, it receives currentExp and nextExp as values for characters experience in order to calculate percentage left before they reach next lvl.

Component uses pretty standard set of elements, besides few dimension / animation and colour props from stylesheed and styled-components library for styling.

NOTE: project is importing this library from expo.io but it’s essentially react-native-svg

import React, { Component } from "react";
import PropTypes from "prop-types";
import styled from "styled-components/native";
import { Animated } from "react-native";
import { Svg } from "expo";
import { colour, dimension, animation } from "../Styles";

const { Circle, Defs, LinearGradient, Stop } = Svg;

const SSvg = styled(Svg)`
  transform: rotate(90deg);
  margin-left: ${dimension.ExperienceCircleMarginLeft};
  margin-top: ${dimension.ExperienceCircleMarginTop};
`;

class ExperienceCircle extends Component {
  // -- prop validation ----------------------------------------------------- //
  static propTypes = {
    nextExp: PropTypes.number.isRequired,
    currentExp: PropTypes.number.isRequired
  };

  // -- state --------------------------------------------------------------- //
  state = {
    percentage: new Animated.Value(0)
  };

  // -- methods ------------------------------------------------------------- //
  componentDidMount() {
    this.state.percentage.addListener(percentage => {
      const circumference = dimension.ExperienceCircleRadius * 2 * Math.PI;
      const dashLength = percentage.value * circumference;
      this.circle.setNativeProps({
        strokeDasharray: [dashLength, circumference]
      });
    });
    this._onAnimateExp(this.props.nextExp, this.props.currentExp);
  }

  componentWillReceiveProps({ nextExp, currentExp }) {
    this._onAnimateExp(currentExp, nextExp);
  }

  _onAnimateExp = (currentExp, nextExp) => {
    const percentage = currentExp / nextExp;
    Animated.timing(this.state.percentage, {
      toValue: percentage,
      duration: animation.duration.long,
      easing: animation.easeOut
    }).start();
  };

  // -- render -------------------------------------------------------------- //
  render() {
    const { ...props } = this.props;
    // const circumference = dimension.ExperienceCircleRadius * 2 * Math.PI;
    // const dashLength = this.state.percentage * circumference;
    return (
      <SSvg
        width={dimension.ExperienceCircleWidthHeight}
        height={dimension.ExperienceCircleWidthHeight}
        {...props}
      >
        <Defs>
          <LinearGradient
            id="ExperienceCircle-gradient"
            x1="0"
            y1="0"
            x2="0"
            y2={dimension.ExperienceCircleWidthHeight * 2}
          >
            <Stop
              offset="0"
              stopColor={`rgb(${colour.lightGreen})`}
              stopOpacity="1"
            />
            <Stop
              offset="0.5"
              stopColor={`rgb(${colour.green})`}
              stopOpacity="1"
            />
          </LinearGradient>
        </Defs>
        <Circle
          ref={x => (this.circle = x)}
          cx={dimension.ExperienceCircleWidthHeight / 2}
          cy={dimension.ExperienceCircleWidthHeight / 2}
          r={dimension.ExperienceCircleRadius}
          stroke="url(#ExperienceCircle-gradient)"
          strokeWidth={dimension.ExperienceCircleThickness}
          fill="transparent"
          strokeDasharray={[0, 0]}
          strokeLinecap="round"
        />
      </SSvg>
    );
  }
}

export default ExperienceCircle;

UPDATE: Extended discussion and more examples (similar approach working for different elements) available via issue posted to react-native-svg repo: https://github.com/react-native-community/react-native-svg/issues/451


Get this bounty!!!

#StackBounty: #javascript #java #android #firebase #firebase-cloud-messaging Firebase Cloud HTTP Message from Web

Bounty: 50

I have set up a webpage (home.html) that a user can sign into firebase using authentication. Once they authenticate, they are directed to a new page(test.html). Once they are here, I want to be able to send a notification or data message.

I am wondering if anyone can help me with the code to send a notification – any type of notification. I’ve been on this for 3 days and cannot send a notification from the web!! I can’t find any tutorials on this – only people using curls.

I have no idea how to handle the code below, which is supposed to be on how to send a notification to the devices subscribed to a topic. I am guessing that this is all JSON and needs to be put into a JSON object?

Please assume the Initialization is filled in, I removed all info – even though I think that information is supposed to be public.

enter image description here

Thanks for any info!

This is my service worker (so far): firebase-messaging.sw.js

  // Give the service worker access to Firebase Messaging.
  // Note that you can only use Firebase Messaging here, other Firebase libraries
  // are not available in the service worker.
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');  

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();
  messaging.setBackgroundMessageHandler(function(payload){
    const title = "Hello World";
    const options = {
      body: payload.data.status
    };
    return self.registration.showNotification(title, options);
  });

This is the app.js file that goes to the test.html page

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  // Retrieve Firebase Messaging object.
  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function() {
    console.log('Notification permission granted.');
    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
  })
  .catch(function(err) {
    console.log('Unable to get permission to notify.', err);
  })

  messaging.onMessage(function(payload){
    console.log('onMessage:', payload);
  });

And the barebones test.html file

<!DOCTYPE html>

<html>
    <head>
        https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js
        https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js
    </head>
    <body> 
        /scripts/app.js
    </body>
</html>


Get this bounty!!!

#StackBounty: #javascript #amazon-web-services #authentication #amazon-cognito Using AWS Cognito can I resolve the authenticated Identi…

Bounty: 250

I have a JavaScript web application that supports Cognito unauthenticated identities. I’m trying to figure out how to identify the linked authenticated IdentityId for a DISABLED unauthenticated IdentityId.

First unauthenticated users are issued an IdentityId via AWS.config.credentials.get. Internally CognitoIdentityCredentials is using getId to generate a new unauthenticated IdentityId.

let unathenticatedIdentityId;

const AWS = require('aws-sdk');
AWS.config.region = region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId
});
AWS.config.credentials.get(err => {
    unathenticatedIdentityId = AWS.config.credentials.identityId;
});

Then our user authenticates to a Cognito User Pool via amazon-cognito-identity-js and the unauthenticated IdentityId changes to the authenticated IdentityId associated with their Cognito Login. The unauthenticated IdentityId is automatically marked DISABLED and is linked internally to the authenticated IdentityId.

let authenticatedIdentityId;

const { CognitoUserPool, CognitoUser, AuthenticationDetails } = require('amazon-cognito-identity-js');
const Pool = new CognitoUserPool({
    UserPoolId,
    ClientId,
});
const authDetails = new AuthenticationDetails({
    Username,
    Password,
});
const user = new CognitoUser({
    Pool,
    Username,
});
user.authenticateUser(authDetails, {
    onSuccess: (session) => {
        AWS.config.credentials.params.Logins = {
            [PoolProviderName]: session.idToken.jwtToken,
        };
        AWS.config.credentials.expired = true;

        AWS.config.credentials.refresh(err => {
            authenticatedIdentityId = AWS.config.credentials.identityId;
        });
    },
});

I have the value for unathenticatedIdentityId and authenticatedIdentityId but I do not see a way in the AWS Cognito API’s to resolve that the DISABLED unauthenticatedIdentityId has been linked to the authenticatedIdentityId. Conversely I do not see a way to identify what IdentityIds have been linked to the authenticatedIdentityId. The describeIdentity API will tell me that unauthenticatedIdentityId is DISABLED and that it has no Logins, but it does not point to the linked authenticatedIdentityId.

How can I, with only the value of the linked/DISABLED unauthenticatedIdentityId, resolve the value authenticatedIdentityId?


Get this bounty!!!

#StackBounty: #javascript #listview #nativescript NativeScript – array in listview

Bounty: 50

I’m new to NS and i’m trying to display a list of passengers inside a list of rides ( each ride has many passengers).

So i tried to put a listview (passengers) inside a global listview ( rides ), the listview for the rides work but not for the passenger (obviously), i don’t think it’s the right way to do it.

here is my code:

rides.xml :

    <ListView items="{{ ridesList }}" id="ridesList">
  <ListView.itemTemplate>
    <!-- Rides -->
    <StackLayout class="box" orientation="vertical">
      <GridLayout class="boxHeader" rows="auto" columns="*">
        <Label class="title" verticalAlignment="center" horizontalAlignment="left" text="{{reference}}" />
      </GridLayout>
      <StackLayout class="boxContent" orientation="vertical">
        <GridLayout class="checkpoints" rows="auto, auto" columns="80, *, 60">
          <!-- -->
          <ListView items="{{ passagers }}" id="passagersList">
            <ListView.itemTemplate>
                <StackLayout class="timedate" orientation="vertical" row="0" col="0">
                  <Label class="time" text="14:32" />
                  <Label class="firstname" text="{{firstname}}" />
                </StackLayout>
                [...]
              </ListView.itemTemplate>
            </ListView>
        </GridLayout>
      </StackLayout>
    </StackLayout>
    <!-- /Rides -->
  </ListView.itemTemplate>
</ListView>

rides.js

    var ride = new RideViewModel([]);
[...]
exports.loaded = function(args) {
    var page = args.object;
        page.bindingContext = ride;

            ride.futurCourse().then(function(data) {
                                [...]

                                ride.fillFuturCourse(data);
            });
};

ride-view-model.js

viewModel.fillFuturCourse = function(data){

  var testdModel = new ObservableArray();
  var jsone = JSON.parse('{"course":[{"id":"5","reference":"test","passagers":[{"firstname":"julien"},{"firstname":"andre"}]},{"id":"6","reference":"RF7878788"}]}');
  testdModel= jsone.course;
  viewModel.set("ridesList",testdModel);
};

Thanks !


Get this bounty!!!

#StackBounty: #javascript #reactjs #redux #mocha #chai React Mocha-chai test not recognizing store from prop

Bounty: 50

I have a Mocha-chai test on a Redux connected React component. In order to pass the Redux store to the test component, I create it in the test file and pass it as a prop, but the test throws the following error:

Invariant Violation: Could not find “store” in either the context or
props of “Connect(Project)”. Either wrap the root component in a
<Provider>, or explicitly pass “store” as a prop to
“Connect(Project)”.

Here is the test:

import React from 'react';
import ReactDOM from 'react-dom';
import { 
  renderIntoDocument,
  scryRenderedComponentsWithType
} from 'react-dom/test-utils';
import Project from '../../src/components/Project';
import { expect } from 'chai';
import { createStore } from 'redux';
import reducer from '../../src/reducers/reducers';

const store = createStore(reducer);

const component = renderIntoDocument(
  <Project 
    store={ store } 
    project={
      {
        "name": "MyName",
        "img": "path.jpg",
        "img_alt": "alt desc",
        "description": "lorem ipsum",
        "github": "repository",
        "link": "website.com"
      }
    } />
);

describe('Project', () => {

  // tests ...

});

This is the React component:

import React from 'react';
import ProjectImage from './ProjectImage';
import ProjectText from './ProjectText';
import { connect } from 'react-redux';
import * as actions from '../actions/actions';

export const Project = React.createClass({

  getProject: function() {
    return this.props.project || {};
  },

  handleClick: function(event) {
    this.props.dispatch(actions.showModal(true));
    this.props.dispatch(
      actions.setModalContent(this.getProject())
    );
  },

  render: function() {
    return (
      
); } }); export default connect()(Project);


Get this bounty!!!