2021年9月3日 星期五

[frontend, main] The React, Angular, WebAPI, Chart FAQ

The React, Angular, WebAPI, Chart FAQ

井民全, Jing, mqjing@gmail.com


The Public FAQ Index (view)

Table of contents


1. React 3

1.1. Setup 3

1.2. Debug 5

1.3. Component 7

1.3.1. OLD/BAD Practice 9

1.4. TSX/JSX 11

1.5. Test 14

1.6. UI 14

1.6.1. Layout 14

1.6.2. CSS Style 15

1.6.3. Canvas 16

1.6.4. Heading 16

1.6.5. Input 17

1.6.6. Slides 17

1.6.7. Button 17

1.6.8. Switch 19

1.6.9. Progress 19

1.6.10. Table 19

1.6.11. Form 20

1.6.12. Dialog 21

1.6.13. Calendar 21

1.6.14. Menu 21

1.6.15. Tree View 22

1.7. Server-related 24

1.8. CRUD 24

1.9. Redux 25

1.10. Auth: for User Signup & User Login 27

2. Angular 27

2.1. Common 27

2.2. App 27

2.3. Component 28

2.4. CRUD 29

2.5. Debug 29

3. HTML5 30

3.1. List item 31

3.2. File 32

3.3. Button 33

3.4. Request 36

4. CSS 37

5. UI Framework 38

6. Authortication 39

6.1. Common 39

7. WebAPI 40

7.1. Console 40

7.2. Keyboard 41

7.3. Touch 41

7.4. Timer 41

7.5. WebBluetooth 42

7.6. WebAudio 43

7.7. WebRTC 46

7.8. WebAssembly 47

7.9. WebSerial 47

8. Animation libraries 47

8.1. Spring 47

8.2. Famer 48

9. Graphic libraries 48

9.1. Survey 48

9.2. 3D libraries 48

9.3. Image libraries 48

9.4. Map, CesiumJS 48

10. Chart libraries 49

10.1. comm 49

10.2. High performance chart libraries 49

10.2.1. Dygraphs 49

10.2.2. TimeChart 50

10.2.3. uPlot 51

10.2.4. Webgl-plot 51

10.2.5. [canvas] d3 52

10.2.6. [canvas] Wavesurfer 52

10.2.7. Livechart 52

10.2.8. Chart.js 53

10.2.8.1. Javascript (chart.js only) 53

10.2.8.2. Typescript + React 53

10.2.8.3. react-chartjs-2 54

10.2.8.4. chartjs-plug-stream 54

10.2.9. Recharts 57

10.2.10. Others 57



1. React

  1. [react, example] React.js Examples (ref)

1.1. Setup

  1. [react, sheet] The React sheet (sheet)

  1. [react, official] React (ref), State (ref)

  2. [react, official, tutorial] React (ref

  3. [react, doc, api] api doc (ref)

  4. [react, official, example] The official live example (ref)

  5. [react, install] How to install react via npm (ref)l


npm init

npm install --save react

npm install --save react-dom


  1. [react, port] How to setup the default port for React app (ref)


# package.json (Ubuntu)

"scripts": {

    "start": "PORT=8000 react-scripts start",

    "build": "react-scripts build",

    "test": "react-scripts test",

    "eject": "react-scripts eject"

  },


  1. [react, app, typescript] Create typescript react app (ref) (blog)


npx create-react-app my-app --template typescript

cd my-app

npm start


  1. [react, app, javascript] Create react app (ref)


npx create-react-app my-app

  1. [react, app, build] release build


yarn build

serve -s build

  1. [react, app, env] How to pass parameters to the react app (view) (ref)


package.json

"scripts": {

     "start:test": "REACT_APP_MY_SWITCH=TRUE react-scripts start",

     "start": "react-scripts start",

     ...

 }


App.tsx

const { REACT_APP_MY_SWITCH } = process.env



yarn test

Output

REACT_APP_MY_SWITCH = undefined


  1. [yarn, script, makeclean, cross-platform] A npm script for clean


Install

yarn global add rimraf // yarn add rimraf -D


clean

"clean": "rimraf out build dist node_modules & rimraf **/*.js & rimraf **/*.map & rimraf **/*.raw & rimraf **/*.log",


  1. [react, makeclean] How to clean the React App


// package.json

"clean": "rm -fr node_modules"




1.2. Debug

  1. [react, debug, basic] How to add a break point in code


xxx{){

     ...

     debugger;

     ...

}


  1. [react, debug, tool] Debug tool for firefox (ref)

  2. [react, debug, tool] Debug tool for Chrome (ref)


Step 1: Chrome web store -> React Developer Tools

Step 2: Mouse right click to bring up the inspect tool


Step 3: Check the componset tree in [⚛️ Components] tabs

  1. [react, debug, vscode] How to config the chrome debugger in vscode (ref)


Step 1: Create a launch.json file that chooses chrome

Step 2: Change the port 


{

     "version": "0.2.0",

    "configurations": [

        {

            "type": "chrome",

            "request": "launch",

            "name": "Launch Chrome against localhost",

            "url": "http://localhost:3000",

            "webRoot": "${workspaceFolder}"

        }

    ]

}



Step 3: Build & Run service

yarn start


Step 4: Click Run from vscode 

 



1.3. Component

  1. [react, function component] 更新元件狀態不使用 Ref 的範例 Create a function component update state without Ref (github) (modify to setState(state => ({...state, id: 123}));)

  2. [react, function component] 更新狀態是直接呼叫 function 給參數, 回傳 JSX 顯示畫面

    1. 元件狀態模板: const [state, setState] = useState({ id: 0 });

    2. 更新狀態模板: setState(... );  // 會啟動連鎖變更繪圖  (ref)


// function component

setState(state => ({...state, id: 123}));


// bad

setState({...state, id: 123});   // this is the class component update form


  1. Render 元件設定 props 模板: <MyFunComp id={state.id}>

  2. 元件模板


function MyFunComp(props:{id:number}): JSX.Element {

     if(pros.id == 0){

         return (<div> GOT 0</div>);

     }


    return(<div> Others</div>);

}


export default MyFunComp;


  1. [react, function component, create] How to create a React Component using function***(view)

    1. 一個簡單的好例子 (ref)

    2. 不要在 function component 裡面用 ref (ref2)

    3. 不要過度使用 ref 改變 component 狀態, 而使用 props 和 setState 產生連鎖反應改變元件狀態

  2. [react, function component, instance variable] How to use non-state variables in functional components (ref1), (ref2)


const bcheckedRef:any = useRef<boolean>(); // 宣告

bcheckedRef.current = true; // write

console.log(bcheckedRef.current); // read

  1. [react, function component, effect] How to run only once (ref)


useEffect( () => {

    RunOnlyOnce();

  }, []);


  1. [react, function componen, hook, useCallback] 如何使用 useCallback 更新 React function component 的狀態 (view) (blog), 被動的  update. useEffect 是在 render 後, 被呼叫.. 而 setState 則是主動更新. 

  2. [react, class component, prop, pass data] How to pass data between Components via props (view) (ref)

  3. [react, class component, prop, pass function] How to pass props to the Class Component (view)

  1. [react, class component, state] How to use this.state in Class component (view)


type MyState = { date: Date }; // define the state data type

class App extends React.Component<{}, MyState> {

    ...

}

  1. [react, class component, state] How to update the component state from javascript to the html render via setStatus (view) (ref) (ref2)


When you call setState in a component, React automatically updates the child components inside of it too. (ref)


Key:

// 1. 宣告 State 成員

//      this.state = {變數 1: 資料1 或陣列, 

//                            變數 2: 資料 2,

//                           };

//                            


// 2.  Update 資料:

//    this.setState({

//                             變數 1: 新資料 1,

//                             變數 2: 新資料 2,

                               });


