How to Protect URLs from SSRF Threats in Java

Server-side request forgery (SSRF) attacks are yet another form of cyber-crime, and they are designed to specifically target a server by sending back-end requests from vulnerable web applications. These attacks can threaten not only servers, but other connected confidential information such as cloud services in AWS, Azure, and OpenStack as well. They can be especially challenging to battle since they are generally used to target internal systems protected by firewalls that are inaccessible from the external network; by directing these strikes, the attacker has the potential to gain full or partial control of the requests sent by a web application.

There are multiple approaches that the malicious user may take in a typical SSRF attack; a frequently seen example is by inducing the server to create a connection back to itself or external third-party services. From here, the attacker can seize control of the third-party service URL to which the web application makes a request. Other examples include making requests to internal resources, running port scans on internal IPs, and more. These attacks exploit relationships that your server has built, inciting trust only to strike the vulnerable application and carry out their own agenda.

You Might Not Need That Block

As I was perusing the WordPress plugin directory this morning, I noticed a new block plugin, which is always one of the highlights of my week. It was a simple pricing block. Of course, I installed it and began playing around with its features. It was a version-1.0 product, so I was not going to fault it for not exceeding any expectations I might have had.

I have little doubt the plugin will meet many users’ needs. However, it did not bring much to the table that users could not already do with stock WordPress. And, as the block system continues to mature with more block options, end-users will gain more design control over every aspect of the existing core blocks.

This is not a knock at this particular plugin. I see less and less need for many third-party blocks the more I browse and test them. With WordPress’s base blocks and a decent theme, many custom solutions are possible via patterns.

To test the plugin’s block, I added it to a Columns block and duplicated it a couple of times to create pricing columns.

Pricing Block from a plugin inserted into columns.

The structure of an individual pricing block is straightforward. It contains the equivalent of the following core blocks:

  • Group
  • Heading
  • Heading/Paragraph
  • Heading/Paragraph
  • Paragraph
  • Button(s)
  • Separator
  • List

Since I had the structure, I tried recreating it while using the Twenty Twenty-One theme. I kept everything nearly the same other than a couple of font sizes and colors.

Pricing columns pattern as shown from the Twenty Twenty-One theme.

The result was not particularly impressive, but it was mostly on par with what the plugin was doing. The biggest letdown with Twenty Twenty-One is that there are no vertical spacing controls to tighten up some of the text. This is more of a limitation of WordPress than the theme. Plus, margin and padding controls are coming.

Aside from one-click insertion into the content canvas, the benefits the Pricing Block plugin brings are rounded borders, box shadows, and list icons. However, these items would fit more into a site’s design if they were controlled by the theme.

Knowing that the Eksell theme solved the vertical alignment issue with a custom block style, I decided to try it. Again, I mostly stuck with the same structure.

Pricing columns using the Eksell WordPress theme in the block editor.

Much better. However, Eksell is such a beautifully designed theme that it will upgrade the appearance of nearly anything. It almost isn’t fair.

Kicking things up a notch, I gave the pattern an overhaul. I moved some things around, changed a few colors, and tried to have a little fun with it.

Alternate design of pricing columns with the Eksell theme. Added heading background.

The noteworthy thing here is that I had far more control over the placement and design — within the current WordPress limitations. This was not possible with the plugin’s block.

There are more robust pricing blocks. This is not a comparison of all the available options out there. However, many blocks share these problems. Often, what they need to do is take advantage of WordPress’s “inner blocks” system and nest core blocks, which provides access to existing design options.

Wanting to take this experiment just a bit further, I activated a development version of the Gutenberg plugin and a block-based theme I have been tinkering with. With the right tools in hand, I had control over spacing, borders, typography, and far more — features that users will have in the coming months.

Custom pricing columns with a custom-built WordPress theme and full-site editing.

I like it, but I would also like to see professional designers take over from here. I want to see various pricing columns/tables available as patterns in themes and in the upcoming block directory.

The next level of pricing columns would be integrating with plugins like WooCommerce, Easy Digital Downloads, and other eCommerce solutions. For example, users could insert a product’s price or buy-now button into a pre-built pattern inserted into the editor canvas. That way, the data stays updated.

However, this is not specifically about pricing columns. It is about the blocks ecosystem altogether. Nearly every time I see a testimonial block, for example, I just see it as another pattern that could be registered.

For end-users, the quick solution will often be to activate an extra plugin. This requires more resources in the editor and, usually, the front end. It also ties them to another third-party tool, one which they may not necessarily need.

