TECH |
Techable(テッカブル) |
裸眼で3D鑑賞できるタブレット「nubia Pad 3D」に注目!医療・教育など幅広い業界の革新に期待 |
https://techable.jp/archives/215899
|
nubiapadd |
2023-08-07 12:00:41 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
初めてのQiita |
https://qiita.com/fermerMask/items/ad1aedf03eea1678be53
|
qiita |
2023-08-07 21:07:38 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
Dockerで代替DNSの動きを確認してみた |
https://qiita.com/pizza_slice/items/4beb1733795837b64441
|
docker |
2023-08-07 21:17:12 |
技術ブログ |
Developers.IO |
小規模コミュニティによる継続交流のすすめ |
https://dev.classmethod.jp/articles/minimum-community/
|
組織開発 |
2023-08-07 12:41:15 |
海外TECH |
MakeUseOf |
The Best Samsung Galaxy Z Flip 5 Case Deals |
https://www.makeuseof.com/best-samsung-galaxy-z-flip-5-case-deals/
|
discounts |
2023-08-07 12:20:38 |
海外TECH |
MakeUseOf |
Unlock Lightning-Speed Charging for Your iPhone: Introducing ESR’s New CryoBoost MagSafe Collection |
https://www.makeuseof.com/esr-gear-level-up-your-magsafe/
|
charging |
2023-08-07 12:00:25 |
海外TECH |
DEV Community |
Auto-Completion and Cocktail mixing with Golang’s Cobra CLI |
https://dev.to/tomfeigin/auto-completion-and-cocktail-mixing-with-golangs-cobra-cli-h26
|
Auto Completion and Cocktail mixing with Golang s Cobra CLIAt Raftt we build a dev tool which enables effortless development on Kubernetes envs Development environments created with Raftt can be interacted with and controlled via a CLI program which we built with the Go programming language Recently we added the ability to auto complete the names of Kubernetes resources in the dev env The auto completion feature improved our UX and made many users happy that they can leverage the terminal to auto complete resource names instead of having to type them out In this post we explain how to implement custom auto completion ability for a CLI tool written in Go and using Cobra We start by walking through the creation of a tiny mixologist app using Cobra The mixologist app is a CLI tool written in Go using the Cobra framework that can make cocktails from a list of ingredients and uses custom auto completion to improve the user experience For reference the code for the CLI application can be found here Here is an example of auto completion of the mixologist CLI The post will then cover how to enable basic auto completion of a specific subcommand and finally how to implement custom auto completion The post concludes with a brief discussion of how this feature is used in the Raftt CLI Create a CLI utility with CobraThis paragraph discusses how to enable auto completion in a CLI tool written in Go using the Cobra framework It walks through the process of creating a small application using Cobra adding a subcommand and implementing basic auto completion for that subcommand It then explains how to implement custom auto completion in order to improve the user experience What is Cobra Cobra is a library for creating powerful modern CLI applications You probably already know about Cobra if you ever wrote a CLI tool in Go but for the few who don t this article contains a short introduction on how to use it For CLI utilities written in Go Cobra is the go to command line wrapper used by the likes of Kubernetes Github CLI Helm and many more In the next section we will build a small application in Go using the cobra framework The mixologist appIn this introduction we will create a mixologist app The app will act as a mixologist which can make a cocktail from a list of ingredients First create the root command for our app cmd root govarrootCmd amp cobra Command Use mixologist Short Mixologist is your personal bartender Long Mixologist acts as a bartender who specializes in cocktail making RunE func cmd cobra Command args string error return cmd Help func Execute if err rootCmd Execute err nil fmt Println err os Exit The rootCmd is the entry point of our mixologist app it prints the help and exits As mentioned before we want our mixologist to mix cocktails to do that we will add the sub command mix The mix subcommand will receive at least arguments controlled by the Args field of the cobra Command cmd mix goimport github com spf cobra golang org x exp slices var mixCmd amp cobra Command Use mix Short make a cocktail Long Mix some ingredients together to make a cocktail Args cobra MinimumNArgs RunE func cmd cobra Command args string error Psuedo code if slices IndexFunc args func s string bool return s Vodka gt amp amp slices IndexFunc args func s string bool return s Orange Juice gt fmt Println You can make a screwdriver cocktail return nil return fmt Errorf i can t make a cocktail from v args func init rootCmd AddCommand mixCmd We now need to tie it all together in our main go file package main import pathToYourApp cmd func main cmd Execute By executing the mixologist with the correct ingredients it can make us a Vodka Screwdriver But if we get the ingredients wrong we will get an error In the next paragraph we will demonstrate how we can leverage cobra to have auto completion in our terminal and make it easier for our users to enjoy our app Basic Auto completionUsers of the mixologist app may find it difficult to guess the available ingredients We should make it easier to use the app by making our CLI utility auto complete an ingredient if it is available in our bar To implement basic auto completion we will set the ValidArgs field of the command like so var availableIngredients string Vodka Gin Orange Juice Triple Sec Tequila simple syrup white rum Kahlua coffee liqueur var mixCmd amp cobra Command Use mix Short make a cocktail ValidArgs availableIngredients Now we need to install the auto completion in our shell cobra can generate auto completion for bash zsh and fish shells out of the box After choosing the shell we can do mixologist completion zsh gt tmp completionsource tmp completionAnd then when we type mixologist tab tab we will get the list of ingredients auto completed That is really cool but it still isn t optimal the command can auto complete ingredients which when mixed together doesn t make any cocktail We want to auto complete the next ingredient only if it can actually combine with all previously mentioned ingredients To achieve that optimal user experience we need to implement custom auto completion we will see how to do that in the next paragraph Custom Auto completionNow our mixologist app auto completes the ingredient list in when pressing tab on the mix subcommand but we want to make it smarter Our opinionated bartender believes that the only thing that can be paired with Vodka is Orange Juice so we want our auto completion to suggest only Orange Juice if the previously mentioned ingredient was Vodka We also don t want to repeat the same ingredient twice so we won t end up mixing Kahlua with Kahlua times To achieve that we need to edit the mix subcommand and use the awesome lo package for some help import github com samber lo var availableIngredients string var mixCmd amp cobra Command Use mix Short make a cocktail ValidArgsFunction func cmd cobra Command args string toComplete string string cobra ShellCompDirective if len args amp amp args Vodka return string Orange Juice cobra ShellCompDirectiveNoFileComp unusedIngredients lo Difference args availableIngredients return unusedIngredients cobra ShellCompDirectiveNoFileComp When we use the auto completion of the mix subcommand by pressing tab twice the terminal will show Notice that selected ingredients do not appear as an option for subsequent auto completions anymore If we give Vokda as the first argument and then press tab twice the terminal will auto complete Orange Juice immediately The new auto completion improved the UX of our mixologist app and made our users much happier Now that we know how to implement custom auto completion using the cobra framework we will discuss in short how we use this feature in the raftt CLI Auto completion in raftt In the Raftt CLI we have implemented custom auto completion using the Cobra framework This feature allows users to easily and quickly input valid Kubernetes resource names when interacting with resources in the Raftt dev environment With custom auto completion users can select only valid resource names improving the overall user experience and preventing frustrating typos If you are following along our tutorial here you can try out our auto complete for yourself when you convert the frontend or recommendations services to dev mode Write raftt dev tab tab and see it list the options The tightly integrated auto completion provided us with blazing fast and effortless UX without having to worry about typos The step where we installed the completion by running the source command above is performed for you if you have installed Raftt using brew or snap Otherwise add eval raftt completion lt SHELL gt to your shell s rc file PerformanceLastly we should briefly touch the efficiency of the auto completion feature if the auto completion logic is complicated or depends on remote services consecutive completions will be slow and result in a bad user experience For example when auto completing a long list of Kubernetes resources by repeatedly pressing the tab tab combination To mitigate this issue we can cache the results of the complicated auto completion logic Caching auto complete results introduces two new problems Where are the results stored The CLI itself only runs for a second to generate the completion and does not stick around We could potentially put them on disk but that means dealing with multiple accessors at once locking etc Raftt has a daemon that it starts up and it was natural to cache the results there Out of date information If our cache is too long we might be serving incorrect information For example if the Kubernetes resources have since been deleted We settled on seconds as a reasonable duration In conclusion implementing custom auto completion for a CLI tool using Cobra can greatly improve the user experience and make the tool more efficient to use By following the steps outlined in this post you can add this feature to your own Go based CLI tool With auto completion users can more easily navigate and interact with your tool reducing errors and improving the overall experience Thank you for auto completing this post The code for the mixologist app can be found here If you are interested in how Raftt can help you be develop effectively on local or remote Kubernetes clusters check out our tutorials here |
2023-08-07 12:47:15 |
海外TECH |
DEV Community |
🪄✨Building a blog with a liking feature using React, Hanko and Novu 🔥 |
https://dev.to/novu/building-a-blog-with-a-liking-feature-using-react-hanko-and-novu-1m81
|
🪄Building a blog with a liking feature using React Hanko and Novu TL DR In this tutorial you ll learn how to build a blogging platform that let s you create and react to posts We will build a login and registration with HankoBuild the entire blog Create postsReact to posts Add in app notification to every reaction with Novu Novu Open source notification infrastructure Just a quick background about us Novu is an open source notification infrastructure We basically help to manage all the product notifications It can be In App the bell icon like you have in the Dev Community Websockets Emails SMSs and so on Let set it up Here I ll walk you through creating the project setup for the application We ll use React js for the front end and Node js for the backend server Create a folder for the web application as done below mkdir simple blogcd simple blogmkdir client server Setting up the Node js serverNavigate into the server folder and create a package json file cd server amp npm init yInstall Express Nodemon and the CORS library npm install express cors nodemonExpressJS is a fast minimalist framework that provides several features for building web applications in Node js CORS is a Node js package that allows communication between different domains and Nodemon is a Node js tool that automatically restarts the server after detecting file changes Create an index js file the entry point to the web server touch index jsSet up a Node js server using Express js The code snippet below returns a JSON object when you visit the http localhost api in your browser index jsconst express require express const cors require cors const app express const PORT app use express urlencoded extended true app use express json app use cors app get api req res gt res json message Hello world app listen PORT gt console log Server listening on PORT Configure Nodemon by adding the start command to the list of scripts in the package json file The code snippet below starts the server using Nodemon In server package json scripts test echo Error no test specified amp amp exit start nodemon index js Congratulations You can now start the server by using the command below npm start Setting up the React applicationNavigate into the client folder via your terminal and create a new React js project with Vite npm create vite latestInstall React Icons and React Router a JavaScript library that enables us to navigate between pages in a React application npm install react router dom react iconsDelete the redundant files such as the logo and the test files from the React app and update the App jsx file to display “Hello World as done below function App return lt div gt lt p gt Hello World lt p gt lt div gt export default App Copy the CSS file required for styling the project here into the src index css file Building the app user interface ️Here we ll create the user interface for the blogging application to enable users to view create and react to posts Create a components folder within the client src folder containing the Home jsx Login jsx Details jsx and NewPost jsx cd client srcmkdir componentstouch Home jsx Details jsx Login jsx NewPost jsxFrom the code snippet aboveThe Home jsx component displays all the available posts The Detail jsx component displays the details of each post such as its content the date posted and the number of reactions to the post The NewPost jsx component enables users to create a new post The Login jsx component log users into the application via Hanko Update the App jsx file to render the components using React Router import React from react import BrowserRouter as Router Route Routes from react router dom import Home from components Home import Details from components Details import Login from components Login import NewPost from components NewPost const App gt return lt Router gt lt Routes gt lt Route path element lt Home gt gt lt Route path login element lt Login gt gt lt Route path post slug element lt Details gt gt lt Route path post new element lt NewPost gt gt lt Routes gt lt Router gt export default App The Home pageThe Home page displays all the posts created within the application Copy the code below into the Home jsx file import React from react import Link from react router dom const Home gt return lt div gt lt nav className navbar gt lt Link to className logo gt lt h gt MyBlog lt h gt lt Link gt lt div style display flex alignItems center gt lt Link to post new className newPostBtn gt New Post lt Link gt lt div gt lt nav gt lt main className main gt lt h className heading gt Latest Posts lt h gt lt div className posts container gt lt Link to post details className post gt lt h className post title gt Building a chat app with React Novu and Websockets lt h gt lt Link gt lt Link to post details className post gt lt h className post title gt How to install Novu in React lt h gt lt Link gt lt div gt lt main gt lt div gt export default Home The Post Details pageThis page displays post details when a user clicks on them from the Home jsx component Copy the code below into the Details jsx file import React from react import AiTwotoneLike AiTwotoneDislike from react icons ai const Details gt return lt div gt lt header className details header gt lt h className details heading gt How to install Novu in React lt h gt lt div className post details gt lt div gt lt p className details date gt Posted on th July lt p gt lt div gt lt div className reactions group gt lt button className reactBtn gt Like lt AiTwotoneLike gt lt span style marginLeft gt lt span gt lt button gt lt button className reactBtn unlikeBtn gt Dislike lt AiTwotoneDislike gt lt span style marginLeft gt lt span gt lt button gt lt div gt lt div gt lt header gt lt main className details body gt Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry s standard dummy text ever since the s when an unknown printer took a galley of type and scrambled it to make a type specimen book It has survived not only five centuries but also the leap into electronic typesetting remaining essentially unchanged It was popularised in the s with the release of Letraset sheets containing Lorem Ipsum passages and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum lt main gt lt div gt export default Details The New Post pageThis page displays a form field that accepts the title and content of a blog post Copy the code snippet below into the NewPost jsx file import React useState from react import Link useNavigate from react router dom const NewPost gt const navigate useNavigate const title setTitle useState const content setContent useState const handleSubmit e gt e preventDefault console log title content setContent setTitle return lt div gt lt nav className navbar gt lt Link to className logo gt lt h gt MyBlog lt h gt lt Link gt lt div gt lt button className newPostBtn logOut gt Log out lt button gt lt div gt lt nav gt lt main className main gt lt h className heading gt Create new post lt h gt lt form className newPost form onSubmit handleSubmit gt lt label htmlFor title className label gt Title lt label gt lt input type text className newPost title id title name title value title required onChange e gt setTitle e target value gt lt label htmlFor content className label gt Content lt label gt lt textarea rows className newPost content value content required onChange e gt setContent e target value gt lt button className newPostBtn submitBtn type submit gt Create Post lt button gt lt form gt lt main gt lt div gt export default NewPost Are passkeys the future Hanko is an open source easy to integrate authentication solution that enables you to add various forms of authentication such as Email amp Password password less passkeys and OAuth to your software applications It is an all in one authentication solution that enables you to set up authentication in a few minutes in your web applications It also provides customisable web components which you can add to your web application to handle authentication quickly and easily In the upcoming sections you ll learn how to add Hanko to the blogging application Adding authentication easily to React apps with HankoHere you ll learn how to add authentication to your React applications using Hanko Before we begin install the Hanko package by running the code snippet below npm install teamhanko hanko elements Setting up an Hanko projectVisit the homepage and create an account Create a new organization that will manage your Hanko projects Then create a new Hanko project and add your development server as the API URL Finally save your API URL somewhere on your computer it will be used for setting up the authentication Adding Hanko to React appsCopy the code below into the Login jsx file import React useEffect useCallback useMemo from react import useNavigate from react router dom import register Hanko from teamhanko hanko elements const hankoApi lt YOUR HANKO API URL gt const Login gt const navigate useNavigate const hanko useMemo gt new Hanko hankoApi useEffect gt register hankoApi catch error gt console log error return lt div className login container gt lt hanko auth gt lt div gt export default Login The code snippet displays the Hanko authentication component and enables users to sign up or sign in directly via Hanko Add the code snippet below within the Login jsx component generates random string as IDconst generateUserID gt Math random toString substring executes after a user logs inconst redirectAfterLogin useCallback gt localStorage setItem loggedIn true if localStorage getItem u id localStorage setItem u id generateUserID navigate navigate triggered after a successful sign inuseEffect gt hanko onAuthFlowCompleted gt redirectAfterLogin hanko redirectAfterLogin From the code snippet above when a user signs into the application the u id value is set to the local storage to identify each user when they request the Node js server PS I m using local storage because this is a small application If you are using Hanko in a production environment you may need to check out the backend guide Congratulations You ve successfully added Hanko to a React application In the upcoming section we ll add all the necessary features to the blogging application Communicating with the Node js serverIn this section you ll learn how to communicate with the Node js server by retrieving and creating posts within the application Before we begin create a utils folder containing a util js file within the React app cd clientmkdir utilscd utilstouch util js Displaying the blog postsCreate a posts array within the index js file on the server let posts u id a post id title Building a chat app with NextJS and Novu slug building a chat app with nextjs and novu content Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry s standard dummy text ever since the s when an unknown printer took a galley of type and scrambled it to make a type specimen book It has survived not only five centuries but also the leap into electronic typesetting remaining essentially unchanged published date likes u id u id ancsd dislikes user id u id u id b post id title How to create an ecommerce app with NextJS and Novu slug how to create an ecommerce app with nextjs and novu content Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry s standard dummy text ever since the s when an unknown printer took a galley of type and scrambled it to make a type specimen book It has survived not only five centuries but also the leap into electronic typesetting remaining essentially unchanged It was popularised in the s with the release of Letraset sheets published date likes u id dislikes user id Add another endpoint that returns the posts in JSON format app get posts req res gt res json posts Next create a function within the utils util js file that sends a request to the endpoint from the React app export const fetchAllPosts setLoading setPosts gt fetch http localhost posts then res gt res json then data gt setLoading false setPosts data posts catch err gt console error err Finally execute the function when the Home component mounts import React useCallback useEffect useState from react import Link from react router dom import fetchAllPosts from utils util const Home gt const loggedIn setLoggedIn useState false const posts setPosts useState const loading setLoading useState true const fetchPosts useCallback gt fetchAllPosts setLoading setPosts useEffect gt if localStorage getItem loggedIn setLoggedIn true fetchPosts fetchPosts if loading return lt p gt Loading lt p gt return lt div gt lt nav className navbar gt lt Link to className logo gt lt h gt MyBlog lt h gt lt Link gt lt div style display flex alignItems center gt loggedIn lt Link to post new className newPostBtn gt New Post lt Link gt lt Link to login className newPostBtn gt Log in lt Link gt lt div gt lt nav gt lt main className main gt lt h className heading gt Latest Posts lt h gt lt div className posts container gt posts map post gt lt Link to post post slug className post key post post id gt lt h className post title gt post title lt h gt lt Link gt lt div gt lt main gt lt div gt export default Home The code snippet above fetches all the posts from the server when the page mounts and displays them within the React app It also checks if the user is authenticated to display either the Login or New Post buttons Retrieving the posts detailsHere you need to fetch a post s details when you click on it from the Home page To do this you need to filter the array of posts via its slug property Create another POST route that filters the posts array by a post s slug and returns the entire post object app post post details req res gt const slug req body const result posts filter post gt post slug slug res json post result Add a function within the utils util js file that sends a request to the post details endpoint and returns the post object export const fetchPostContent slug setLoading setPost gt fetch http localhost post details method POST body JSON stringify slug slug headers Accept application json Content Type application json then res gt res json res then data gt setLoading false setPost data post catch err gt console error err Import the function into the Details jsx component import useParams from react router dom import fetchPostContent from utils util const Details gt const slug useParams const post setPost useState const loading setLoading useState true const fetchPostDetails useCallback gt fetchPostContent slug setLoading setPost slug useEffect gt fetchPostDetails fetchPostDetails if loading return lt p gt Loading lt p gt return lt div gt lt div gt Update the UI elements to display the post details accordingly return lt div gt lt header className details header gt lt h className details heading gt post title lt h gt lt div className post details gt lt div gt lt p className details date gt Posted on post published date lt p gt lt div gt lt div className reactions group gt lt button className reactBtn onClick gt reactToPost slug like gt Like lt AiTwotoneLike gt lt span style marginLeft gt post likes length lt span gt lt button gt lt button className reactBtn unlikeBtn onClick gt reactToPost slug dislike gt Dislike lt AiTwotoneDislike gt lt span style marginLeft gt post dislikes length lt span gt lt button gt lt div gt lt div gt lt header gt lt main className details body gt post content lt main gt lt div gt Reacting to blog postsFirst you need to create an endpoint on the Node js server that updates the number of likes and dislikes property of a post when a user clicks the button from the user interface app post post react async req res gt const slug type u id req body like post functionality for let i i lt posts length i if posts i slug slug amp amp type like validates the post reaction const validateLike posts i likes filter likes gt likes u id u id if validateLike length posts i likes push u id res json message You ve just liked a post dislike post functionality if posts i slug slug amp amp type dislike validates the post reaction const validateDislike posts i dislikes filter dislikes gt dislikes u id u id if validateDislike length posts i dislikes push u id const sendNotifcation await notify liked u id res json message You ve just disliked a post The code snippet above handles the user s reaction to posts It filters the posts array via the post s slug and validates the post reaction to ensure that the user has not reacted to the post before updating the property accordingly Create a function within the utils util js file that sends a request to the endpoint when a user clicks the Like and Dislike buttons export const postReaction slug type gt fetch http localhost post react method POST body JSON stringify slug type u id localStorage getItem u id headers Accept application json Content Type application json then res gt res json res then data gt alert data message catch err gt console error err Execute the function when a user clicks on the buttons import postReaction from utils util const Details gt calls the function const reactToPost slug type gt postReaction slug type return lt div gt lt header className details header gt lt h className details heading gt post title lt h gt lt div className post details gt lt div gt lt p className details date gt Posted on post published date lt p gt lt div gt lt div className reactions group gt like button lt button className reactBtn onClick gt reactToPost slug like gt Like lt AiTwotoneLike gt lt span style marginLeft gt post likes length lt span gt lt button gt Dislike button lt button className reactBtn unlikeBtn onClick gt reactToPost slug dislike gt Dislike lt AiTwotoneDislike gt lt span style marginLeft gt post dislikes length lt span gt lt button gt lt div gt lt div gt lt header gt lt main className details body gt post content lt main gt lt div gt export default Details Creating new postsCreate an endpoint that adds a new post to the posts array creates post slugconst createSlug text id gt let slug text trim toLowerCase replace w s g slug slug replace s g return slug id generates a random string as IDconst generateID gt Math random toString substring app post post add req res gt const u id title content date req body const postObject u id post id generateID title slug createSlug title generateID content published date date likes dislikes posts unshift postObject res json message Post added successfully The code snippet above creates a new post object and adds the newly created post to the posts array Add a function that sends a request to the endpoint within the utils util js file export const addNewPost u id title content date navigate gt fetch http localhost post add method POST body JSON stringify u id title content date headers Accept application json Content Type application json then res gt res json res then data gt alert data message navigate catch err gt console error err alert Encountered an error Execute the function when the user submits the form within the NewPost jsx file formates the date to a readable stringconst formatDate gt const date new Date const day String date getDate padStart const month String date getMonth padStart const year date getFullYear return day month year executes on form submitconst handleSubmit e gt e preventDefault adds the new post addNewPost localStorage getItem u id title content formatDate navigate setContent setTitle Sending in app notifications with Novu Here we need to notify the post authors when someone reacts to their posts To do this we ll use Novu an open source notification infrastructure that enables you to send in app SMS chat push and e mail notifications from a single dashboard Creating a Novu projectNavigate into the client folder and create a Novu project by running the code below cd clientnpx novu initSelect your application name and sign in to your Novu dashboard The code snippet below contains the steps you should follow after running npx novu init Now let s setup your account and send your first notification What is your application name Forum App Now lets setup your environment How would you like to proceed Create a free cloud account Recommended Create your account with Sign in with GitHub I accept the Terms and Conditions and have read the Privacy Policy YesCreated your account successfully Visit the demo page copy your subscriber ID from the page and click the Skip Tutorial button Create a notification template with a workflow as shown below Novu Digest allows you to control how you send notifications in your app It collects multiple trigger events schedules them or sends them as a single message Update the In App notification step to send this message to the post author when someone reacts to their post You have a new reaction on your post Adding Novu notification bell to a React appNovu in app notification uses a notification bell to send alerts to users Here you ll learn how to add it to your React applications Install the Novu Notification package npm install novu notification centerCreate a Novu jsx file within the components folder and copy the below into the file import React from react import NovuProvider PopoverNotificationCenter NotificationBell from novu notification center import useNavigate from react router dom function Novu const navigate useNavigate const onNotificationClick notification gt navigate notification cta data url return lt gt lt NovuProvider subscriberId lt YOUR SUBSCRIBER ID gt applicationIdentifier lt YOUR APP ID gt gt lt PopoverNotificationCenter onNotificationClick onNotificationClick colorScheme light gt unseenCount gt lt NotificationBell unseenCount unseenCount gt lt PopoverNotificationCenter gt lt NovuProvider gt lt gt export default Novu The code snippet above enables us to add Novu s notification bell icon to the application With this you can view all the notifications within the app Select Settings on your Novu Admin Panel to copy your App ID and replace the subscriber s ID placeholder with yours Import the Novu jsx component into the Home jsx component const Home gt return lt div gt lt nav className navbar gt lt Link to className logo gt lt h gt MyBlog lt h gt lt Link gt lt div style display flex alignItems center gt Novu component lt Novu gt loggedIn lt Link to post new className newPostBtn gt New Post lt Link gt lt Link to login className newPostBtn gt Log in lt Link gt lt div gt lt nav gt other components lt div gt Configuring Novu on a Node js serverInstall the Novu SDK for Node js into the server folder npm install novu nodeImport Novu from the package and create an instance using your API Key const Novu require novu node const novu new Novu lt YOUR API KEY gt Create a function within the index js file that sends notification to the post author via Novu const notify async reaction userID gt await novu subscribers identify userID firstName inAppSubscriber const response await novu trigger notify to subscriberId lt YOUR SUBSCRIBER ID gt payload reaction return response data data Execute the function when a user reacts to a post app post post react async req res gt const slug type u id req body for let i i lt posts length i if posts i slug slug amp amp type like const validateLike posts i likes filter likes gt likes u id u id if validateLike length posts i likes push u id Triggers Novu const sendNotifcation await notify like u id if sendNotifcation acknowledged res json message You ve just liked a post if posts i slug slug amp amp type dislike const validateDislike posts i dislikes filter dislikes gt dislikes u id u id if validateDislike length posts i dislikes push u id Triggers Novu const sendNotifcation await notify dislike u id if sendNotifcation acknowledged res json message You ve just disliked a post Congratulations You ve completed the application ConclusionSo far you ve learnt how to authenticate users with Hanko communicate between a React and Node js app and send in app notifications using the Novu Digest Novu enables you to create a rich notification system in your applications thereby providing a great user experience for your users You should also try out Hanko it is minimal and easy to integrate The source code for this tutorial is available here Thank you for reading |
2023-08-07 12:13:42 |
海外TECH |
DEV Community |
How to Create a Sticky NavBar using Tailwind CSS |
https://dev.to/bobbyiliev/how-to-create-a-sticky-navbar-using-tailwind-css-1587
|
How to Create a Sticky NavBar using Tailwind CSS IntroductionWhen building a modern responsive website navigation plays a crucial role in user experience A sticky or affix navigation bar remains visible at the top of the screen as users scroll making it easy for them to access the main menu items without having to scroll back to the top Tailwind CSS a popular utility first CSS framework makes it simple to create elegant functional sticky navigation bars In this tutorial we ll walk you through the process of creating a sticky navigation bar using Tailwind CSS and showcase some stylish designs to inspire your project Step Setting Up the ProjectBefore we start make sure you have Tailwind CSS installed in your project You can either use the CLI include it from a CDN or set up a custom build Visit the official Tailwind CSS documentation to learn how to set up Tailwind CSS for your specific project Step Creating the Basic NavBarFirst let s create a simple navigation bar using Tailwind CSS Add the following HTML code to your project lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta name viewport content width device width initial scale gt lt link href dist tailwind min css rel stylesheet gt lt title gt Sticky NavBar using Tailwind CSS lt title gt lt head gt lt body class bg gray gt lt header class bg white gt lt nav class container mx auto px py gt lt div class flex justify between items center gt lt a href class text xl font bold text gray gt MyWebsite lt a gt lt div class flex space x gt lt a href class text gray gt Home lt a gt lt a href class text gray gt About lt a gt lt a href class text gray gt Services lt a gt lt a href class text gray gt Contact lt a gt lt div gt lt div gt lt nav gt lt header gt lt Add your page content here gt lt body gt lt html gt This code sets up a basic navigation bar with a container logo and menu links Step Making the NavBar StickyTo make the navigation bar sticky we need to add the fixed top and w full classes to the lt header gt element This will fix the header at the top of the viewport and span the full width of the screen Update your lt header gt tag as follows lt header class bg white fixed top w full gt Now when you scroll down the page the navigation bar will remain at the top Step Adding a ShadowTo create a subtle separation between the sticky navigation bar and the page content add a shadow using the shadow md class lt header class bg white fixed top w full shadow md gt Step Design InspirationsNow that you ve created a basic sticky navigation bar using Tailwind CSS you can customize its design by applying various utility classes or creating your own Here are a few design ideas to inspire you Transparent background with a color change on scroll Add a transparent background to the navigation bar and change the background color when the user scrolls down creating a smooth transition effect You can achieve this by using JavaScript to toggle a class when the user scrolls Hover effect on menu items Enhance user experience by adding a hover effect to the menu items Use the hover prefix to change the text color or background color of the menu items when users hover over them For example lt a href class text gray hover text blue gt Home lt a gt Add a call to action button Encourage users to take a specific action such as signing up or contacting you by adding a CTA button to the navigation bar Use the bg text and rounded classes to style the button lt a href class bg blue text white px py rounded md gt Sign Up lt a gt Responsive design with a hamburger menu For mobile devices you can create a responsive design by hiding the menu items and displaying a hamburger menu instead Use Tailwind CSS s responsive classes e g lg hidden and lg flex and JavaScript to toggle the mobile menu Add a search bar Enhance your sticky navigation bar by integrating a search bar Use the border rounded and focus classes to style the input field and search button lt div class flex items center space x gt lt input type search placeholder Search class border border gray rounded md px py focus outline none focus border blue gt lt button class bg blue text white px py rounded md gt Search lt button gt lt div gt Complete exampleHere is the complete HTML code for a basic sticky navigation bar with some additional design elements including hover effects a CTA button and a search bar lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta name viewport content width device width initial scale gt lt link href dist tailwind min css rel stylesheet gt lt title gt Sticky NavBar using Tailwind CSS lt title gt lt head gt lt body class bg gray gt lt header class bg white fixed top w full shadow md gt lt nav class container mx auto px py gt lt div class flex justify between items center gt lt a href class text xl font bold text gray gt MyWebsite lt a gt lt div class hidden md flex items center space x gt lt a href class text gray hover text blue gt Home lt a gt lt a href class text gray hover text blue gt About lt a gt lt a href class text gray hover text blue gt Services lt a gt lt a href class text gray hover text blue gt Contact lt a gt lt a href class bg blue text white px py rounded md gt Sign Up lt a gt lt div gt lt div class md hidden flex items center gt lt button class text gray focus outline none gt lt Add a hamburger menu icon here gt lt svg class w h fill none stroke currentColor viewBox xmlns gt lt path stroke linecap round stroke linejoin round stroke width d M hM hM h gt lt path gt lt svg gt lt button gt lt div gt lt div gt lt div class mt gt lt div class flex items center space x gt lt input type search placeholder Search class border border gray rounded md px py focus outline none focus border blue w full gt lt button class bg blue text white px py rounded md gt Search lt button gt lt div gt lt div gt lt nav gt lt header gt lt Add your page content here gt lt body gt lt html gt This example includes hover effects for menu items a CTA button and a search bar You can further customize the design by applying different utility classes or creating your own Remember to test your designs on various devices and screen sizes to ensure a seamless experience for all users ConclusionIn this tutorial we demonstrated how to create a sticky navigation bar using Tailwind CSS and provided some design ideas to help you customize the look and feel of your NavBar By implementing a sticky navigation bar on your website you can improve user experience and ensure that essential menu items are always easily accessible To make the design process even more efficient and enjoyable you can use the Tails Tailwind CSS page builder which offers a comprehensive library of pre built UI components all created with Tailwind CSS This intuitive user friendly page builder allows you to effortlessly create and customize your website designs using a visual interface without having to write a single line of code Remember to test your designs on various devices and screen sizes to ensure a seamless experience for all users |
2023-08-07 12:01:11 |
Apple |
AppleInsider - Frontpage News |
Hyper fields HyperDrive Next collection of a dock, SSD enclosure, and hubs |
https://appleinsider.com/articles/23/08/07/hyper-fields-hyperdrive-next-collection-of-a-dock-ssd-enclosure-and-hubs?utm_medium=rss
|
Hyper fields HyperDrive Next collection of a dock SSD enclosure and hubsHyper has launched its HyperDrive Next range of products which aims to Go Beyond by combining high speed connectivity with sustainability Launched on Monday the HyperDrive Next lineup is said by the company as a testament to our commitment to pushing boundaries by pairing creativity with innovation and environmental responsibility The range consists of four offerings namely a selection of USB C hubs a USB NVMe SSD Enclosure a USB C Dock with dual monitor support aimed at M and m Macs and the USB C Business Class Dock Read more |
2023-08-07 12:51:01 |
海外TECH |
Engadget |
The best laptops for college students |
https://www.engadget.com/best-laptops-for-students-130054631.html?src=rss
|
The best laptops for college studentsWhether you re heading to a physical campus taking classes online or a mix of both a laptop is sure to be the control center for your studies Getting a new machine for the back to school season can better help you stay on top of your schedule and handle your furious multitasking with dozens of tabs devoted to research while you write your essays We re still dealing with the shadow of the pandemic and inflation continues to drive up prices so everything might feel more expensive than ever The good news is laptops are also lasting longer than ever and the options on our list should serve you well for years to come That is as long as you pick one from a reliable company and with the right specs To help you as you shop we put together this collection of things to look out for as well as a list of the best laptops for college What to expectApple has completed its transition to its own Silicon so you ll no longer have the option of Intel powered Macs Nor should you want to really since the M and M MacBooks have proven to be reliable speedy and long lasting With a new generation of chips likely on the horizon older models with M processors should get cheaper while still offering excellent performance This means you ll have more options to consider without having to stretch your budget Meanwhile new PCs keep getting announced with the latest models typically powered by th gen Intel processors or the latest AMD Ryzen chips Though the shift to ARM based systems has been successful for Apple the PC industry is still struggling to keep up and Windows on ARM is basically dead in the water Don t waste your time or money on an ARM based PC they re hard to find nowadays anyway Speaking of laptops with top of the line specs can cost you around to these days For most college students though a midrange machine to use primarily for writing papers and web browsing might be enough Depending on your field of study you could get by with an Intel Core i processor or equivalent with at least GB of RAM If you need to run specialized software for design or programming consider upgrading to a beefier system with more processing power and memory On the other hand if you do most of your coursework online or in a browser getting a Chromebook could save you a lot of money You ll also want to pay attention to a device s weight especially if you plan on lugging your laptop to classes in person There are a lot of premium ultraportables in the inch category with chips like Intel s Core i or i that cost around If these light laptops are too expensive you ll still have respectable options in the to price range but they might be heavier and use older slower processors I ve included our recommendations for the best budget laptops in this college centric guide but we also have more affordable top picks that you can check out as well See Also Best Laptops for Best Gaming LaptopsBest in Laptops for Best ChromebooksBest Cheap Windows Laptops for With some laptop makers deciding to get rid of headphone jacks it s important to check specs lists when you re shopping for newer machines If you don t have wireless headphones or use equipment that plugs into the mm jack you ll want to steer clear of devices like Dell s XPS Plus Finally while most laptops in offer WiFi or E and Bluetooth or later you may not have one of the compatible routers or other devices that would enable those faster connections yet Chances are your campus WiFi might still be stuck on an older setup too so it s not crucial that you get a system with the latest standards yet Of course it doesn t hurt to get a laptop that s future proof but just know that of all the things to look out for WiFi E shouldn t be a dealbreaker in your decision making process The best laptops for college studentsBest Apple MacBook AirIt s hard to beat Apple s MacBook Air if you want a powerful machine for college that won t weigh you down You actually have a few good options this year ーthe new inch M powered MacBook Air last year s inch model and the MacBook Air M The M laptop earned a score of from us for its impressive performance gorgeous inch Liquid Retina display and its refined design that s even thinner than the M version that came before it Our biggest gripe with this laptop is its price tag ーthe M MacBook Air will set you back more than the M so you re looking at spending at least if you want the latest and greatest from Apple Even though it s older the Apple M MacBook Air is a great laptop outperforming many PCs while maintaining a fanless design It s also cheaper starting at You ll still get a great keyboard and long battery life along with a nice Retina display Of course it uses a p webcam while newer models have sharper p cameras in They re housed in notches because Apple shaved down the bezels for a more modern look so if that bothers you it might be best to grab an M model while you can You ll have to live with having just two USB C charging ports since only the M machines have the additional MagSafe socket but if you re already living a largely wireless life and don t mind a not so great camera you might find the M MacBook Air is a solid deal Read our full review of the Apple MacBook Air MBest Windows Dell XPS PlusThe best PC has long been Dell s well rounded XPS series and I still recommend it to anyone that doesn t want a Mac Yes the XPS Plus lacks a headphone jack and some of its buttons are hard to see and use But the XPS is a well rounded machine and reliable workhorse that will get you through classes and late night writing sessions without breaking a sweat Like its predecessors the XPS Plus offers a lovely OLED screen with impressively thin bezels and packs a roomy comfortable keyboard It also features a new minimalist design that looks more modern and offers a performance boost over the standard model The row of capacitive keys at the top in lieu of traditional function keys may irk some as they can be hard to see outdoors but if you become familiar with where they are you might not need to see where they are to find the right ones The invisible trackpad can also be tricky since its boundaries aren t clear If you don t like the changes Dell has made to the XPS or if you definitely need a headphone jack the older generations are still solid options There s also the Samsung Galaxy Book series which feature beautiful OLED screens and sharper webcams in thin and light frames I also like Microsoft s Surface Laptops and the most recent edition offers great performance and battery life albeit in an outdated design Read our full review of the Dell XPS Plus laptopBest for gaming Razer Blade Just because your laptop might primarily be for coursework doesn t mean you can t use it for fun too Those looking to game on their machines should prioritize responsive screens and ample ports for their favorite accessories that can best help them defeat their virtual enemies If you re considering a gaming first machine that you can use for school check out our guide to buying a gaming laptop It covers details about different CPUs and GPUs minimum specs and more Our favorite gaming laptop is the Razer Blade which has an Intel Core i processor and an NVIDIA RTX graphics for At that price point it s the most expensive item on this list but you also get a inch quad HD screen that refreshes at Hz Different configurations are available depending on your preference including Full HD Hz and K Hz versions The Blade series is also one of the most polished gaming laptops around and Razer consistently updates it with the latest processors graphics and other hardware advancements If you really want to go all out you could consider the new Razer Blade that has NVIDIA s RTX or GPUs Students and gamers looking for something cheaper and more portable should consider the ASUS ROG Zephyrus G which was our favorite model in The main reason it got bumped down a notch is because the refresh is almost more expensive It s still a solid gaming laptop though with an excellent display roomy trackpad and plenty of ports in spite of its thin profile Read our full review of the Razer Blade gaming laptopBest Chromebook Lenovo IdeaPad Flex i ChromebookIf you can do most of your schoolwork through web based apps a Chromebook is worth considering for your college laptop Sure they don t generally look fancy nor have high end specs But they re often more affordable and have longer battery life Our favorite Chromebook is Lenovo s IdeaPad Flex i Chromebook which Engadget s resident Chrome OS aficionado Nathan Ingraham described as hitting “the sweet spot for a lot of Chromebook buyers This laptop nails the basics with a inch Full HD touchscreen that s bright and sharp an excellent backlit keyboard and an th generation Intel Core i processor The GB of RAM and GB of storage may sound meager but it s more than enough for a Chromebook especially at this price It s also nice to see USB A and USB C ports a microSD card slot and eight hour battery life Weighing pounds and measuring inches thick the Flex i is not the lightest or slimmest laptop around but hey at least your wallet won t also feel light as feathers after buying this Notably the Flex i is supposed to receive software and security updates until June of so it will last you for years to come That s nice to see considering this laptop has been out for more than a year now and we re expecting Lenovo to release a replacement soon When that happens or if another manufacturer launches a comparable option we will update this list The Lenovo Flex i is no longer available directly from Lenovo but you can commonly find it on Amazon for about as of this writing it is selling for about That s an outstanding value Read our full review of the Lenovo Flex Chromebook Best budget HP Pavilion Aero If you re looking for a sturdy student laptop under your best bet is the HP Pavilion Aero Yes it s almost two years old but it s still one of the best cheap laptops for college students available now For an affordable price you ll get a Full HD screen with a aspect ratio and surprisingly thin bezels as well as a comfortable keyboard and spacious touchpad Importantly the Aero provides relatively powerful components compared to others in this price range with an AMD Ryzen series processor and Radeon graphics Plus it has a generous array of ports and enough hours of battery life to last you a full day and then some Read our full review of the HP Pavilion Aero laptopBest Convertible Microsoft Surface Pro For those who need their laptops to occasionally double as tablets the Surface Pro series is a no brainer Compared to notebooks or in laptops with rotating hinges tablets with kickstands are often much slimmer and lighter The Surface Pro is the most recent model and it features Microsoft s sleek design with a thinner profile and minimal bezels The Pro also has a Hz display that makes scrolling long documents or spreadsheets feel much faster and you can drop the refresh rate down to Hz if you want to conserve battery life Just make sure you get an Intel processor rather than an ARM based configuration since app compatibility might be an issue on the latter You don t want to be the only one in class who can t install the obscure app that your professor wants everyone to use do you We also like Microsoft s Type Covers and the Surface Pens though it s worth noting that they ll have to pay extra for both if you want them Unless you re bent on sticking to Apple s ecosystem in which case an iPad Pro would suit you best the Surface Pro is arguably the best convertible laptop around Read our full review of the Microsoft Surface Pro This article originally appeared on Engadget at |
2023-08-07 12:20:38 |
海外TECH |
Engadget |
WhatsApp's latest feature lets you jump in and out of group voice chats |
https://www.engadget.com/whatsapps-latest-feature-lets-you-jump-in-and-out-of-group-voice-chats-121045597.html?src=rss
|
WhatsApp x s latest feature lets you jump in and out of group voice chatsLast year WhatsApp released a series of new updates to make sending voice messages an overall better experience and now it s bringing the whole group in on it The messaging app has released a beta version of voice chats ーa feature that creates an ongoing group audio conversation reports WABetaInfo The first sign of voice chats came earlier this year under the name audio chats but didn t provide much other info than its mere existence WABetaInfoThough it sounds similar this update isn t exactly the same as starting a group call giving a much more Discord like feel than when you typically give your friends a ring Anyone with the update should see a waveform symbol in the upper right corner of their group chat Pressing the icon starts a group voice chat and will say voice chat opened with a microphone to its left and a red X to its right Everyone else in the group will receive a push notification the same as any message instead of their phone ringing They will see a banner at the top of the chat box letting them know how many people are chatting now and giving them the option to connect Voice chats are protected by end to end encryption just like any other messages sent and also shut off if no one has been active in it for an hour WhatsApp voice chat only appears to be available in beta for Android users right now but will allegedly appear for more people in the coming days This article originally appeared on Engadget at |
2023-08-07 12:10:45 |
ニュース |
BBC News - Home |
England 0-0 Nigeria: Lionesses win penalty shootout to reach quarter-finals |
https://www.bbc.co.uk/sport/football/66420237?at_medium=RSS&at_campaign=KARANGA
|
England Nigeria Lionesses win penalty shootout to reach quarter finalsEngland survive Lauren James sending off and a gruelling Nigeria onslaught to reach the quarter finals of the Women s World Cup |
2023-08-07 12:01:16 |
ニュース |
BBC News - Home |
All scouts leaving South Korea camp as storm looms |
https://www.bbc.co.uk/news/uk-66425793?at_medium=RSS&at_campaign=KARANGA
|
korea |
2023-08-07 12:18:22 |
ニュース |
BBC News - Home |
Niger coup: Junta shuts airspace citing military intervention threat |
https://www.bbc.co.uk/news/world-africa-66424858?at_medium=RSS&at_campaign=KARANGA
|
action |
2023-08-07 12:26:22 |
ニュース |
BBC News - Home |
GB News: Politicians' shows under scrutiny in new Ofcom investigations |
https://www.bbc.co.uk/news/entertainment-arts-66426544?at_medium=RSS&at_campaign=KARANGA
|
daubney |
2023-08-07 12:17:51 |
ニュース |
BBC News - Home |
Matty Healy: The 1975 threatened with legal action after Malaysia festival cancellation |
https://www.bbc.co.uk/news/world-asia-66429339?at_medium=RSS&at_campaign=KARANGA
|
action |
2023-08-07 12:10:52 |
ニュース |
BBC News - Home |
Lauren James: England star lost her emotions for red card, says Sarina Wiegman |
https://www.bbc.co.uk/sport/football/66427469?at_medium=RSS&at_campaign=KARANGA
|
Lauren James England star lost her emotions for red card says Sarina WiegmanLauren James in a split second lost her emotions says boss Sarina Wiegman as England beat Nigeria on penalties in the Women s World Cup |
2023-08-07 12:45:04 |
ニュース |
BBC News - Home |
Australia 2-0 Denmark: Women's World Cup co-hosts reach quarter-finals |
https://www.bbc.co.uk/sport/football/66420244?at_medium=RSS&at_campaign=KARANGA
|
sydney |
2023-08-07 12:38:58 |
コメント
コメントを投稿