1577270742
Slash commands have long existed in chat since the IRC days, but they have been reimagined by modern chat apps such as Slack. They act as shortcuts for simple or complex workflows within an application.
To follow along with this tutorial, you need need to:
Go to your Chatkit dashboard, create a new Chatkit instance for this tutorial and take note of your Instance Locator and Secret Key in the Credentials tab.
Also make sure your Test Token Provider is enabled as shown below. Once enabled, the endpoint from which the test token will be generated will be displayed for you to copy and paste. Note that the test token is not to be used in production. More information on the authentication process for production apps can be found here.
Next, click the Console tab and create a new user and a brand new room for your instance. Take note of the room ID as we’ll be needing it later on.
Run the command below to install create-react-app globally on your machine, then use it to bootstrap a new react React application:
npm install -g create-react-app
create-react-app chatkit-slash-cmd
Once the app has been created, cd
into the new chatkit-slash-cmd
directory and install the following additional dependencies that we’ll be needing in the course of building the chat app:
npm install @pusher/chatkit-client prop-types skeleton-css --save
You can now start your development server by running npm start
then navigate to http://localhost:3000 in your browser to view the app.
Open up src/App.css
in your code editor, and change it to look like this:
// src/App.css
.App {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
.sidebar {
height: 100%;
width: 20%;
background-color: darkcyan;
}
.login {
padding: 5px 20px;
}
.sidebar input {
width: 100%;
}
.chat-rooms .active {
background-color: whitesmoke;
color: #181919;
}
.chat-rooms li {
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px 20px;
font-size: 18px;
color: #181919;
cursor: pointer;
border-bottom: 1px solid #eee;
margin-bottom: 0;
}
.room-list h3 {
padding-left: 20px;
padding-right: 20px;
}
.room-unread {
display: inline-block;
width: 20px;
height: 20px;
line-height: 20px;
border-radius: 50%;
font-size: 16px;
text-align: center;
padding: 5px;
background-color: greenyellow;
color: #222;
}
.chat-rooms li:hover {
background-color: #D8D1D1;
}
.chat-screen {
display: flex;
flex-direction: column;
height: 100vh;
width: calc(100vw - 20%);
}
.chat-header {
height: 70px;
flex-shrink: 0;
border-bottom: 1px solid #ccc;
padding-left: 10px;
padding-right: 20px;
display: flex;
flex-direction: column;
justify-content: center;
}
.chat-header h3 {
margin-bottom: 0;
text-align: center;
}
.chat-messages {
flex-grow: 1;
overflow-y: scroll;
display: flex;
flex-direction: column;
justify-content: flex-end;
margin-bottom: 0;
min-height: min-content;
}
.message {
padding-left: 20px;
padding-right: 20px;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.message span {
display: block;
text-align: left;
}
.message .user-id {
font-weight: bold;
}
.message-form {
border-top: 1px solid #ccc;
}
.message-form, .message-input {
width: 100%;
margin-bottom: 0;
}
input[type="text"].message-input {
height: 50px;
border: none;
padding-left: 20px;
}
Next, let’s set up a basic chat interface so we can add the slash command functionality.
// src/App.js
import React, { Component } from "react";
import {
handleInput,
connectToChatkit,
connectToRoom,
sendMessage,
} from "./methods";
import "skeleton-css/css/normalize.css";
import "skeleton-css/css/skeleton.css";
import "./App.css";
class App extends Component {
constructor() {
super();
this.state = {
userId: "",
currentUser: null,
currentRoom: null,
rooms: [],
messages: [],
newMessage: "",
};
this.handleInput = handleInput.bind(this);
this.connectToChatkit = connectToChatkit.bind(this);
this.connectToRoom = connectToRoom.bind(this);
this.sendMessage = sendMessage.bind(this);
}
render() {
const {
rooms,
currentRoom,
currentUser,
messages,
newMessage,
} = this.state;
const roomList = rooms.map(room => {
const isRoomActive = room.id === currentRoom.id ? 'active' : '';
return (
<li
className={isRoomActive}
key={room.id}
onClick={() => this.connectToRoom(room.id)}
>
<span className="room-name">{room.name}</span>
</li>
);
});
const messageList = messages.map(message => {
const arr = message.parts.map(p => {
return (
<span className="message-text">{p.payload.content}</span>
);
});
return (
<li className="message" key={message.id}>
<div>
<span className="user-id">{message.senderId}</span>
{arr}
</div>
</li>
)
});
return (
<div className="App">
<aside className="sidebar left-sidebar">
{!currentUser ? (
<div className="login">
<h3>Join Chat</h3>
<form id="login" onSubmit={this.connectToChatkit}>
<input
onChange={this.handleInput}
className="userId"
type="text"
name="userId"
placeholder="Enter your username"
/>
</form>
</div>
) : null
}
{currentRoom ? (
<div className="room-list">
<h3>Rooms</h3>
<ul className="chat-rooms">
{roomList}
</ul>
</div>
) : null
}
</aside>
{
currentUser ? (
<section className="chat-screen">
<ul className="chat-messages">
{messageList}
</ul>
<footer className="chat-footer">
<form onSubmit={this.sendMessage} className="message-form">
<input
type="text"
value={newMessage}
name="newMessage"
className="message-input"
placeholder="Type your message and hit ENTER to send"
onChange={this.handleInput}
/>
</form>
</footer>
</section>
) : null
}
</div>
);
}
}
export default App;
Create a new methods.js
file within the src
directory and add the following code into it:
// src/methods.js
import { ChatManager, TokenProvider } from "@pusher/chatkit-client";
function handleInput(event) {
const { value, name } = event.target;
this.setState({
[name]: value
});
}
function connectToChatkit(event) {
event.preventDefault();
const { userId } = this.state;
const tokenProvider = new TokenProvider({
url:
"<test token provider endpoint>"
});
const chatManager = new ChatManager({
instanceLocator: "<your chatkit instance locator>",
userId,
tokenProvider
});
return chatManager
.connect()
.then(currentUser => {
this.setState(
{
currentUser,
},
() => connectToRoom.call(this)
);
})
.catch(console.error);
}
function connectToRoom(roomId = "<your chatkit room id>") {
const { currentUser } = this.state;
this.setState({
messages: []
});
return currentUser
.subscribeToRoomMultipart({
roomId,
messageLimit: 10,
hooks: {
onMessage: message => {
this.setState({
messages: [...this.state.messages, message],
});
},
}
})
.then(currentRoom => {
this.setState({
currentRoom,
rooms: currentUser.rooms,
});
})
.catch(console.error);
}
function sendMessage(event) {
event.preventDefault();
const { newMessage, currentUser, currentRoom } = this.state;
const parts = [];
if (newMessage.trim() === "") return;
parts.push({
type: "text/plain",
content: newMessage
});
currentUser.sendMultipartMessage({
roomId: `${currentRoom.id}`,
parts
});
this.setState({
newMessage: "",
});
}
export {
handleInput,
connectToRoom,
connectToChatkit,
sendMessage,
}
Make sure to replace the <test token provider endpoint>
, <your chatkit instance locator>
and <your chatkit room id>
placeholders above with the appropriate values from your Chatkit dashboard.
At this point, users can converse in a room. What is left is to add slash commands to the room. To demonstrate this functionality, we’ll make a /news [topic]
command that will look up news headlines on the provided topic, and post the first three results to the room.
Head over to https://newsapi.org and register for a free account. Once your account is created, your API key will be presented to you. Take note of it as we’ll be using it shortly.
Next, modify your methods.js
file to look like this:
// src/methods.js
// [..]
function handleSlashCommand(message) {
const cmd = message.split(" ")[0];
const query = message.slice(cmd.length)
if (cmd !== "/news") {
alert(`${cmd} is not a valid command`);
return;
}
return sendNews.call(this, query);
}
function sendMessage(event) {
event.preventDefault();
const { newMessage, currentUser, currentRoom } = this.state;
const parts = [];
if (newMessage.trim() === "") return;
if (newMessage.startsWith("/")) {
handleSlashCommand.call(this, newMessage);
this.setState({
newMessage: "",
});
return;
}
parts.push({
type: "text/plain",
content: newMessage
});
currentUser.sendMultipartMessage({
roomId: `${currentRoom.id}`,
parts
});
this.setState({
newMessage: "",
});
}
// [..]
In sendMessage()
, we check if the message starts with a slash character. If so, the message is passed to the handleSlashCommand()
function where we retrieve the command name and the query after the command. If the command is not /news
, a “Command not found” message will be displayed to the user. Otherwise, the query is passed off to the sendNews()
function which you should create above handleSlashCommand()
:
// src/methods.js
function sendNews(query) {
const { currentUser, currentRoom } = this.state;
fetch(`https://newsapi.org/v2/everything?q=${query}&pageSize=3&apiKey=<your news api key>`)
.then(res => res.json())
.then(data => {
const parts = [];
data.articles.forEach(article => {
parts.push({
type: "text/plain",
content: `${article.title} - ${article.source.name} - ${article.url}`
});
});
currentUser.sendMultipartMessage({
roomId: `${currentRoom.id}`,
parts
});
})
.catch(console.error);
}
In sendNews()
, a request for the top three headlines on the requested topic is made to newsapi.org, and the results are sent to the current room. You need to replace <your news api key>
your API key in the URL endpoint above.
Since the news results will contain links, let’s account for that in the way we’re displaying the messages in the room so that the links don’t display as plain text:
// src/App.js
// [..]
class App extends Component {
// [..]
render() {
// [..]
const insertTextAtIndices = (text, obj) => {
return text.replace(/./g, function(character, index) {
return obj[index] ? obj[index] + character : character;
});
};
const messageList = messages.map(message => {
const arr = message.parts.map(p => {
const urlMatches = p.payload.content.match(/\b(http|https)?:\/\/\S+/gi) || [];
let text = p.payload.content;
urlMatches.forEach(link => {
const startIndex = text.indexOf(link);
const endIndex = startIndex + link.length;
text = insertTextAtIndices(text, {
[startIndex]: `<a href="${link}" target="_blank" rel="noopener noreferrer" class="embedded-link">`,
[endIndex]: "</a>"
});
});
return (
<span className="message-text" dangerouslySetInnerHTML={{
__html: text
}}></span>
);
});
return (
<li className="message" key={message.id}>
<div>
<span className="user-id">{message.senderId}</span>
{arr}
</div>
</li>
)
});
// [..]
}
}
export default App;
Try it out! Test the app by using the /news
command along with any topic of your choice. It should work similarly to the GIF below:
In this tutorial, you learned about how slash commands work and how to implement them in a React chat app. You can checkout other things Chatkit can do by viewing its extensive documentation.
Don’t forget to grab the complete source code in this GitHub repository.
#reactjs #javascript
1598839687
If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?
In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.
Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.
React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.
Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.
Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.
The popularity of React Native comes from its advantages. Some of its advantages are as follows:
Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.
React Native is very close to native. Consider the following aspects as described on the React Native website:
Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.
#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native
1621250665
Looking to hire dedicated top Reactjs developers at affordable prices? Our 5+ years of average experienced Reactjs developers comprise proficiency in delivering the most complex and challenging web apps.
Hire ReactJS developers online on a monthly, hourly, or full-time basis who are highly skilled & efficient in implementing new technologies and turn into business-driven applications while saving your cost up to 60%.
Planning to** outsource React web Development services from India** using Reactjs? Or would you like to hire a team of Reactjs developers? Get in touch for a free quote!
#hire react js developer #react.js developer #react.js developers #hire reactjs development company #react js development india #react js developer
1632537859
Not babashka. Node.js babashka!?
Ad-hoc CLJS scripting on Node.js.
Experimental. Please report issues here.
Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.
Additional goals and features are:
Nbb requires Node.js v12 or newer.
CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).
Install nbb
from NPM:
$ npm install nbb -g
Omit -g
for a local install.
Try out an expression:
$ nbb -e '(+ 1 2 3)'
6
And then install some other NPM libraries to use in the script. E.g.:
$ npm install csv-parse shelljs zx
Create a script which uses the NPM libraries:
(ns script
(:require ["csv-parse/lib/sync$default" :as csv-parse]
["fs" :as fs]
["path" :as path]
["shelljs$default" :as sh]
["term-size$default" :as term-size]
["zx$default" :as zx]
["zx$fs" :as zxfs]
[nbb.core :refer [*file*]]))
(prn (path/resolve "."))
(prn (term-size))
(println (count (str (fs/readFileSync *file*))))
(prn (sh/ls "."))
(prn (csv-parse "foo,bar"))
(prn (zxfs/existsSync *file*))
(zx/$ #js ["ls"])
Call the script:
$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs
Nbb has first class support for macros: you can define them right inside your .cljs
file, like you are used to from JVM Clojure. Consider the plet
macro to make working with promises more palatable:
(defmacro plet
[bindings & body]
(let [binding-pairs (reverse (partition 2 bindings))
body (cons 'do body)]
(reduce (fn [body [sym expr]]
(let [expr (list '.resolve 'js/Promise expr)]
(list '.then expr (list 'clojure.core/fn (vector sym)
body))))
body
binding-pairs)))
Using this macro we can look async code more like sync code. Consider this puppeteer example:
(-> (.launch puppeteer)
(.then (fn [browser]
(-> (.newPage browser)
(.then (fn [page]
(-> (.goto page "https://clojure.org")
(.then #(.screenshot page #js{:path "screenshot.png"}))
(.catch #(js/console.log %))
(.then #(.close browser)))))))))
Using plet
this becomes:
(plet [browser (.launch puppeteer)
page (.newPage browser)
_ (.goto page "https://clojure.org")
_ (-> (.screenshot page #js{:path "screenshot.png"})
(.catch #(js/console.log %)))]
(.close browser))
See the puppeteer example for the full code.
Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet
macro is similar to promesa.core/let
.
$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)' 0.17s user 0.02s system 109% cpu 0.168 total
The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx
this adds another 300ms or so, so for faster startup, either use a globally installed nbb
or use $(npm bin)/nbb script.cljs
to bypass npx
.
Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.
To load .cljs
files from local paths or dependencies, you can use the --classpath
argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs
relative to your current dir, then you can load it via (:require [foo.bar :as fb])
. Note that nbb
uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar
in the namespace name becomes foo_bar
in the directory name.
To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:
$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"
and then feed it to the --classpath
argument:
$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]
Currently nbb
only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar
files will be added later.
The name of the file that is currently being executed is available via nbb.core/*file*
or on the metadata of vars:
(ns foo
(:require [nbb.core :refer [*file*]]))
(prn *file*) ;; "/private/tmp/foo.cljs"
(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"
Nbb includes reagent.core
which will be lazily loaded when required. You can use this together with ink to create a TUI application:
$ npm install ink
ink-demo.cljs
:
(ns ink-demo
(:require ["ink" :refer [render Text]]
[reagent.core :as r]))
(defonce state (r/atom 0))
(doseq [n (range 1 11)]
(js/setTimeout #(swap! state inc) (* n 500)))
(defn hello []
[:> Text {:color "green"} "Hello, world! " @state])
(render (r/as-element [hello]))
Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core
namespace is included with the let
and do!
macros. An example:
(ns prom
(:require [promesa.core :as p]))
(defn sleep [ms]
(js/Promise.
(fn [resolve _]
(js/setTimeout resolve ms))))
(defn do-stuff
[]
(p/do!
(println "Doing stuff which takes a while")
(sleep 1000)
1))
(p/let [a (do-stuff)
b (inc a)
c (do-stuff)
d (+ b c)]
(prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3
Also see API docs.
Since nbb v0.0.75 applied-science/js-interop is available:
(ns example
(:require [applied-science.js-interop :as j]))
(def o (j/lit {:a 1 :b 2 :c {:d 1}}))
(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1
Most of this library is supported in nbb, except the following:
:syms
.-x
notation. In nbb, you must use keywords.See the example of what is currently supported.
See the examples directory for small examples.
Also check out these projects built with nbb:
See API documentation.
See this gist on how to convert an nbb script or project to shadow-cljs.
Prequisites:
To build:
bb release
Run bb tasks
for more project-related tasks.
Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb
License: EPL-1.0
#node #javascript
1615544450
Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.
Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.
In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.
In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.
However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.
It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.
As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.
React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.
React is scalable. it utilises a single language, For server-client side, and mobile platform.
React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.
React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.
Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.
As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.
If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation
#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer
1620893794
Looking to hire top dedicated Reactjs developers from India at affordable prices? Our 5+ years of average experienced Reactjs developers comprise proficiency in delivering the most complex and challenging web apps.
Hire ReactJS developers online on a monthly, hourly, or full-time basis who are highly skilled & efficient in implementing new technologies and turn into business-driven applications while saving your cost up to 60%.
Planning to outsource** Reactjs development company in India** ? Or would you like to hire a team of Reactjs developers? Get in touch for a free quote!
#hire react.js developers #hire react js developers #react programmers #react js development company #react native development company #react.js developers