Ultimately, most webpage sections can be broken down to the individual blocks that exist in WordPress. They simply need to be arranged in a specific order and grouped together. Our community of theme authors can start providing these solutions by doing the legwork of this grouping and register them as patterns.

The most useful blocks do something that WordPress is incapable of doing alone or adding elements that do not exist.

Should DevTools teach the CSS cascade?

Stefan Judis, two days before I mouthed off about using (X, X, X, X) for talking about specificity, has a great blog post not only using that format, but advocating that browser DevTools should show us that value by selectors.

I think that the above additions could help to educate developers about CSS tremendously. The only downside I can think of is that additional information might overwhelm developers, but I would take that risk in favor of more people learning CSS properly.

I’d be for it. The crossed-off UI for the “losing” selectors is attempting to teach this, but without actually teaching it. I wouldn’t be that worried about the information being overwhelming. I think if they are considerate about the design, it can be done tastefully. DevTools is a very information-dense place anyway.

Direct Link to ArticlePermalink


The post Should DevTools teach the CSS cascade? appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

BlueJeans Review

BlueJeans is a video conference call service made by Verizon.

In today’s digitized world, just about every type of business and organization uses video conference calls to connect people for goal discussions, brainstorming, project management, and more.

BlueJeans is one of the best for audio quality, thanks to being powered by Dolby Voice, a pioneer of global audio solutions.

In addition to taking the cake in the audio realm, BlueJeans has an array of other solutions to make sure your team can meet remotely, reliably.

This guide looks at the service’s features that affect your calls and productivity, considering them against some of the best conference call services, to help you find your best option.

BlueJeans Pros and Cons

Pros

  • Easy-to-understand interface
  • Simple screen sharing
  • Desk phone support
  • Video and audio quality
  • Affordable pricing

Cons

  • No in-app playback
  • No waiting room
  • Mobile meetings require app
  • Large download size
Compare The Best Conference Call Services
We reviewed dozens of conference call service providers and narrowed them down to the best options.
See Top Picks

How BlueJeans Compares to Top Conference Call Services

We’ve all been on a conference call with muffled voices or broken-up audio. Needless to say, it’s challenging to host or participate when you can’t accurately hear everyone.

That’s why reliable audio quality is such an important aspect of a conference call service.

BlueJeans is my top pick for audio quality. With Dolby Voice audio, everyone on the call gets natural, clear sound, ensuring that not a single point gets missed.

Still, there are other conference call services, like RingCentral and GoToMeeting, that might be more well-rounded options for your team.

BlueJeans Participant Numbers

A key consideration as you decide on a conference call service to use is how many participants your service can support.

If you’re just hosting a small meeting with five or six participants, you’d be able to use just about any service. However, when you get into larger groups of 20+ participants, it’s important to choose a conference call service that allows that many people—and still offers quality audio and video.

With the introductory BlueJeans plan, you can host up to 100 participants. And that comes along with unlimited meeting times, so you can meet for as long as you need to.

The next plan gives you up to 125 participants with an optional add-on, or you can get up to 200 participants with BlueJeans Enterprise.

No matter how many people you add to your meetings, your audio and video quality won’t suffer, assuming that everyone’s technology meets the minimum requirements for the service.

With that said, it’s important to note that some services give you meetings with 100 participants or more for free.

Zoom is one of them, offering 100 participants but capping calls at 40 minutes. RingCentral allows unlimited participants with a cap on 500 minutes total of shared video.

But, if avoiding restrictions is more your style, a paid BlueJeans Standard plan might be the way to go.

BlueJeans Video Conferencing

The primary offering of BlueJeans is video conferencing. It’s to be expected that the service has a lot to offer businesses that are turning to video conferencing for a more remote-friendly atmosphere.

And BlueJeans does know its stuff in terms of video conferencing. It seems to hit just about every feature someone would need in a video conference, from an enhanced gallery view of up to 25 participants at a time to its universal accessibility with real-time closed captioning and screen readers.

Attendees who may not have access to a mobile phone or computer can even dial in from their desk phone, with or without video, ensuring that anyone can hop on without hangups.

With BlueJeans, you’ll also get a host of collaboration tools to keep everyone in the loop during your meetings. Use the screen share function to show what you see on your screen, or use a digital whiteboard for sketching, annotating, brainstorming, and more.

Need to separate some participants to start working on a new project? Breakout rooms allow you to move groups of people into another BlueJeans room after meeting together in the main conferencing room.

There’s no doubt that BlueJeans is a top contender in video conferencing platforms with its well-planned features that increase ease-of-use and efficiency for the host and attendees. But there is a potentially significant drawback to consider.