Detail

import React from 'react';

class A extends Reacts.Component {

    constructor(props) {

        super(props);

        this.state = {Count : 0};  // Initial component state


        this.onClicked = this.onClicked.bind(this);

    }


    onClicked () {

        let local_count = this.state.Count + 1;

        this.setState({Count: local_count});   // Update the state

  }


   render() {

      return (

          <div className="A">

                abc = <span> {this.state.Count} </span>

                <button onClick={this.onMyClick}> Click</button>

          </div>

    );

  }

}



1.3.1. OLD/BAD Pratice

  1. [component, lifecycle] The react component lifecycle (ref)


// Class component (full text)

export class xxxView extends React.Component {

   constructor(props)

   componentDidMount()

   componentWillUnmount()

   render()

}


// Functional component

export const xxxView = () => {

    const xxxDomRef = useRef();    // create connect

    

    useEffect(

        () => {

            // access xxxDomRef.current

            return () => { subscription.unsubscribe(); };

        }, [props.source]);


    return <div ref={xxxDomRef} />;

}


  1. [react, class component, create] How to create a React component using class**** (view), (github)

  2. [react, class component, access] How to access the React component 

    1. 盡量少用 Ref, 應該使用 props 搭配 setState 產生連鎖變更狀


  1. Ref (ref)

  2. querySelector (ref)

    1. let canvas = document.querySelector('canvas');


  1. [react, class component, image] How to switch the image when user clicked the button (view), (blog), 

    1. 使用 Ref 來更新元件是不恰當的

  2. [react, class component, image] How to add static asset to the React component (view), (blog)

    1. 盡量少用 class component, function component 非常優雅

  3. [react, class component, state] How to use map to handle multiple state change in React component (view)

    1. 盡量少用其他奇奇怪怪的資料型態, 應該直接使用 type object 來宣告元件的 state

  4. [react, componentDidMount]

    1. 在 function component 中, 對應的功能是 effect

  5. [react, ref, callback] How to use callback format to the Ref (ref)

    1.  盡量少用 Ref

1.4. TSX/JSX

  1. [tsx, vscode] Show Error when opening TSX file: Cannot use JSX unless '--jsx' flag is provided ? (ref)


Step 1: Open tsconfig.json