There’s no current ability to play video or audio from within the app. You’ll need to, instead, upload your audio or video clip to BlueJeans to allow it to play. This isn’t a problem for everyone, but it isn’t convenient if you think of a video you’d like to share on the fly.

In contrast, Zoom has a native playback feature that allows you to open a video during your presentation with its built-in video player, making the action more seamless.

BlueJeans Video and Audio Quality

I’ve noted that BlueJeans stands out in terms of audio quality, mostly because it’s powered by Dolby Voice.

This feature keeps background noise to a minimum and clarifies each speaker’s voice to give everyone an even playing field for communicating and being heard during your meeting. This holds true whether you’re connecting from a mobile device or your office computer.

Voice overlapping is a common concern with video conferences, but BlueJeans handles this well, too. Its mission is to make video calls mimic in-person conferences, so when two or more people talk simultaneously, you can hear everyone clearly.

Hosts have the option of muting their participants upon entry, too, to minimize chatter or background noises as everyone gets settled for the meeting to start.

BlueJeans excels with video quality, too. The app uses HD video up to 720p, giving everyone connecting on any device a clear picture.

Keep in mind that your internet connection ultimately decides your video quality. But even with multiple people connecting, BlueJeans skirts choppy video and lag you find on other platforms with its quick, responsive, and modern network.

BlueJeans Call Recording

BlueJeans allows you to record your video meetings with the press of a button, so long as you’re a moderator for the meeting. Your participants will receive a notification that you’ve begun recording.

Your recordings will store online in your BlueJeans account, saving you the hassle of downloading them and storing them on your device.

BlueJeans Standard and Pro plans are a bit limited, though. With Standard, you’ll only get five hours of recording capacity. With Pro, you’ll get 25 hours. To make more room, you’d need to save your recordings elsewhere and delete them on BlueJeans.

An Enterprise plan allows for unlimited recordings. With this plan, you’ll also gain access to link sharing of recordings, multi-channel recording, and auto-recording, which starts recording your meeting as soon as a participant joins.

If you’re looking for a service with helpful call recording tools, try UberConference. It offers call recording with calls up to 45 minutes long on its free plan. With paid plans, you’ll get the additional perk of Voice Intelligence, which provides a full transcript of each meeting.

BlueJeans Call Scheduling and Setup

Call scheduling should feel like a seamless process for hosts and participants. BlueJeans stacks up against its competitors with its ease of scheduling from within the app.

To start a meeting, you’ll simply need to log into your account and click Schedule Meeting. BlueJeans will then present you with several options for your meeting, including repeating the meeting, adding a participant password, and advanced meeting options, like encryption and audible alert disabling.

Email invites to your attendees right through the scheduling prompt. Inviting more people to a meeting after you’ve already sent initial invites is also simple. BlueJeans uses a standard link format for all meetings: bluejeans.com/YourMeetingID#. If you have your meeting ID, you can simply send the participant a link in this format.

BlueJeans also integrates with other apps that use calendars, allowing you to schedule through them if you prefer. Use Google Calendar, Outlook for Windows, or Microsoft Office 365.

BlueJeans Smart Meetings

BlueJeans calls its meetings Smart Meetings due to the many things you can do to prepare for the meeting, grab information from the meeting, and ensure the meeting’s effectiveness afterward. BlueJeans Smart Meetings offers intuitive tools using crowdsourced technology to get everything you and your participants need from each conference call.

BlueJeans Smart Meetings features include:

  • Meeting summaries with quick highlights
  • Priority highlight rankings
  • Create and assign action items during or after meetings
  • Transcriptions of meetings


Everyone you invite to a meeting can receive its highlights, summaries, and action items, whether they joined the meeting or not, keeping your team on the same page. This feature is unmatched by many BlueJeans competitors, which don’t yet offer ways to catch up on important meeting details without watching a full recording.

BlueJeans Integrations

Most conference call platforms integrate with other software and apps to allow your work to transition between the tools you use most. BlueJeans integrates with several popular tools, including Slack, Skype, and Trello. You’ll also have access to connections with:

  • Alexa for Business
  • Kaptivo
  • Pigeonhole
  • Okta
  • Epic
  • Marketo
  • Zoho
  • Canvas
  • Zoom.ai
  • Intellum
  • LinkedIn


Like many competitors, BlueJeans also works with YouTube to stream your meetings and events live to YouTube viewers.

The downside? Third-party integrations are only available for those on the BlueJeans Pro or Enterprise plans. Other services, like Zoom, offer several integrations and apps for free, with more advanced integrations on higher-tier plans.

BlueJeans Command Center and Admin Controls

With BlueJeans, you don’t just get video call conferencing. You also get a host of admin controls and analytics that help you manage meetings and enhance productivity.

It all happens within the BlueJeans Command Center. The full-service dashboard displays the location of participants, active user data, and ROI metrics, like how much you’ve potentially saved participants from traveling to in-person meetings.

One of the most valuable features here is the meeting quality feedback overview. This information can help you pinpoint where video or audio quality issues might be happening the most, such as in specific meeting rooms or with mobile devices.

The Live Meetings tab also points you to metrics of current meetings, including participant details, recording information, and live monitoring and moderating. You can also get real-time alerts on quality loss and participant feedback to resolve issues as quickly as possible.

For large organizations handling multiple meetings daily or weekly, these tools are a must-have, but smaller companies might still see usage indicators and meeting quality summaries as helpful data.

BlueJeans Mobile Conferencing

BlueJeans is available for desktop or mobile devices. The mobile app has a few features specific to its platform to enhance user experience when connecting from a phone or tablet.

One of them is Transit Mode, which allows you to connect with audio-only features to minimize driving distractions. The app will keep your video and microphone off while in this mode, allowing you to listen to the meeting and speak with the tap of a button.

There’s also automatic bandwidth management, which detects your network quality and adjusts it as needed to maintain more consistent video and quality. Whether you’re on the road or using coffee shop Wi-Fi, this feature can make sure you stay connected.

Anyone using the app can share their screen or share documents and photos as well, making BlueJeans extremely friendly for on-the-go meeting participants or hosts.

BlueJeans Security

Meeting security is a priority for anyone using call conferencing services. You should be able to get on a call and know that only you and your invited participants can see and hear the discussion.

BlueJeans has a few features to combat potential security issues, including restricted meeting settings. All meetings can include everyone with a link, invited participants only, or your organization only. For the latter, all meeting participants will need to be set up in your organization’s BlueJeans account.

There’s also a Quick Lock function to keep people from accidentally entering your meeting room. This is beneficial when you use the same meeting ID for multiple meetings, especially those that run back-to-back, to keep your next meeting’s participants in a waiting room until you’re ready.

Until 2020, BlueJeans was behind the security curve compared to its competitors, lacking the basic meeting lock and waiting room feature that many others already had in place. But this addition has brought it up to par, giving hosts more control over who can enter meetings and when.

Compare The Best Conference Call Services
We reviewed dozens of conference call service providers and narrowed them down to the best options.
See Top Picks

BlueJeans may not be as well-known as Zoom for video call conferencing, but its excellent audio and video quality and helpful integrations, analytics, and smart features make it a contender in the industry. Large organizations, especially, may find its Command Center and Smart Meetings even more intuitive than RingCentral or GoToMeeting’s offerings. These features do come at a cost, though. Smaller businesses might get everything they need from the free versions of RingCentral or Zoom, which allow limited-time meetings for 100 participants.

Open Source Maintainer Week Begins June 7 with Activities, Events, and Resources

GitHub, in partnership with Tidelift, has set aside June 7-12, 2021, as Maintainer Week, a time for open source maintainers to share knowledge and experiences through a series of planned activities and events.

Tidelift plans to kick off Maintainer Week on June 7 with a virtual event called Upstream, featuring 30+ sessions that attendees can watch live or access following the event. This event will focus on some of the bigger problems and trends in the open source ecosystem. For example, Sarah Novotny from Microsoft will be speaking about open source as an innovation engine. Simon Phipps, OSI Director of Standards and Policy, will be presenting on “spotting the rights ratchet model early,” a hot topic in the recent open source relicensing controversies. Attendees will also have the opportunity to meet the maintainers and experts behind many popular open source tools that are used at scale.

GitHub will be hosting its inaugural Global Maintainer Summit on June 8-9 as part of the week’s activities. It is billed as more of a gathering or “group therapy session” for maintainers, with lightning talks featuring different projects’ approaches to common problems. WordPress lead developer Helen Hou-Sandí will be presenting a session called “You Can’t Have a Solution Without a Problem.” GitHub emphasized that attendees do not have to be open source maintainers to attend, as many of the the best practices and skills discussed pertain to other aspects of life.

In between sessions, maintainers will have the chance to build collaborative relationships with others and add skills that will help them avoid burnout. GitHub will be hosting a virtual hallway experience using Gather. This will allow attendees to talk with those standing closest to them and have smaller, more personal conversations.

Open source maintainers who want to connect with others who share some of the same challenges, will want to add Maintainer Week’s activities to the calendar. All of the upcoming events are free but registration is required on the Upstream site.