Step 2: Setup jsx: flag 

   From "jsx": "react-jsx" to "jsx": "react" 


  1. [tsx, html] JSX vs. HTML (ref


// HTML (ref): Almost elements require opening and closing tags

<a href="https://www.w3schools.com">Visit W3Schools.com!</a>


// JSX: any element can be writed as self-closing tag

const element = <a href={user.avatarUrl} />;


  • JSX: JSX is JavaScript XML, an extension of JavaScript that allows writing HTML in React.

  • HTML:  a standard markup language for documents designed for the web browser


  1. [react, render] How react renders a string from jsx (ref)


// Step 1: 自定義 react function component[1]

function Welcome(props) {

// 注意: 不是回傳字串. 而是 jsx element

// 這東西會被編譯成 React.createElement 形式[2]

  return <h1>Hello, {props.name}</h1>;  

}


// Step 2: 呼叫 Welcome component 把  attribute 與 child 封裝成 props, props.name = "Sara" 當作參數丟進去. 

// 回傳: 已經代換好的 element =>  <h1> Hello Sara </h1>  

const element = <Welcome name="Sara" />;


// Step 3: react DOM update the DOM

ReactDOM.render(

  element,

  document.getElementById('root')

);



References

  1. Components and Props, https://reactjs.org/docs/components-and-props.html

  2. JSX in Depth, https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized



  1. [jsx]  jsx compile (javascript) (view)


<component props=...>

         children

</component>


=>

React.createElement(component, props, ...children)


  1. [jsx, brace] What's the differente betwee double brace and single brace for inline styles


Ex: 

function(text, index) {

    return (

        <div style={{textDescription: 'hello'}} className="todo"> {text} </div>;

    );

}


  •  {text} : In JSX {variable}, the braces are used to reference the JS variable or expression.

  • {{textDescription: 'hello'}} : the outer braces denotes a js expression and the inner braces are for creating a object.

  1. [tsx, create] How to return a JSX.Element?


class App ... {


private __arrayTag:any = [];


constructor(){

    this.addTag();

}


addTag(){

    this.__arrayTag.push(<p> item </p>) 

}


render() {

    return (

      <div>

      <p>Hello World</p>

      {this.__arrayTag}

      </div>

    );

  }


}

  1. [tsx, show, array] How to show array data (ref)


import React from "react";

import axios from "axios";


export default class App extends React.Component {

  state = {

    users: [],

  };

  componentDidMount() {

    axios.get("/users.json").then((response) => {

      this.setState({ users: response.data });

    });

  }


  render() {

    const { users } = this.state;

    return (

      <div>

        <ul className="users">

          {users.map((user) => (

            <li className="user">

              <p>

                <strong>Name:</strong> {user.name}

              </p>

            </li>

          ))}

        </ul>

      </div>

    );

  }

}


1.5. Test

  1. [test, survey] 15 Best Chrome Extensions for Software Testers in 2021 (ref)

  2. [react, test, official] The React Test Overview (ref)

1.6. UI

  1. [react, ui, doc] React components for efficiently rendering large lists and tabular data -- react-virtualized

  2. [react, ui, survey] 20+ Best React UI Component Libraries / Frameworks (ref 1) (ref 2)

  3. [react, semantic] Semantic-UI-React (github)

  4. [react, bootstrap] Frontend framework, Bootstrap (ref)

  5. [react, ui, material] Material Kit React (github), (doc), (ref)

  6. [ract, ui, material] Color (ref)

1.6.1. Layout

  1. [react, material-ui, layout, grid] How to use grid layout (ref)

  2. [react, material-ui, layout, grid] How to get the width of cell (ref)

1.6.2. CSS Style

  1. [css, tailwindcss] Rapidly build modern websites without ever leaving your HTML (ref)

  2. [react, render, css, inline] How to setup the style in jsx (ref)


class App extends Component {

 graphStyle = {

    width: '1500px',

    height: '300px',

  };


 // ...


  render() {

        return (

        <div>

          <div id="graph" style={this.graphStyle}></div>

        </div>

      );

  }

}


  1. [react, css, file] How to use css in file (ref)


// File: xxx.tsx

import React from 'react';

import './DottedBox.css';


const DottedBox = () => (

  <div className="DottedBox">

    <p className="DottedBox_content">Get started with CSS styling</p>

  </div>

);


export default DottedBox;


/* File: DottedBox.css */

.DottedBox {

  margin: 40px;

  border: 5px dotted pink;

}


.DottedBox_content {

  font-size: 15px;

  text-align: center;

}



1.6.3. Canvas

  1. [react, canvas] How to create a canvas using react (view)


export default class App extends React.Component {

    ...


    render() {

      return (

        <div className="App" >

          <div className="canvasWave"><canvas width="600" height="300"></canvas></div>

        </div>

    );

  }

}



1.6.4. Heading

  1. [react, h2] How to write a hello world react app (view)

1.6.5. Input

  1. [react, input, example] 連動計算的範例 (view) (demo)

  2. [react, checkbox] An example for the checkbox (view)

  3. [react, form, submit] How to handle submit (view)

1.6.6. Slides

  1. [react, slide] How to get the HTML slide object? (view)

1.6.7. Button

  1. [react, button, animated] 3D animated react button (ref) (ref2) xxx

  2. [react, material-ui, button] How to use material-ui button in React app (view)


yarn add @material-ui/core


# code

import Button from '@material-ui/core/Button';

...

<Button onClick={onClickHandler} variant="contained" color="primary">

        {state}

</Button>


  1. [react, button, callback] How to handle the callback function (view)

  2. [react, material-ui, button] Title always upper case (ref)

  3. [react, button] How to add onClick event to a button component (view)


// key:

//     Step 1: UI part: find the render method

//     Step 2: add the html onClick event

// ref

class Square extends React.Component {

    render() {

        return (

            <button className='square' onClick={function() {alert('click');}}>

                {

                    this.props.value

                }

            </button>

        );

    }

}



import React from 'react';

export default class App extends React.Component {

    constructor(props:any) {

        super(props);

        this.onClicked = this.onClicked.bind(this);

    }


    onClicked () {

        console.log('click');

    }


    render() {

      return (

          <div className="App">

                <button onClick={this.onClicked}> Play</button>

          </div>

    );

  }

}



  1. [react, button, evergreen] How to create a evergreen button using react (ref)


npx create-react-app my-app

cd my-app

yarn add evergreen-ui


// File: ./src/App.js

import { Button } from 'evergreen-ui'


<div className="App">

     ....

     <Button appearance="primary">I am using 🌲 Evergreen!</Button>

</div>



1.6.8. Switch

  1. [react, material-ui, switch] How to use Material-ui Switch component (view)

1.6.9. Progress

  1. [react, material-ui, progress] The progress (ref)

1.6.10. Table

  1. [react, spreadsheet] How to createa spreadsheet using react (ref)

  2. [react, spreadsheet] React component like SpreadSheet (ref)

  3. [react, spreadsheet, google] How to access and display googl sheets using reactorjs (ref)

  4. [react, grid] How to create a spreadsheet -- adgrid (ref)

  5. [react, table, crud] React Table CRUD example using Hooks & react-table v7 (ref)

  6. [react, table, crud] React Hooks CRUD example with Axios and Web API (ref)

1.6.11. Form

  1. [react, ui, form] formik (ref)

1.6.12. Dialog

  1. [react, ui, dialog] How to create a dialog using React SkyLight (ref)

1.6.13. Calendar

  1. [react, ui, calendar] A Survey on Calendar (view)

1.6.14. Menu

  1. [react, ui, menu] Examples (view)

  2. [react, ui, menu] A ReactJS circular menu (ref)

  3. [react, ui, menu] A stateless tree menu component for React (ref)

  4. [react, ui, menu] Path Fly Out menu recreated using React Motion (ref)

1.6.15. Tree View

  1. [react, material, tree] The material tree view (ref)

  2. [react, tree, draggable] A Draggable tree component for react (ref

  3. [react, tree, draggable] react-sortable-tree (ref), (ref_survey)

  4. [react, tree, search] TreeView with Search Bar (ref)

  5. [react, tree] deni-react-treeview (ref), (ref_survey)

  6. [react, tree] Treebeard (ref), (ref_survey)

  7. [react, tree, animation] The animation tree (ref), (ref_survey)

1.7. Server-related

  1. [react, flask] React and Flask Full Stack Web app: Component-oriented and Data-driven (ref)

  2. [react, express, deploy] How to deploy the React App with Express (view)

  3. [react, express, restfulAPI] How to implement a restfulAPI using Express and React (view)

  4. [react, express, sse] How to create server that streams events to the front-end client using Express and React**** (view), (blog)

  5. [react, express, sse, get] How to create a express server accepting RestfulAPI to change it's status showing on client (view), draft

  6. [heroku, react] Deploy your React app on Heroku (view)

1.8. CRUD

  1. [react-admin] react-admin (sheet), (ref)

  2. [react-admin] Bootstrap the react-admin (view), (blog)

  3. [react-admin, firebase] How to use react-admin with Firebase (draft)

  4. [react, admin] CRM Starter Admin App built with react and Ant Design (ref)

  5. [react, framework, admin] reduction-admin/react-reduction (github), (demo)

  6. [react, framework, admin] Notus React FREE TAILWIND CSS UI KIT AND ADMIN (ref), (angular)

  7. [react, flask, crud] Build a Simple CRUD (Create, read, update and delete) App with Python, Flask, and React (ref)

1.9. Redux

  1. [redux, official] The official site (ref)

    1. a library for managing and updating application state, using events called "actions"

  2. [redux, debug] The Redux DevTools (ref)

  3. [redux, flow] What the data flow looks like?

    1. Store: 統一從 App Store 讀取 State

    2. Action (Event Handler): 透過 Dispatch 更改 App Store 中的 state

    3. Reducer: 定義 update logic, 下一個 state, 根據目前 state 以及 action.

  4. [redux, action] What is the action in redux?


An action is an event that descripts something that happened in the application. [ref]


// A typical action object

const addTodoAction = {

  type: 'todos/todoAdded',    // type: category/eventName

  payload: 'Buy milk'               // additional information

}


  1. [redux, action] What is the action creator in redux?


A action creator is a function used to create an action object


// A typical action creator function

const addTodo = text => {

  return {

    type: 'todos/todoAdded',

    payload: text

  }

}


  1. [redux, reducer] What is the reducer in redux?


A function that decides how to update the state based on the current statue and an action object.


// A typical reducer function

const initialState = { value: 0 }


function counterReducer(state = initialState, action) {

  if (action.type === 'counter/increment') {

       // 回傳新的 state 物件

        return {

              ...state,    // 複製原來的 state

              value: state.value + 1      // Update state.value

        }

  }

  

  return state 

}


  1. [redux, store] What is the store in redux?


The current Redux application state lives in the store.


// Create a store

import { configureStore } from '@reduxjs/toolkit'


const store = configureStore({ reducer: counterReducer })


console.log(store.getState())

// {value: 0}


  1. [redux, dispatch] What is the dispatch?


The only way to update the application state method is call the store.dispatch(action). The store will save the updated state in side.

  1. [redux, thunk, official] The official site of redux-thunk (ref)

  2. [react, redux] How create a React + Redux App (view), (blog)


1.10. Auth: for User Signup & User Login

  1. [auth, main] Auth: for User Login (view)



2. Angular

2.1. Common

  1. [angular, sheet] The Angular sheet (view)

  2. [official, doc] Google Angular (ref)

  3. [angular cli, version] How to check the Angular CLI version (ref)


ng version

  1. [angular, cli, offical] The Angular cli official site (ref)

  2. [angular cli, version] How to downgrade the Angular CLI version (ref)(ref2-typescript)


sudo npm uninstall -g @angular/cli

sudo npm cache clean

sudo npm install -g @angular/cli@1.4.1

  1. [angular, tslint, issue] Not using the local TSLint version found for xxx To enable code execution from the current workspace you must enable workspace library execution.(ref)


2.2. App

  1. [angular, app] Creating a single page todo app with node and angular (ref)

  2. [angular, app] How to create an Angular application in one step (view)


Step 1: Create template app

ng new angular-tour-of-heroes

cd angular-tour-of-heroes

yarn start     # ng serve --open


Step 2: Modify the template

File: src/app/app.component.html

<h1>{{title}}</h1>



  1. [angular, style] How to setup a consistent look across all components in application? (ref)


File: src/styles.css


2.3. Component

  1. [angular, component, create] How to create a angular component


Command

ng generate component my-comp


Change

Create:  Define the new component

  1. folder: app/my-comp

  2. files: 

    1. my-comp/my-comp.component.ts


...selector: 'app-my-comp', // <<--- the element selector


  1. my-comp/my-comp.component.html

Update

  1. files:

    1. app.module.ts

  1. [angular, component, show] How to display the component in App component?


Key

// Add the the element selector to the app.component html template

ex:

<app-heroes></app-heroes>


  1. [angular, component, status, update] How to update the Component status (view)


Key:

export class xxxComponent{   // <-- component.ts

   variable = 'xxxx'

}


{{variable}}    // <---- html


Detail

// File: app.component.ts

...

export class AppComponent {

  title = 'Tour of Heroes';

}


// File: app.component.html

<h1>{{title}}</h1>

  1. [angular, component, button] How to create a button using Angular in 3 steps (view)

2.4. CRUD

  1. [react, framework, admin] Notus Angular FREE TAILWIND CSS UI KIT AND ADMIN (react), (angular)

2.5. Debug

  1. [alert] How to show a message-box liked window

    1. window.alert("sometext");






3. HTML5

  1. [html, color] color (ref), (color map)

  2. [html, css, display] How to specify an html element is display (view)


Key: 

block: 佔據整行

In-line: 全部放在一行

none: 不顯示


Code:

<style>

li {

  display: block;

}

</style>


  1. [html, code] URL decoder (ref)


%E9%87%91%E8%8F%AF92  --> 華山92


  1. [html, sumit, get] How to create a GET form (ref)

  2. [html, alert] How to show alert box (ref)


alert("I am an alert box!");

  1. [html, document] How to write text on the page


Key:

document.write(i.toString() + '<br>');


Example:

for(let i = 1; i<7; i++){

            document.write(i.toString() + '<br>');

}


  1. [html, mine] The Media Type (ref), all availbe Media type (ref)

  2. [html, javascript] How to embed javascript code to html file (view)


<body>

    <script>

    </script>

</body>

  1. [html, javascript] How to embed javascript file to html (ref)


<script src="myscripts.js"></script>

  1. [html, document, getElementById] How to query a html element by id (view), (blog)

  2. [html, canvas, data] How to convert the HTML canvas to dataURL (ref)


var canvas = document.getElementById('canvas');

var dataURL = canvas.toDataURL();

console.log(dataURL);

// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby

// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"


  1. [html, dataURL, blob ] How to convert the dataURL to binary blob (view)



3.1. List item

  1. [html, item] The normal form (ref)


<ul>

  <li>Coffee</li>

  <li>Tea</li>

  <li>Milk</li>

</ul>


  1. [html, item, js, list2item] How to create a item list from a list (ref)


const candies = ['snickers', 'skittles', 'twix', 'milky way']

<ul>

            {candies.map(candy => (

              <li key={candy}>

                <button onClick={() => dispense(candy)}>grab</button> {candy}

              </li>

            ))}

          </ul>



3.2. File

  1. [html, file] How to select a file from browser (ref)


public browserSelectFile(){

        var input = document.createElement('input');

        input.type = 'file';

        input.addEventListener('change', (event) => {

            if(event.target === null){

                LoggerService.logger.warning('[Warn] selectFileBrowser, event.target === null. (User cancel?). Act: do nothing.');

                return;

            }

            const fileList = (event.target as HTMLInputElement).files;

            console.log(fileList);

        });


        input.click();


        

    }

  1. [html, file] Read the content from file  (ref)


var input = document.createElement('input');

input.type = 'file';


input.onchange = e => { 


   // getting a hold of the file reference

   var file = e.target.files[0]; 


   // setting up the reader

   var reader = new FileReader();

   reader.readAsText(file,'UTF-8');


   // here we tell the reader what to do when it's done reading...

   reader.onload = readerEvent => {

      var content = readerEvent.target.result; // this is the content!

      console.log( content );

   }


}


input.click();


  1. [html, file, binary] How to read binary file 




3.3. Button

  1. [html, button ,create] How to create a button with ID


let button = document.createElement('button');

button.setAttribute("id", strID);


  1. [html, button, create] How to create a button (view)


<html lang="en">

<body>

<script type="application/javascript">

    let button = document.createElement('button');

    button.innerHTML = 'ok';  // set the button content = "ok"

    button.addEventListener('click', function() {

        console.log('clicked');

        

    });

    var body = document.getElementsByTagName("body")[0];

    body.appendChild(button);

</script>

</html>


  1. [html, button, get] How to get the button element by Id


let btPlay = document.getElementById("btPlayId");

 if(btPlay === null){

  console.log('[Error] btPlay === null');

  return;

 }

 btPlay.innerText = 'playing';

  1. [html, button, text] How to change the html button text?


let btPlay = document.getElementById("btPlayId");

 if(btPlay === null){

  console.log('[Error] btPlay === null');

  return;

 }

 btPlay.innerText = 'playing';


  1. [html, button, addEventListener] How to add an EventListener (ref)

    1. Use => allow function

class MyClass{

   initUI(){

        let button = document.createElement('button');

        button.innerHTML = 'ok'; 

        const that = this;

        button.addEventListener('click', => () {

                // this.constructor.name => MyClass

                console.log('this.constructor.name = ', this.constructor.name);        

                this.myFun();

        });

   }

        

    myFun(){

         console.log('myFun()');

    }

} // end of class


  1. Use a const that to save this reference

class MyClass{

   initUI(){

        let button = document.createElement('button');

        button.innerHTML = 'ok'; 

        const that = this;

        button.addEventListener('click', function () {

                // this => HTMLButtonElement

                console.log('this.constructor.name = ', this.constructor.name); 


                // that => MyClass

                console.log('that.constructor.name = ', that.constructor.name);

                that.myFun();

        } );

   }

        

    myFun(){

         console.log('myFun()');

    }

} // end of class

  1. Bind a inline anonymous function (ref)

class MyClass{

   initUI(){

        let button = document.createElement('button');

        button.innerHTML = 'ok'; 

        const that = this;

        button.addEventListener('click', function () {

                // this.constructor.name => MyClass

                console.log('this.constructor.name = ', this.constructor.name);        

                this.myFun();

        }.bind(this) );

   }

        

    myFun(){

         console.log('myFun()');

    }

} // end of class


class MyClass{

   initUI(){

        let button = document.createElement('button');

        button.innerHTML = 'ok'; 

        button.addEventListener('click', evt => this.onClick(evt));

   }

    onClick(evt){

        console.log('clicked');

        this.myFun();

    }

    

    myFun(){

         console.log('myFun()');

    }

} // end of class

  1. [html, image] 


3.4. Request

  1. [html, xhr, get] How to use GET method to access remote api with XMLHttpRequest (view)

  2. [html, xhr, get] How to use GET method to access remote api using XMLHttpRequest with React client and Express server*** (view), (blog)

  3. [html, xhr, get, onLoad] Use arrow function to handle onLoad event with XMLHttpRequest (ref)


class MyClass {

     loadAudioBuffer(url){

        var request = new XMLHttpRequest();

        request.open('GET', url, true);

        request.responseType = 'arraybuffer';

        // Decode asynchronously

        request.onload = () => {

            this.context.decodeAudioData(request.response, function(theBuffer) {

                console.log('Get the data.')

                let buffer = theBuffer;

                console.log('buffer = ', buffer);

                }, function () {

                    console.log('[Error] loadAudioBuffer:: decodeAudioData error.')

                });

        }

        request.send();

    }

    

}

  1. [html, xhr, post, ArrayBuffer] How to post an ArrayBuffer data to server using XMLHttpRequest, React and Express *** (view), (blog)

  2. [html, xhr, post, palaintext] How to post an plaintext data to server using XMLHttpRequest, React and Express *** (view), (blog)

  3. [html, xhr, post, json] How to post JSON data to server using XMLHttpRequest, React, Express and AJV (view), (blog)



4. CSS

  1. [css, tailwindcss] The Tailwindcss (ref)

  2. [css, center] Center


.center {

    margin: auto; /* To horizontally center a block element, use margin:auto*/

    background: lime;

    width: 66%;

  }


// Usage

        <div>

            <div>{props.labName}</div>

            <div id="graph"  className="center"> </div>

        </div>




5. UI Framework

  1. [ui] perfect-scrollbar (ref)

  2. [ui] smooth scrollbar (ref)


            container

                 /

       +--------+

  #####################

  #    |        |     #

  #    |        |     #

  #    +--------+     # -- content

  #                   #

  #                   #

  #####################


  1. [ui, kanban] jkanban (ref) (ref-ionic)

    1. add item, add board, delete board 

  2. [ui, drag]  dragula (ref

  3. [ui, booking] gantt-schedule-timeline-calendar (ref)



6. Authorization

  1. [author, library, login] How to use otaka to do authorization (ref) (usage)

6.1. Common

  1. [framework] DoJo (go)

  2. [ui] ONSen (ref)

  3. [ui + cordova + IDE + phone debug tool] Ionic -- IDE + ionic view (phone debug platform) + , (ref)

  4. [bundle, cordova] Cordova = typescript + AngularJS + Onsen UI (view) (ref)

  5. [chrome, context] chrome context menu programming (view)

  6. [dictionary] CDICT, http://cdict.net/?q=Test

  7. [google, sheets, json] Get the Google sheets data via json format (ref)

  8. [google, sheets, ajax] Edit, Insert, Delete Google sheet (ref)


[Server] Open-Shift

[Back-End] Google Script: Write Update API

[Fonrt-End] AJAX: Access 

  1. [javascript, grid] How to create a spreadsheet -- adgrid (ref)





7. WebAPI

7.1. Console

  1. [console, hex] How to print out a message in hex (ref)


let buf:Buffer = Buffer.from([1, 2, 3]);

console.log('Data in Hex = ', buf.toString('hex')

  1. [console, raw2hex] How to convert the raw byte array to hex (ref)


function handleNotifications(event) {

  let value = event.target.value;

  let a = [];

  // Convert raw data bytes to hex values just for the sake of showing something.

  // In the "real" world, you'd use data.getUint8, data.getUint16 or even

  // TextDecoder to process raw data bytes.

  for (let i = 0; i < value.byteLength; i++) {

    a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));

  }

  log('> ' + a.join(' '));

}



7.2. Keyboard

  1. keyboard event (view)

7.3. Touch

  1. Touch UI Library

    • Sencha (view), very good

    • TouchSwipe (view)

    • JQueryMobile (view)

  2. Gesture Library

  3. W3C Touch Spec

    • S3C Touch Event (view)

  4. Tutorial (view)

7.4. Timer

  1. [timer, interval] How to use timer (view)


function main() {

    simInterval = setInterval( () => {

       console.log('Hello');

       }, 500);

}

  1. [node, timer, timeout] How to set timeout (ref)


// normal version

function main() {

    setTimeout();

}


function my_next(strMessage) {

    console.log('my_next::', strMessage);

}



// argument version

function main() {

    setTimeout(my_next.bind(null, 'this is a argument));

}


function my_next(strMessage) {

    console.log('my_next::', strMessage);

}

  1. [node, date, time] How to show year-month-day-hour-min-sec


Code

const date = new Date();

const dateTimeFormat = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'numeric', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}) 

const [{ value: month },,{ value: day },,{ value: year },,{ value: hour },,{ value: minute },,{ value: second }] = dateTimeFormat.formatToParts(date ) 


console.log(`${year}-${month}-${day}-${hour}-${minute}-${second}`)


Output

2020-8-28-04-17-38


References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

  2. https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date




  1. [date] How to get date information (view)

  2. [timestamp] How to get timestamp (view)


7.5. WebBluetooth

  1. [webbluetooth] The WebBluetooth browser compatibility (ref)

  2. [webbluetooth, check] How to check if the browser supports the Web Bluetooth (view)


        if (!navigator.bluetooth) {

            document.write("Web Bluetooth is not supported.");

        }   


7.6. WebAudio

  1. [sheet] The WebAudio sheet (sheet)

  2. [node, audio, format] How to get the wave format (ref)


var fs = require('fs');

var wav = require('wav');


strFullFilename = './ImperialMarch60_mono_signed_16bit_pcm_22k.wav';

var file = fs.createReadStream(strFullFilename);

var reader = new wav.Reader();

 

// the "format" event gets emitted at the end of the WAVE header

reader.on('format', function (format) {

  console.log('format = ', format)

});

 

// pipe the WAVE file to the Reader instance

file.pipe(reader);


  1. [webaudio, source] How to create Sin audio buffer source for WebAudio to streaming play (view)


        let source:AudioBufferSourceNode = this.__audioCtx.createBufferSource();

        source.buffer = myAudioBuffer;   // <<-------

        source.connect(this.__audioCtx.destination);

        source.start(this.__numStartAt);



  1. [audio, seek] seek (view), (ref)

  2. [audio]  playback, m4a (view)

  3. [audio, gain, change] How to change the audio gain dynamicly (view)

  4. [audio, filter, bandpass] How to setup bandpass filter using webaudio (view)

  5. [audio] audio2array, array2audio, playback, wavefile object (ref)

  6. [audio, wavefile] How to read a wave file (ref)


const WaveFile = require('wavefile');


// read the audio file

let buffer = fs.readFileSync(fullfilename_snd)

let wav = new WaveFile(buffer);

console.log('wav = ', wav)

  1. [audio, audio2sample) How to read the audio samples

    1. Key

      1.  sample = wav.getSample(i)

const WaveFile = require('wavefile');


// read the audio file

let buffer = fs.readFileSync(fullfilename_snd);

let wav = new WaveFile(buffer);

console.log('wav = ', wav);


// audio2buffer

console.log('chunkSize = ', wav.data.chunkSize);

console.log('bitsPerSample = ', wav.fmt.bitsPerSample)

numOfSample = wav.data.chunkSize/wav.fmt.bitsPerSample

console.log('numOfSample = ', numOfSample)

for(i = 0; i < numOfSample; i++){

    sample = wav.getSample(i)

    console.log(i, 'sample = ', sample)

}


  1. [audio, sample2audio] How to write a wave file from a sample array


console.log('chunkSize = ', wav.data.chunkSize);

console.log('bitsPerSample = ', wav.fmt.bitsPerSample)

numOfSample = Math.floor(wav.data.chunkSize*8/wav.fmt.bitsPerSample)

console.log('numOfSample = ', numOfSample)


var int16SampleBuffer = new Int16Array(numOfSample);


for(i = 0; i < numOfSample; i++){

    sample = wav.getSample(i)

    // console.log(i, 'sample = ', sample)

    int16SampleBuffer[i] = sample

}


// buffer2wav

let wav2 = new WaveFile();

wav2.fromScratch(1, 8000, '16', int16SampleBuffer);

fs.writeFileSync('wav2.wav', wav2.toBuffer());




  1. [webaudio, source, rxjs] How to create Sin audio buffer source for WebAudio to streaming play (view)

  2. [webaudio, get data] How to get the mp3 data from remote URL (view)

  3. [webaudio, algo, queue, cache] How to create a cache for storing the incoming variance length data (ref)


Q: 如果不要用 queue, 直接使用 Buffer. 不斷往後 concats, 避開切割的亂雜運算,是否能解決 glitch?


1. 加入資料

this.cache = Buffer.alloc(0)


this.cache = Buffer.concat([this.cache, buffer])


2. 取出資料: 用 slice(0, numbyteperframe] 從前面取資料


while (this.cache.length > 960) {

        const buffer = this.cache.slice(0, 960) // 取資料

        this.cache = this.cache.slice(960) // 滑動

        const samples = new Int16Array(new Uint8Array(buffer).buffer)

        this.onData({

          bitsPerSample: 16,

          sampleRate: 48000,

          channelCount: 1,

          numberOfFrames: samples.length,

          type: 'data',

          samples

        })

      }

  1. [webaudio, audioworklet] What is the AudioWorklet (ref)

  2. [webaudio, audioworklet] How to create a white-noise source using Audio Worklet Node (view)

  3. [webaudio, playback, webrtc] How to play a WebRTC stream with an audio element and add sound effect in real-time (view)


const source = context.createMediaStreamSource(remoteStream);

  source.connect(filter);

  filter.connect(gainNode);

  gainNode.connect(context.destination);

  1. [webaudio, render, canvas, Scope, javascript] How to visualize the web audio using scope using Scope with javascript** (view)

  2. [webaudio, render, canvas, Scope, react] How to visualize the web audio using scope with React*** (view)

  3. [webaudio, render, canvas, react] Audio visualisation with the Web Audio API and React (ref)

7.7. WebRTC

  1. [webrtc, faq] The WebRTC FAQ (view)

  2. [webrtc] How to implement a webrtc audio source to deliver WAV file (download)

    1. rtcaudiosourcewavefile.js

    let byteBuffer = fs.readFileSync(strFullFilename);

    let offset = 44;

    function next() {

      for (let i = 0; i < numberOfFrames; i++) {

        if (offset < byteBuffer.length - 2){

          samples[i] = byteBuffer.readInt16LE(offset);

        }else{

          //console.log('offset > byteBuffer.length - 2');

          samples[i] = 0;

          offset = 0;

        }

        offset = offset + 2; // 16-bit = 2 bytes

      }

      //console.log('frame ', cntFrame, ' samples[0] = ', samples[0]); cntFrame++;

      source.onData(data);

      // eslint-disable-next-line

      scheduled = options.schedule(next, secondsPerSample*numberOfFrames*1000 );

    }


    let scheduled = options.schedule(next);



7.8. WebAssembly

  1. [webAssembly, official] The official site (ref)

7.9. WebSerial

  1. [webserial, faq] The webserial sheet (view)


8. Animation libraries

8.1. Spring

  1. [spring, official, example] examples (ref

  2. [spirnt, tutorial] video (ref)

8.2. Famer

  1. [framer, official] site (ref)

9. Graphic libraries

9.1. Survey

  1. The Data Visualisation Catalogue (ref)

  2. Open Source Plotting Libraries (primarily for React) (ref)

9.2. 3D libraries

  1. [graphosaurus] Draw 3D point on screen (view) (ref)

  2. [elegans] Draw 3D point on screen (ref)

  3. [three.js] Draw 3D (ref)

  4. [three.js] How to use three.js (view)

9.3. Image libraries

  1. [canvas-js, official] The official site (ref)

  2. [canvas-js, showImage] How to show a canvas on your browser (view)

  3. [canvas-js, text, background] How to show a text on canvas with background (view)

  4. [canvas-js, text, height] How to get the font height (view)

  5. [canvas-js, rectangle] How to show a rectangle on your browser (view)

  6. [canvas-js, clean] How to clean the canvas (view)

  7. [canvas-js, savetofile] How to save a canvas image to a local file (view)

9.4. Map, CesiumJS

  1. [cesiumjs, init] The first 3D app (view)

  2. [cesiumjs, camera] How to setup the camera fly to the target (view)

10. Chart libraries

10.1. comm

  1. [chart, survey] Charting Library Survey (ref)

  2. [chart, performance] Performance Test (ref)

    1. Timechart (ref), uplot (ref) >> chart.js

10.2. High performance chart libraries

10.2.1. Dygraphs

  1. [dygraphs, official] The official site (ref)

    1. D3, speed: middle, 

    2. Javascript: ok, typescript: ok, React: ok

    3. stream

  2. [dygraphs, performance] benchmarking for Plots with many points (ref), good enough

  3. [dygraphs, play] A dynamic update sample on dygraphs in JSFiddle playground**** (view)(ref)


  4. [dygraphs, react, real-time] Show live time-serial data using React, dygraphs, push/pull mode *** (view)

  5. [react, function component, dygraph]  How to show a live updated time-serial data using dygraphs in React function component (view)

10.2.2. TimeChart

  1. [timechart, official] The official site (ref)

    1. Webgl, very fast

    2. Javascript: ok, React: ?

  2. [timechart,, real-time] How to draw a live serial data in real-time (ref)

10.2.3. uPlot

  1. [uplot, official] The official site (ref)

    1. Webgl, very fast

    2. Javascript: ok, React: yes


  2. [uplot, real-time] How to draw a live serial data in real-time (ref)

  3. [uplot, react] a react example (ref)

  4. [uplot, react, wrap] The react wrap (ref), (class vs. function ex)

  5. [uplot, react, function] How to use uplot (github)

10.2.4. Webgl-plot

  1. [webgl-plot, official] The official site (ref)

    1. Webgl, very fast, width only 1

    2. Javascript: ok, React: ?

  2. [webgl-plot, real-time] How to draw a live serial data in real-time ** (ref)



10.2.5. [canvas] d3

  1. [d3, official] The official site, d3 (ref)

  2. [d3, basic shape] Basic shape (ref)

  3. [d3, circle] How to draw a circle (view), (js)

  4. [d3, circle] How to draw 3 circle using data binding (view)

  5. [d3, curve] (ref), (curve example)

  6. [d3, real-time, d3] How to draw a live serail data in real-time (ref)

  7. [d3, real-time, rickshaw] The rickshaw (ref), start: 6.5k


10.2.6. [canvas] Wavesurfer

1. [time-line] official (ref)

10.2.7. Livechart

  1. [livechart, official] The official site (ref)


10.2.8. Chart.js

10.2.8.1. Javascript (chart.js only)

  1. [chartjs, official] The official site (ref)

    1. 缺點: 速度太慢

  2. [chartjs, javascript, line] How to use chartjs (view)

  3. [node, chartjs] How to write a node code to use chartjs for charting (ref)

  4. [chartjs, javascript, line, live] How to show a live line chart using pure javascript (view)***, 最簡單, 所有可執行的範例, 

    1. (how to use typescript to implement this?, 非同步測試?)

  5. [chartjs, interact, pure] How to draw a live bar chart in real-time (ref) (github)


10.2.8.2. Typescript + React

  1. [chartjs. react, typescript] How to show a static line chart with React (view)

10.2.8.3. react-chartjs-2

  1. [react-chartjs-2, real-time, ] How to draw a live line chart in real-time (view)

10.2.8.4. chartjs-plug-stream

  1. [chartjs-plug-streaming, data feed] The Data feed models (ref)

  2. [chartjs-plug-streaming, javascript] Show live time-serial data using pure javascript (html 版本順暢)

  3. [chartjs-plug-streaming, react] Show live time-serial data using React*** (view  react 版會頓一下, 奇怪


React 版卡頓似乎跟 char.js 版本有關.

solution

yarn add chart.js@2.8.0 (比較順) 

yarn add chart.js@2.7.3 (比較順) 


  1. [chartjs-plug-streaming, chart] How to get the chart object from chart.js react object (ref)(official, react)


<Line

     data={this.state}

     height={5}

     width={20}

     ref = {(reference) => this.reference = reference}

/>



  1. [chartjs-plug-streaming, react] Show live time-serial data using React with Push Model (Listening Based)*** (view)


Key:


class App extends Component {

    private myRefLine:any = null;  // for Line chart obj

    ...


    componentDidMount(){

           ...

           if (this.myRefLine == null)

                 return;


             let myChart:any = this.myRefLine.chartInstance;

             myChart.data.datasets[0].data.push({

                   x: Date.now(),

                   y: Math.floor(Math.random() * 100)

             });

             // update chart datasets keeping the current animation

            myChart.update({

                 preservation: true

             });

 

            ...

    }


    render() {

       return (

         <Line

           data={this.dictDataCfg}

           options={this.dictOptions}

           ref = {(ref) => this.myRefLine = ref}

          />

    );

  }




10.2.9. Recharts

  1. [recharts, official] The examples (ref)

  2. [recharts, real-time] How to draw a live bar chart in real-time (ref) (line)


10.2.10. Others

  1. [camera] communicate with the network camera (ref)

  2. [animation, physical] CSS Animation (ref)

  3. [chart, rea-time, epoch] (ref)