except ValueError… i dont know how to fix it

import math
import numpy as np
import matplotlib.pyplot as plt

print("y = a^x + b")
jarda=0
while jarda<=0 or jarda==1:
 jarda=int(input("zadej a "))

def v() :
 while True:
   slo=(input("zadej b "))
   try :
return int (slo)
  except ValueError
 print("nebylo zadan slo")
barca=b()

A = int (input("zadej poten hodnotu def.oboru "))
B = int (input("zadej konenou hodnotu def.oboru "))

if barca>=0:
 print("Px nen")
else:
 print("Px je:[0; ",(math.log(-barca,jarda)))
 print("Py je:[0; ",(jarda0+barca))
if barca<=0:
 print("Py nen")
else:
 print("Py je:[0; ",(jarda0+barca))

x= np.linspace(A,B)
y = jarda**x+barca

plt.plot(x,y, color="pink")
plt.axhline(y=0,color="black")
plt.axvline(x=0,color="orange")
plt.xlabel("x")
plt.ylabel("y")
plt.box(True)
plt.grid(True)
plt.title("exponenciln funkce")

5 Thrilling Questions About Digital Age Verification Answered!

Do you know that presently, 94% of the people with an age group of 3 to 18 can access the internet effortlessly? Among them, 88% can access the internet via computers and the remaining 6% can access the internet only via smartphones. The rest of the 6% do not have any in their houses. 

With great numbers comes great responsibility. The pandemic year was a major excuse for online education. Parents have to permit their children to have internet access for their online studies. But also, parents these days are busy enough that they do not have spare time to keep a critical eye on their child’s activities. This results in unauthorized child access to age-restricted content and products, resulting in child exploitation. Children are getting smarter and smarter in parallel to technological innovations and advancements. Effortless access to age-restricted content has become a major concern of teachers, parents, and e-retailers. There exist a wide range of e-commerce platforms that sell tobacco, alcohol, etc. 

Mobile Apps Dataset

Introduction

My main job is related to mobile advertising, and from time to time, I have to work with mobile application datasets.

I decided to make some of the data publicly available for those who want to practice building models or get an idea of some of the data that can be collected from open sources. I believe that open-source datasets are always useful as they allow you to learn and grow. Collecting data is often a difficult and dreary job, and not everyone has the ability to do it.

Comparison of Apache Kafka Products and Cloud Services

Apache Kafka became the de facto standard for event streaming. The open-source community is huge. Various vendors added Kafka and related tooling to their offerings or provide a Kafka cloud service. This blog post uses the car analogy - from the motor engine to the self-driving car - to explore the different Kafka offerings available on the market. I also cover a few other vehicles, meaning (partly) Kafka-compatible technologies. The goal is not a feature-by-feature comparison (that would be outdated the day after the publication). Instead, the intention is to educate about the different deployment models, product strategies, and trade-offs from the available options.

Disclaimer: I work for Confluent. However, the post is not about comparing features but explaining the concepts behind the alternatives. I talk to enterprises across the globe every week. I can assure you that many people I talk to are not aware or mislead about what you read in the following sections. Hence, I hope that the following helps you to make the right decision. Either choose to run open-source Apache Kafka or one of the various commercial Kafka offerings, or even a combination of both.

Svelte for the Experienced React Dev

This post is an accelerated introduction to Svelte from the point of view of someone with solid experience with React. I’ll provide a quick introduction, and then shift focus to things like state management and DOM interoperability, among other things. I plan on moving somewhat quickly, so I can cover a lot of topics. At the end of the day, I’m mainly hoping to spark some interest in Svelte.

For a straightforward introduction to Svelte, no blog post could ever beat the official tutorial or docs.

“Hello, World!” Svelte style

Let’s start with a quick tour of what a Svelte component looks like.

<script>
  let number = 0;
</script>

<style>
  h1 {
    color: blue;
  }
</style>

<h1>Value: {number}</h1>

<button on:click={() => number++}>Increment</button>
<button on:click={() => number--}>Decrement</button> 

That content goes in a .svelte file, and is processed by the Rollup or webpack plugin to produce a Svelte component. There’s a few pieces here. Let’s walk through them.

First, we add a <script> tag with any state we need.

We can also add a <style> tag with any CSS we want. These styles are scoped to the component in such a way that, here, <h1> elements in this component will be blue. Yes, scoped styles are built into Svelte, without any need for external libraries. With React, you’d typically need to use a third-party solution to achieve scoped styling, such as css-modules, styled-components, or the like (there are dozens, if not hundreds, of choices).

Then there’s the HTML markup. As you’d expect, there are some HTML bindings you’ll need to learn, like {#if}, {#each}, etc. These domain-specific language features might seem like a step back from React, where everything is “just JavaScript.” But there’s a few things worth noting: Svelte allows you to put arbitrary JavaScript inside of these bindings. So something like this is perfectly valid:

{#if childSubjects?.length}

If you jumped into React from Knockout or Ember and never looked back, this might come as a (happy) surprise to you.

Also, the way Svelte processes its components is very different from React. React re-runs all components any time any state within a component, or anywhere in an ancestor (unless you “memoize”), changes. This can get inefficient, which is why React ships things like useCallback and useMemo to prevent un-needed re-calculations of data.

Svelte, on the other hand, analyzes your template, and creates targeted DOM update code whenever any relevant state changes. In the component above, Svelte will see the places where number changes, and add code to update the <h1> text after the mutation is done. This means you never have to worry about memoizing functions or objects. In fact, you don’t even have to worry about side-effect dependency lists, although we’ll get to that in a bit.

But first, let’s talk about …

State management

In React, when we need to manage state, we use the useState hook. We provide it an initial value, and it returns a tuple with the current value, and a function we can use to set a new value. It looks something like this:

import React, { useState } from "react";

export default function (props) {
  const [number, setNumber] = useState(0);
  return (
    <>
      <h1>Value: {number}</h1>
      <button onClick={() => setNumber(n => n + 1)}>Increment</button>
      <button onClick={() => setNumber(n => n - 1)}>Decrement</button>
    </>
  );
}

Our setNumber function can be passed wherever we’d like, to child components, etc.

Things are simpler in Svelte. We can create a variable, and update it as needed. Svelte’s ahead-of-time compilation (as opposed to React’s just-in-time compilation) will do the footwork of tracking where it’s updated, and force an update to the DOM. The same simple example from above might look like this:

<script>
  let number = 0;
</script>

<h1>Value: {number}</h1>
<button on:click={() => number++}>Increment</button>
<button on:click={() => number--}>Decrement</button>

Also of note here is that Svelte requires no single wrapping element like JSX does. Svelte has no equivalent of the React fragment <></> syntax, since it’s not needed.

But what if we want to pass an updater function to a child component so it can update this piece of state, like we can with React? We can just write the updater function like this:

<script>
  import Component3a from "./Component3a.svelte";
        
  let number = 0;
  const setNumber = cb => number = cb(number);
</script>

<h1>Value: {number}</h1>

<button on:click={() => setNumber(val => val + 1)}>Increment</button>
<button on:click={() => setNumber(val => val - 1)}>Decrement</button>

Now, we pass it where needed — or stay tuned for a more automated solution.

Reducers and stores

React also has the useReducer hook, which allows us to model more complex state. We provide a reducer function, and it gives us the current value, and a dispatch function that allows us to invoke the reducer with a given argument, thereby triggering a state update, to whatever the reducer returns. Our counter example from above might look like this:

import React, { useReducer } from "react";

function reducer(currentValue, action) {
  switch (action) {
    case "INC":
      return currentValue + 1;
    case "DEC":
      return currentValue - 1;
  }
}

export default function (props) {
  const [number, dispatch] = useReducer(reducer, 0);
  return (
    <div>
      <h1>Value: {number}</h1>
      <button onClick={() => dispatch("INC")}>Increment</button>
      <button onClick={() => dispatch("DEC")}>Decrement</button>
    </div>
  );
}

Svelte doesn’t directly have something like this, but what it does have is called a store. The simplest kind of store is a writable store. It’s an object that holds a value. To set a new value, you can call set on the store and pass the new value, or you can call update, and pass in a callback function, which receives the current value, and returns the new value (exactly like React’s useState).

To read the current value of a store at a moment in time, there’s a get function that can be called, which returns its current value. Stores also have a subscribe function, which we can pass a callback to, and that will run whenever the value changes.

Svelte being Svelte, there’s some nice syntactic shortcuts to all of this. If you’re inside of a component, for example, you can just prefix a store with the dollar sign to read its value, or directly assign to it, to update its value. Here’s the counter example from above, using a store, with some extra side-effect logging, to demonstrate how subscribe works:

<script>
  import { writable, derived } from "svelte/store";
        
  let writableStore = writable(0);
  let doubleValue = derived(writableStore, $val => $val * 2);
        
  writableStore.subscribe(val => console.log("current value", val));
  doubleValue.subscribe(val => console.log("double value", val))
</script>

<h1>Value: {$writableStore}</h1>

<!-- manually use update -->
<button on:click={() => writableStore.update(val => val + 1)}>Increment</button>
<!-- use the $ shortcut -->
<button on:click={() => $writableStore--}>Decrement</button>

<br />

Double the value is {$doubleValue}

Notice that I also added a derived store above. The docs cover this in depth, but briefly, derived stores allow you to project one store (or many stores) to a single, new value, using the same semantics as a writable store.

Stores in Svelte are incredibly flexible. We can pass them to child components, alter, combine them, or even make them read-only by passing through a derived store; we can even re-create some of the React abstractions you might like, or even need, if we’re converting some React code over to Svelte.

React APIs with Svelte

With all that out of the way, let’s return to React’s useReducer hook from before.

Let’s say we really like defining reducer functions to maintain and update state. Let’s see how difficult it would be to leverage Svelte stores to mimic React’s useReducer API. We basically want to call our own useReducer, pass in a reducer function with an initial value, and get back a store with the current value, as well as a dispatch function that invokes the reducer and updates our store. Pulling this off is actually not too bad at all.

export function useReducer(reducer, initialState) {
  const state = writable(initialState);
  const dispatch = (action) =>
    state.update(currentState => reducer(currentState, action));
  const readableState = derived(state, ($state) => $state);

  return [readableState, dispatch];
}

The usage in Svelte is almost identical to React. The only difference is that our current value is a store, rather than a raw value, so we need to prefix it with the $ to read the value (or manually call get or subscribe on it).

<script>
  import { useReducer } from "./useReducer";
        
  function reducer(currentValue, action) {
    switch (action) {
      case "INC":
        return currentValue + 1;
      case "DEC":
        return currentValue - 1;
    }
  }
  const [number, dispatch] = useReducer(reducer, 0);      
</script>

<h1>Value: {$number}</h1>

<button on:click={() => dispatch("INC")}>Increment</button>
<button on:click={() => dispatch("DEC")}>Decrement</button>

What about useState?

If you really love the useState hook in React, implementing that is just as straightforward. In practice, I haven’t found this to be a useful abstraction, but it’s a fun exercise that really shows Svelte’s flexibility.

export function useState(initialState) {
  const state = writable(initialState);
  const update = (val) =>
    state.update(currentState =>
      typeof val === "function" ? val(currentState) : val
    );
  const readableState = derived(state, $state => $state);

  return [readableState, update];
}

Are two-way bindings really evil?

Before closing out this state management section, I’d like to touch on one final trick that’s specific to Svelte. We’ve seen that Svelte allows us to pass updater functions down the component tree in any way that we can with React. This is frequently to allow child components to notify their parents of state changes. We’ve all done it a million times. A child component changes state somehow, and then calls a function passed to it from a parent, so the parent can be made aware of that state change.

In addition to supporting this passing of callbacks, Svelte also allows a parent component to two-way bind to a child’s state. For example, let’s say we have this component:

<!-- Child.svelte -->
<script>
  export let val = 0;
</script>

<button on:click={() => val++}>
  Increment
</button>

Child: {val}

This creates a component, with a val prop. The export keyword is how components declare props in Svelte. Normally, with props, we pass them in to a component, but here we’ll do things a little differently. As we can see, this prop is modified by the child component. In React this code would be wrong and buggy, but with Svelte, a component rendering this component can do this:

<!-- Parent.svelte -->
<script>
  import Child from "./Child.svelte";
        
  let parentVal;
</script>

<Child bind:val={parentVal} />
Parent Val: {parentVal}

Here, we’re binding a variable in the parent component, to the child’s val prop. Now, when the child’s val prop changes, our parentVal will be updated by Svelte, automatically.

Two-way binding is controversial for some. If you hate this then, by all means, feel free to never use it. But used sparingly, I’ve found it to be an incredibly handy tool to reduce boilerplate.

Side effects in Svelte, without the tears (or stale closures)

In React, we manage side effects with the useEffect hook. It looks like this:

useEffect(() => {
  console.log("Current value of number", number);
}, [number]);

We write our function with the dependency list at the end. On every render, React inspects each item in the list, and if any are referentially different from the last render, the callback re-runs. If we’d like to cleanup after the last run, we can return a cleanup function from the effect.

For simple things, like a number changing, it’s easy. But as any experienced React developer knows, useEffect can be insidiously difficult for non-trivial use cases. It’s surprisingly easy to accidentally omit something from the dependency array and wind up with a stale closure.

In Svelte, the most basic form of handling a side effect is a reactive statement, which looks like this:

$: {
  console.log("number changed", number);
}

We prefix a code block with $: and put the code we’d like to execute inside of it. Svelte analyzes which dependencies are read, and whenever they change, Svelte re-runs our block. There’s no direct way to have the cleanup run from the last time the reactive block was run, but it’s easy enough to workaround if we really need it:

let cleanup;
$: {
  cleanup?.();
  console.log("number changed", number);
  cleanup = () => console.log("cleanup from number change");
}

No, this won’t lead to an infinite loop: re-assignments from within a reactive block won’t re-trigger the block.

While this works, typically these cleanup effects need to run when your component unmounts, and Svelte has a feature built in for this: it has an onMount function, which allows us to return a cleanup function that runs when the component is destroyed, and more directly, it also has an onDestroy function that does what you’d expect.

Spicing things up with actions

The above all works well enough, but Svelte really shines with actions. Side effects are frequently tied to our DOM nodes. We might want to integrate an old (but still great) jQuery plugin on a DOM node, and tear it down when that node leaves the DOM. Or maybe we want to set up a ResizeObserver for a node, and tear it down when the node leaves the DOM, and so on. This is a common enough requirement that Svelte builds it in with actions. Let’s see how.

{#if show}
  <div use:myAction>
    Hello                
  </div>
{/if}

Note the use:actionName syntax. Here we’ve associated this <div> with an action called myAction, which is just a function.

function myAction(node) {
  console.log("Node added", node);
}

This action runs whenever the <div> enters the DOM, and passes the DOM node to it. This is our chance to add our jQuery plugins, set up our ResizeObserver, etc. Not only that, but we can also return a cleanup function from it, like this:

function myAction(node) {
  console.log("Node added", node);

  return {
    destroy() {
      console.log("Destroyed");
    }
  };
}

Now the destroy() callback will run when the node leaves the DOM. This is where we tear down our jQuery plugins, etc.

But wait, there’s more!

We can even pass arguments to an action, like this:

<div use:myAction={number}>
  Hello                
</div>

That argument will be passed as the second argument to our action function:

function myAction(node, param) {
  console.log("Node added", node, param);

  return {
    destroy() {
      console.log("Destroyed");
    }
  };
}

And if you’d like to do additional work whenever that argument changes, you can return an update function:

function myAction(node, param) {
  console.log("Node added", node, param);

  return {
    update(param) {
      console.log("Update", param);
    },
    destroy() {
      console.log("Destroyed");
    }
  };
}

When the argument to our action changes, the update function will run. To pass multiple arguments to an action, we pass an object:

<div use:myAction={{number, otherValue}}>
  Hello                
</div>

…and Svelte re-runs our update function whenever any of the object’s properties change.

Actions are one of my favorite features of Svelte; they’re incredibly powerful.

Odds and Ends

Svelte also ships a number of great features that have no counterpart in React. There’s a number of form bindings (which the tutorial covers), as well as CSS helpers.

Developers coming from React might be surprised to learn that Svelte also ships animation support out of the box. Rather than searching on npm and hoping for the best, it’s… built in. It even includes support for spring physics, and enter and exit animations, which Svelte calls transitions.

Svelte’s answer to React.Chidren are slots, which can be named or not, and are covered nicely in the Svelte docs. I’ve found them much simpler to reason about than React’s Children API.

Lastly, one of my favorite, almost hidden features of Svelte is that it can compile its components into actual web components. The svelte:options helper has a tagName property that enables this. But be sure to set the corresponding property in the webpack or Rollup config. With webpack, it would look something like this:

{
  loader: "svelte-loader",
  options: {
    customElement: true
  }
}

Interested in giving Svelte a try?

Any of these items would make a great blog post in and of itself. While we may have only scratched the surface of things like state management and actions, we saw how Svelte’s features not only match up pretty with React, but can even mimic many of React’s APIs. And that’s before we briefly touched on Svelte’s conveniences, like built-in animations (or transitions) and the ability to convert Svelte components into bona fide web components.

I hope I’ve succeeded in sparking some interest, and if I have, there’s no shortage of docs, tutorials, online courses, etc that dive into these topics (and more). Let me know in the comments if you have any questions along the way!


The post Svelte for the Experienced React Dev appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS Hell

Collection of common CSS mistakes, and how to fix them

From Stefánia Péter.

Clever idea for a site! Some of them are little mind-twisters that could bite you, and some of them are honing in on best practices that may affect accessibility.

Why “CSS Hell”?

It’s a joke idea I stole from HTMHell. I hope adding some fun and sarcasm to learning might help raising awareness of how !important a good CSS code is.

Direct Link to ArticlePermalink


The post CSS Hell appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.