1685361070
Adobe Photoshop выпустила новый инструмент под названием Generative Fill, который управляется генератором изображений Firefly с искусственным интеллектом. Этот инструмент позволяет пользователям легко расширять фотографии, добавлять или удалять элементы с помощью текстовых подсказок и обеспечивает больший контроль, чем существующие инструменты, такие как Content-Aware Fill. Благодаря интеграции в Photoshop Generative Fill расширяет доступ к возможностям создания изображений с помощью ИИ. Давайте посмотрим на специфику и возможности этого нового инструмента.
Инструмент генеративной заливки Photoshop предоставляет множество вариантов изменения и изменения изображения.
Вот несколько примеров того, чего вы можете достичь с помощью генеративного ИИ:
Adobe объявила, что Firefly Generative Fill скоро станет опцией по умолчанию в Photoshop. Однако в настоящее время эта возможность доступна только в бета-версии Photoshop. Выполните следующие простые шаги, чтобы получить доступ к бета-функциям:
Выполнив эти шаги, вы можете получить доступ к бета-версии Photoshop и протестировать экспериментальные функции, такие как Firefly Generative Fill, прежде чем они станут доступны для широкой публики. Воспользуйтесь возможностью изучить и узнать о возможностях этого интересного инструмента.
Если вы знакомы с генеративным искусственным интеллектом, использование «Photoshop AI» и его новой функции генеративного заполнения не составит труда. Просто выполните следующие действия:
Новейшие возможности искусственного интеллекта Adobe Photoshop предоставляют художникам и дизайнерам множество мощных инструментов, помогающих им улучшить свой творческий процесс. Давайте посмотрим на захватывающие возможности Adobe Photoshop AI:
Окунитесь в будущее искусственного интеллекта Photoshop: художники получают непревзойденную творческую гибкость и продуктивность, используя возможности искусственного интеллекта Adobe Photoshop. Photoshop остается отраслевым стандартом, используя возможности искусственного интеллекта, позволяя художникам исследовать и расширять границы своего воображения. Исследуйте интригующий мир Photoshop AI прямо сейчас и раскройте свой творческий потенциал.
Эта статья поможет вам изучить Adobe Powerful Generative AI Tools в бета-версии Photoshop. Мы верим, что это было полезно для вас. Пожалуйста, не стесняйтесь делиться своими мыслями и отзывами в разделе комментариев ниже.
Оригинальный источник статьи: https://www.cloudbooklet.com/
1685357300
Adobe Photoshop 发布了一款名为 Generative Fill 的新工具,由 AI 图片生成器 Firefly 驱动。该工具使用户能够使用文本提示轻松扩展照片、添加或删除项目,并提供比当前工具(如内容识别填充)更多的控制。通过与 Photoshop 的集成,Generative Fill 拓宽了对 AI 图片制作功能的访问。让我们看看这个新工具的细节和可能性。
Photoshop 的 Generative Fill 工具提供了多种图片修改和更改选项。
以下是您可以使用生成式 AI 实现的一些示例:
Adobe 宣布 Firefly 生成填充将很快成为 Photoshop 中的默认选项。但是,此功能目前仅在 Photoshop 的测试版中可用。按照以下简单步骤获取对测试版功能的访问权限:
通过执行这些步骤,您可以访问 Photoshop 的测试版并在Firefly Generative Fill 等实验性功能向更广泛的公众开放之前对其进行测试。利用这个机会探索和了解这个有趣工具的功能。
如果您熟悉生成式 AI,那么使用“Photoshop AI”及其新的生成式填充功能将轻而易举。只需按照以下步骤操作:
Adobe Photoshop 的最新 AI 功能为艺术家和设计师提供了大量强大的工具,帮助他们改进创作过程。让我们来看看 Adobe Photoshop AI 令人兴奋的功能:
拥抱 Photoshop AI 的未来:艺术家使用 Adobe Photoshop 的 AI 功能获得无与伦比的创作灵活性和生产力。Photoshop 通过使用 AI 的力量保持行业标准,允许艺术家探索和突破他们想象力的界限。立即探索 Photoshop AI 的迷人世界,释放您的创造潜能。
本文旨在帮助您学习 Photoshop Beta 中的 Adobe 强大的生成式 AI 工具。我们相信它对您有所帮助。请随时在下面的评论部分分享您的想法和反馈。
文章原文出处:https: //www.cloudbooklet.com/
1685353560
Adobe Photoshop has released a new tool called Generative Fill, which is driven by the AI picture generator Firefly. This tool enables users to easily extend photos, add or delete items using text prompts, and provides more control than current tools such as Content-Aware Fill. With its integration into Photoshop, Generative Fill broadens access to the capabilities of AI picture production. Let’s look at the specifics and possibilities of this new instrument.
Photoshop’s Generative Fill tool provides a variety of picture altering and alteration options.
Here are some examples of what you may achieve using Generative AI:
Adobe has announced that Firefly Generative Fill will soon become the default option in Photoshop. However, this capability is presently only available in Photoshop’s beta version. Follow these easy steps to acquire access to the beta functions:
By following these steps, you may gain access to Photoshop’s beta edition and test out experimental features like Firefly Generative Fill before they are made available to the wider public. Take advantage of the chance to explore with and learn about the capabilities of this interesting tool.
If you’re familiar with generative AI, using “Photoshop AI” and its new generative fill function is a breeze. Simply follow these steps:
Adobe Photoshop’s newest AI capabilities provide artists and designers with a plethora of strong tools to help them improve their creative process. Let’s have a look at Adobe Photoshop AI’s exciting capabilities:
Embrace the Future of Photoshop AI: Artists get unparalleled creative flexibility and productivity using Adobe Photoshop’s AI capabilities. Photoshop remains the industry standard by using the power of AI, allowing artists to explore and push the boundaries of their imagination. Explore the intriguing world of Photoshop AI now and unleash your creative potential.
This article is to help you learn Adobe Powerful Generative AI Tools in Photoshop Beta. We trust that it has been helpful to you. Please feel free to share your thoughts and feedback in the comment section below.
Original article source at: https://www.cloudbooklet.com/
1679470320
store
nonce
for CSP>=2.0.3
)>=1.11.0
(highly recommended to use 2.x.x
)>=17.0.0
# yarn
yarn add jotai-devtools
# npm
npm install jotai-devtools --save
Enhance your development experience with the UI based Jotai DevTool
Use Jotai babel plugins for optimal debugging experience. Find the complete guide on jotai.org
Eg.
{
"plugins": [
// Enables hot reload for atoms
"jotai/babel/plugin-react-refresh",
// Automatically adds debug labels to the atoms
"jotai/babel/plugin-debug-label"
]
}
You may skip this section if you're not using Next.js.
Enable transpilePackages
for the UI CSS and components to be transpiled correctly.
// next.config.ts
const nextConfig = {
// Learn more here - https://nextjs.org/docs/advanced-features/compiler#module-transpilation
// Required for font css to be imported correctly 👇
transpilePackages: ['jotai-devtools'],
};
module.exports = nextConfig;
type DevToolsProps = {
// Defaults to false
isInitialOpen?: boolean;
// pass a custom store
store?: Store;
// Defaults to light
theme?: 'dark' | 'light';
// Custom nonce to allowlist jotai-devtools specific inline styles via CSP
nonce?: string;
options?: {
// Private atoms are used internally in atoms like `atomWithStorage` or `atomWithLocation`, etc. to manage state.
// Defaults to `false`
shouldShowPrivateAtoms?: boolean;
};
};
import { DevTools } from 'jotai-devtools';
const App = () => {
return (
<>
<DevTools />
{/* your app */}
</>
);
};
import { createStore } from 'jotai';
import { DevTools } from 'jotai-devtools';
const customStore = createStore();
const App = () => {
return (
<Provider store={customStore}>
<DevTools store={customStore} />
{/* your app */}
</Provider>
);
};
Detailed documentation is available on https://jotai.org/docs/api/devtools
import {
useAtomsSnapshot,
useGotoAtomsSnapshot,
useAtomsDebugValue,
// Redux devtool hooks
useAtomDevtools,
useAtomsDevtools,
} from 'jotai-devtools';
Find the official migration guide on jotai.org
jotai/react/devtools
to jotai-devtools
Install this package
# npm
npm install jotai-devtools --save
# yarn
yarn add jotai-devtools
Update imports from jotai/react/devtools
to jotai-devtools
import {
useAtomsSnapshot,
useGotoAtomsSnapshot,
useAtomsDebugValue,
// Redux devtool integration hooks
useAtomDevtools,
useAtomsDevtools,
- } from 'jotai/react/devtools';
+ } from 'jotai-devtools';
Author: Himself65
Source Code: https://github.com/Himself65/jotai-devtools
License: MIT license
1675517421
Speed is money for an ecommerce site. The faster your site loads, the better the shopping experience. A better user experience translates to improved SEO, increased ROI, and happier customers. This ultimately leads to greater revenue and profits.
Shoppers today expect high-resolution images and videos, live chat, user reviews, real-time inventory, personalization, and a host of other dynamic tools.
Online shoppers have a short attention span. Hence, all the features they expect to have a faster and smoother buying experience are the same ones that slow down your ecommerce site if you don’t execute them properly.
WooCommerce is the most popular ecommerce platform in the world and is free to use and tweak as per your requirements. Kinsta Can with POPs highlighted” width=”800″ height=”500″ /> Kinsta Can with PoPs
WooCommerce leads the ecommerce pack (Image source: BuiltWith)\
WooCommerce has been downloaded over 88 million times to date. As of now, it’s in use on over 5 million websites.
WooCommerce plugin downloads and usage stats
Unlike other popular shopping platforms, you don’t have to pay a percentage of your revenue to WooCommerce if you use it. There are some overhead costs associated with running a WooCommerce-powered store though.
But there’s a catch! Since WooCommerce is free with limited support, you’re responsible for maintaining it in tip-top shape. The good news is that it’s easy to take care of it if you know what you’re doing!
Want to learn how to speed up your WooCommerce site reliably?
This guide is for you!
And remember, your ultimate goal is to increase your store’s revenue. So be sure to download our free ebook, 10 Ways to Boost Your WooCommerce Product Page Conversions.
First impressions matter and speed is the first thing a user will notice about your site. In a study by Google, 53% of mobile users left a site if it took longer than 3 seconds to load.
3 seconds is best practice (Image source: Think with Google)
“2 seconds is the threshold for ecommerce website acceptability. At Google, we aim for under a half second.”
– Maile Ohye, Tech Lead, Google
In another global study, 80% of users said that they find a slow loading website more frustrating than a temporarily down one. The same study also found that 73% of users would switch to a competitor site if a website is too slow to load.
Even a 100-millisecond delay in page response time can hurt the user experience and online revenue. As per Akamai, a 100-millisecond delay impacts conversion rates by 7%, while a 2-second delay increases bounce rates by a whopping 103%.
If your site is generating $1000 in revenue daily, 100-millisecond delays in page load times might cost you $25,550 in lost sales annually.
The bigger the business, the greater the fall. For instance, Amazon projected a revenue loss of $1.6 billion annually if its page load time slowed by just one second.
Page load time is vital (Image source: Think with Google)
The above data suggests that if your website takes 6 seconds or more to load, you’re losing twice as many users as you would if your site loaded in less than 3 seconds.
Apart from user experience, your site’s speed also impacts SEO. Website speed and performance play a major factor in Google’s site ranking algorithm.
Google has shifted to mobile-first indexing for over 50% of the pages shown in their search results. Despite this, data from HTTPArchive.org suggests that the average load time for mobile sites running WordPress has worsened in the last year.
How top WordPress sites perform (Image source: HTTPArchive.org)
During peak traffic times such as Cyber Monday and Black Friday, it’s even more crucial to keep your site running as fast as possible. With the outburst of offers going around, ensuring that shoppers don’t abandon your site is critical to close sales.
Given these statistics, speeding up your WooCommerce Store can give you a significant edge over your competition.
What you cannot measure, you cannot improve!
Now that you’ve understood why speed is important for your WooCommerce store, it’s time to learn how to measure it. It’s essential to know how to gauge the improvements when you’re trying to speed up your WordPress site.
A website speed test is a perfect tool to test the responsiveness of your WooCommerce store. But if you don’t do this properly, your site may seem slower to you after making a change, when it’s faster.
A website speed test report (Image source: Pingdom)
We recommend you get started with one of these website speed testing tools: WebPagetest, Pingdom, Google PageSpeed Insights or GTMetrix.
You can also use the free WordPress plugin Query Monitor to pinpoint the themes, plugins, and functions that are performing poorly. It helps you debug inefficient database queries, bloated functions, PHP errors, HTTP API calls, etc.
No speed testing tool is perfect, but pick one and stick with it. You can work your way towards other options later.
Gary Illyes, Webmaster Trends Analyst, Google
There’s a difference between actual performance and perceived performance. The user experience matters more than the technical wizardry powering the site.
Therefore, use the techniques mentioned below to enhance your site’s overall user experience, rather than just getting a high-speed score.
A speed test report will give you an actionable plan to optimize your slow WooCommerce site. Excited? Let’s get started!
Let’s start with the basics by optimizing WooCommerce plugin settings.
First, change your login page URL. By default, every WordPress site’s login URL is domain.com/wp-admin/. While this is easy to remember, it poses a major problem: everyone knows about it too, including bots and hackers.
Changing your login URL to something unique will protect you against brute force attacks from nefarious actors. It’ll also help you combat rate-limiting HTTP errors like 429 Too Many Requests.
Free plugins such as WPS Hide Login and Rename wp-login.php make this task super easy.
If your ecommerce site hosts a blog too, you can limit the number of posts on your blog feed. WordPress sets this limit to 10 posts by default, but you can set a lower limit.
While this may seem trivial, performance savings add up if you run a high-traffic blog (here’s how to drive traffic to your website). You can find this option under WordPress Dashboard → Settings → Reading.
Limit the number of posts in your blog feed
Next, disable pingbacks on your website. They usually generate worthless spam. The fewer queries your site generates, the better.
Optimize the discussion settings
If you have a lot of user comments on your posts or pages, then WordPress also gives you an option to break them into smaller chunks. The same setting holds true for breaking down reviews on your product pages.
Keep this number between 10 and 20 to optimize your product page load time.
You can disable product reviews under WooCommerce → Settings if you don’t like having them on your store. This will help speed up your site as it eliminates loading a few scripts and widgets.
Disable product reviews if you don’t need them
Finally, remove any unnecessary/outdated themes and plugins from your site. The fewer themes and plugins you’ve installed, the easier it is to maintain them and troubleshoot performance issues.
Using the right WooCommerce theme matters. There are hundreds of thousands of themes out there, so deciding on the one that’s perfect for you is always a challenge.
Featured themes on WordPress.org
A beautiful theme with amazing built-in features can sound great on paper, but it may flop in actual usage. For an ecommerce site, you need to ensure that it’s fully compatible with WooCommerce.
Filter down your ecommerce theme search
WP Rocket tested a bunch of popular WooCommerce themes for speed and came up with the following results.
Opt for a fast WooCommerce theme (Image source: WP Rocket)
Astra, OceanWP, and GeneratePress are also Kinsta’s favorites as suggested in the WordPress speed up article. They’re ultra-fast, lightweight WordPress themes. You will find 10+ additional very fast themes in this tutorial.
When paired with a page builder such as Elementor or Beaver Builder, they can help you create almost any site.
Storefront is WooCommerce’s official theme
Storefront is a free theme offered by WooCommerce, whereas Shoptimizer, Divi, and WoondrShop are premium themes. Since these themes are built for running an ecommerce site, there’s no need to install third-party plugins to get all the features you want.
If you’re short on budget, it’s perfectly fine to start with a free theme and upgrade later to a premium solution.
We recommend leaving page builders behind to reduce bloat. Instead, go for a theme that supports WordPress’ block editor Gutenberg.
To decide on a theme, we suggest you list down all the features you need in your online store. Then go for a theme that covers most of your feature requirements. This will help you cut down dependency on bloated multi-purpose themes and third-party plugins.
This brings us to the next suggestion.
WordPress has 54,000+ free plugins in its repository. There are even more premium plugins out in the wild. Thus, it’s easy to get carried away and install dozens of them.
There’s a plugin for almost anything
Many popular plugins, especially performance and security related ones, don’t work well in certain hosting environments.
If you find it hard to decide which plugin to install, go through Kinsta’s hand-picked list of the best WordPress plugins for various uses. From SEO to image compression, you’re bound to find some gems in there.
WooCommerce functionality can be expanded with its wide range of free and premium WooCommerce extensions. They work the same way as plugins.
WooCommerce extensions enhance your store’s functionality
Contrary to popular perception, the number of plugins you install doesn’t always cause performance issues. But this holds true only as long as the plugins are built with the best coding practices.
Vetting every plugin you install for quality becomes a hassle when there are too many of them. And that’s considering you have the skills and expertise to vet them thoroughly.
A few plugins even create conflicts with other plugins. When you have dozens of plugins on your site, the probability of a plugin conflict occurring shoots up exponentially.
Hence, be smart about the type of plugins and WooCommerce extensions you install.
WordPress allocates 32 MB memory for PHP by default. If it runs into any crunches, it’ll automatically try to increase this limit to 40 MB (for a single site) or 64 MB (for a multisite).
In most cases, this memory limit won’t be enough for a WooCommerce site. You may even receive an error message on your dashboard such as:
“Allowed memory size of xxxxxx bytes exhausted”
It’s recommended to increase this limit to 256 MB. Always do a backup of any file before you edit it. In case something goes wrong, you can replace the edited file with the original one.
Images make up the bulk of any website’s page size, more so for an ecommerce site. WooCommerce sites are loaded with product images and banners.
If you don’t optimize images for size and delivery, they can bring your website to a crawl 🐌
HTTPArchive tracks the size and quantity of many popular web pages. Here’s a visual representation of their state of WordPress sites in 2021:
Images are a heavy resource
While videos are a heavier resource than images, they’re loaded on demand in most cases. Hence, they don’t affect the perceived page load speed as much as images do.
According to HTTP Archive’s State of the Images report, you can save 545 KB per page by lazy-loading hidden and offscreen images.
By setting your JPEG compression levels to 85 or lower, you can further save 40.3 KB per page. This metric comes straight from Lighthouse, Google’s speed test tool for mobile websites.
Follow these 5 rules to optimize images for your WooCommerce store (and the web in general):
WooCommerce 3.3 introduced image size improvements such as on-the-fly thumbnail resizing, blurry image fix, and background thumbnail resizing. All these features make using a plugin such as Regenerate Thumbnails for WooCommerce-related images redundant.
Customizing WooCommerce’s Product Images (Image source: WooCommerce)
If you’re starting with a fresh install, you can compress your images before you upload them to your site. Here are some of the top online image compression recommendations:
Compress images with minimal loss in quality (Image source: Compressor.io)
Do you have many images already up on your site? Then you can use a WordPress plugin to automate image optimization. Here are the ones that consistently performed the best in our experience:
Most of these plugins also enable lazy-loading for images. The WordPress core team is planning to add lazy-loading images as an inbuilt feature. This will utilize the new loading HTML attribute for <img> tags.
One last thing on image optimization, though. Avoid using image compression plugins as much as possible, particularly the ones that use your server’s resources to compress the images.
Instead, use a service that offloads the image compression task to an external server. Or better yet, resize and compress your images before uploading them to your website.
For an in-depth tutorial, Kinsta’s article on image optimization for web and performance is a great resource to get started.
A Content Delivery Network (CDN) is a group of servers located strategically around the world. These server locations are known as Points of Presence (PoPs).
A CDN’s primary function is to cache and deliver static resources such as images, JavaScript, CSS, etc. More powerful CDNs can also host and deliver dynamic content such as audio and video.
Even if your site runs on the fastest server on the planet, it’s still limited by its geographical location. A WordPress CDN will decrease the distance between the individual user and the site’s resources, reducing both network latency and time to first byte (TTFB).
Kinsta CDN with PoPs highlighted
Depending on where the request is coming from, it automatically assigns the nearest CDN PoP to deliver the cached resources. The result is a faster website and a better user experience.
If you are a Kinsta customer, at no extra cost to you, we provide only locations offering Google’s best C2 machines. You can select the region that works best for you and your users and choose from 26 data centers on five continents.
Your WooCommerce store can run a maximum speed with our 275+ CDN POPs.
For instance, if your WooCommerce store is hosted at a server in the USA, and a user from India tries to open your website, the CDN will serve the website’s assets from the nearest PoP. Here it would be from Bengaluru (India).
CDNs are perfect for delivering static content (Image source: Seobility)
As a general rule, the higher the number of PoPs and the wider their global spread, the faster your website will be for your users.
Kinsta put its CDN to the test and the results speak for themselves. For users in geographical locations that are considerably farther from the hosting server, using a CDN decreased site load time by over 50%.
Apart from caching, many CDNs include other performance-enhancing features such as superior on-the-fly image compression, HTTP/2 support, hotlink protection, and additional security.
For a faster WooCommerce store, we recommend that you get a fast CDN. Some popular CDNs you can check out are:
Most WordPress themes and plugins load scripts and stylesheets on all your site’s pages. They load these assets even when they’re not used on the page.
As an example, Contact Form 7 loads its scripts and stylesheets on every page. Its forms may only be used on the contact page, but the assets load on all the pages. Quite unnecessary!
Stripping these unused assets from pages will help you reduce bloat and speed up page load times. WooCommerce and its extensions (e.g., Smart Coupons and Follow-Ups) are susceptible to this issue.
For instance, it’s unnecessary to load scripts related to payment gateways on your store’s homepage or shop page. You can restrict such scripts to load only on the checkout and order confirmation pages. Likewise, eliminate scripts and styles for sliders and carousels from your checkout page.
If you want to know which assets to eliminate, look at the waterfall chart in your website speed test report. It’ll give you an idea about the unnecessary assets that are being loaded.
GTMetrix’s Waterfall Chart
The Network tab under Chrome browser’s DevTools is also a good place to get started. It’ll give you a comprehensive view of how and what a web page loads.
Use the Network tab in Google Chrome DevTools
Strip the scripts and styles that aren’t necessary for the functioning of the page. Start by optimizing your homepage and landing pages, since these are the first points of entry for most of your users.
You can use wp_dequeue_script and wp_dequeue_style functions to remove scripts and styles you don’t need. An easy way to achieve the same is through a plugin called Asset CleanUp: Page Speed Booster.
Clean up your WordPress assets
Asset CleanUp scans for all scripts and stylesheets that will be loaded onto a page. You can disable the ones that aren’t used on the page. Test the page for proper design and functionality once you finish making the changes.
Unloading Stripe payment gateway script with Asset Cleanup
The pro version of the plugin allows you to set async or defer attributes to the assets. Applying this setting removes JavaScript from the page’s critical rendering path. It should help with improving your site’s perceived page load time.
Another advantage of eliminating unnecessary CSS and JS assets is that your website will make fewer HTTP requests.
For a free alternative, you can use the combination of Autoptimize and Async JavaScript plugins to get the same results. If you go with Autoptimize plugin here is our full step by step guide on the best settings.
If we were writing this article a few years ago, we would’ve titled this section “Reduce the Number of HTTP Requests.” Thanks to substantial improvements in how browsers communicate with websites (and vice-versa), the need for this optimization is now obsolete.
HTTP 1.1 was the first major update to the HTTP protocol, and it was finalized way back in 1997. That’s before social media, streaming services, smartphone apps, and even WordPress. The web has grown exponentially since then.
HTTP/2 improved upon the HTTP 1.1 protocol and made its entry in 2015 to keep up with the growing demands of the internet. It brought with it amazing improvements in speed, efficiency, and security.
HTTP 1.1 vs HTTP/2 (Image source: Cloudflare)
The performance increase with HTTP/2 is due to multiple reasons:
All that jazz amounts to one crucial advantage: making websites load faster, even when they host various types of resources.
Typically, WooCommerce stores serve a lot of resource-heavy assets such as images, stylesheets, and scripts. Sites like these will benefit greatly by switching to HTTP/2.
You can use the HTTP/2 test tool by KeyCDN to check whether your site is configured to work with HTTP/2. As of now, every major browser supports HTTP/2. There’s no reason you shouldn’t be taking advantage of its massive performance benefits.
If your hosting provider doesn’t support HTTP/2 yet, start looking for a new one. Kinsta supports HTTP/2 and TLS 1.3 on all of its servers and CDN.
Furthermore, HTTP/3 is just around the corner and is set to make websites load even faster.
Caching is temporarily storing resources (cache) from one request so that subsequent requests can be executed quickly. The cache can be stored either on the server or on the user’s device.
It’s one of the easiest ways to speed up your WooCommerce store. And it’s also the most important one.
How web caching works
If everything works smoothly, all the above steps should take a few seconds at max to execute.
But that’s just one request from a single user. What if there are multiple requests from thousands of users at the same time? That will put an enormous load on the server, eventually leading to a slower website.
This is where caching comes to the rescue. It reduces the amount of work required to generate a pageview, thus reducing WordPress’ dependency on PHP and a database. Caching makes WordPress perform almost as fast as static websites, if not the same.
There are 2 major types of web caching, each with their own subsets:
Server-Side Caching
Client-Side Caching
Caching not only makes the website load faster, but it also reduces load on the server. Kinsta’s in-depth article on WordPress cache is a great resource for a detailed explanation.
If your WooCommerce store is hosted with Kinsta, caching is taken care of at the server-level. Hence, you need not use a caching plugin.
Kinsta configures cache rules to work seamlessly with WooCommerce. This ensures that your users have a smooth checkout experience with no hiccups.
WordPress load times after migrating to Kinsta’s new servers
If your hosting provider doesn’t handle caching at the server-level, then you need to depend on third-party caching plugins to do the work for you. While they aren’t an ideal solution, something is always better than nothing.
Here are our top WordPress caching plugin recommendations:
For more options, check out Kinsta’s post on WordPress caching plugins.
A database is an organized collection of all your website’s data. In a WooCommerce store, it includes:
Every time a user visits your store, they’re requesting your site content, which is mostly static and doesn’t change much. But when they’re placing an order, they’re making a dynamic request.
If you don’t optimize your store’s database, it may take too long to process these requests. Ultimately, a slow server response time leads to a slow website. Hence, you must clean up and optimize the database by removing unnecessary junk.
Here are 6 ways to speed up and fine-tune your WooCommerce database.
If your WooCommerce store has been up for quite a while, its pages, posts, and products will be filled with old revisions. It’s time to clean these up.
The easiest way to do it is through plugins such as WP-Sweep or WP Rocket.
Deleting old revisions with WP Rocket
If you’re handy with WP-CLI, then you can also connect to your server via SSH and run a few simple commands to do the same. Here’s how you can do it.
You can avoid having numerous old revisions by limiting the number of revisions for posts and pages. If you’re prone to updating your site content often, this will help you keep revisions from going out of hand.
An easy way to set the limit is by adding the below code snippet below to your wp-config.php file. Make sure to add it before the line where ABSPATH is defined.
define('WP_POST_REVISIONS', 15);
I’ve set the limit as 15 in the code above. You can change it to any number of revisions you want, but try to keep it below 15.
Alternatively, you can use a free plugin such as WP Revisions Control to do the same.
Set the number of revisions with WP Revisions Control
You can disable revisions from your site altogether. All you need to do is add the following code to your wp-config.php file. As before, ensure that you add this snippet above the line where ABSPATH is defined.
define('WP_POST_REVISIONS', false);
Or you can use a free plugin such as Disable Post Revision to do the same with a single click.
Before disabling revisions, we suggest you delete all the old revisions that are still present. This way, your site’s database will be completely free of revisions going forward.
Transients are cached data stored with a custom name and an expiration period. They’re usually stored in the WordPress database under the wp_options table.
Transients are similar to Options, except they have an added property of expiration time. They are useful to store temporary data such as responses from a remote API or large queries.
The WordPress Transients API defines how to handle transients and delete expired transients automatically. However, things don’t always go as planned.
Sometimes, a corrupt transient cache can create almost a million junk entries with no end in sight. Customer sessions can rack up over time, creating thousands of unnecessary rows in your database tables. In such cases, a bloated database can bring your site to its knees.
The free Delete Expired Transients plugin is an easy way to get rid of all expired transients.
Deleted all your expired transients easily
Your WooCommerce database stores everything that’s needed to run your ecommerce store. As data gets added, removed, and moved around the tables in your database, it becomes inefficient and ends up storing many things that aren’t important to run your store.
You need to clear out this unnecessary data by cleaning up your database tables. The wp_options table, in particular, is prone to getting bloated and hurting database performance.
The wp_options table in WordPress database
Database housekeeping is key to keeping your WordPress site running as swiftly as possible.
Optimizing your database manually is a time-consuming process. You can use the free WP-Optimize plugin to check which database tables have unnecessary data and delete those wasted spaces. It can also retrieve storage space lost to data fragmentation.
You can schedule WP-Optimize to clean up and optimize your database regularly.
WooCommerce themes and plugins come with a lot of cool features that seem great from the outset but end up crumbling the database.
One such example is using “Popular Products” and “Related Products” plugins. These features can cause enormous sitewide queries, especially if you have many products. If you need these features, try to insert them manually into your pages. Plugins such as Advanced Custom Fields can help here immensely.
Kinsta inserts its ‘Related Content’ posts manually
Another example is image optimization plugins that compress images on the same server where the site is hosted, rather than do it externally. This ends up using a lot of your server’s resources.
Social Warfare plugin can tax the server resources
Also, stay away from plugins that add counters to your site. For example, adding the number of views/posts/comments beside a username. A lengthy discussion with multiple users involved will stress your database to crunch these numbers.
This advice holds true for using social counters too. Minimize the use of auto-generated counters to maximize database performance.
Need a blazing-fast, reliable, and fully secure hosting for your ecommerce website? Kinsta provides all of this and 24/7 world-class support from WooCommerce experts. Check out our plans
Like housekeeping, fine-tuning your WordPress database is an ongoing process.
Keeping this in mind, Kinsta has implemented an automated system to combat database performance issues. Based on your site’s needs, the automated system scans and fine-tunes your MySQL database once per week to ensure peak database performance. If the system detects something out of the ordinary that can’t be fixed automatically, it notifies the sysadmin team to take immediate action.
If your site is hosted somewhere else, here are a few database optimization plugins to make your job easier:
Reminder: Always take a backup before editing your database or WordPress core files.
As of January 2020, there are over 4 billion internet users in the world. There are almost as many mobile internet users. It’s expected to grow to 5+ billion by 2024.
There are billions of us (Image source: Statista)
Mobile devices overtook desktops in global website traffic in 2019, generating 52.6% of the total pageviews. In some countries such as India and Nigeria, mobile phones account for 70%+ of web page views.
Mobile traffic from Google Analytics
According to a study involving 500+ million online shoppers across 37 countries, smartphones accounted for 65% of site visits and 46% of ecommerce orders.
Mobile shopping has massive growth potential (Image source: Statista)
Surprisingly, the conversion rate for mobile phones is less than half that of desktops. There’s phenomenal room for growth here.
Speed counts a lot for mobile shoppers (Image source: Think with Google)
You can start by making your WooCommerce store mobile-friendly. You can use Google’s Mobile Friendly Test tool to check whether your site passes the minimum mobile usability standards.
Google’s Mobile Friendly Test
The test will show you a snapshot of how your website looks on a mobile device. It’ll also list any mobile usability issues if it finds any.
The easiest way to make your WordPress website mobile-friendly is to use a responsive theme. All the themes mentioned earlier in this post are responsive out of the box and look great on mobile devices.
Mobile shoppers don’t enjoy scrolling endlessly. Hence, keep your store pages as lean as possible. Don’t overcrowd them with too much content.
If you have loads of products listed on your store, make it easier for your mobile shoppers to find them through search. You can install the WooCommerce Product Search plugin to help your customers find products swiftly with live product filters.
Simplify product search with filters (Image source: WooCommerce)
Finally, streamline the checkout experience for your online shoppers. The fewer the steps to place an order, the better the shopping experience. Here are a few WooCommerce extensions that can help you with this:
Easy mobile checkouts with Bolt
Ultimately, mobile shopping is more than just about making a purchase. Many users use it primarily to look up product information and check/compare prices. Make your online store experience great for your users on their mobile devices.
When a user makes any changes to their shopping cart, WooCommerce uses the Get Refreshed Fragments AJAX request to update the shopping cart contents dynamically. Refreshing the cart page without reloading it seems great from a user experience perspective.
But most times it slows down websites, mainly those hosted on shared servers. Plus, a lot of sites don’t end up using this feature.
Just to verify, we tested an up-to-date WooCommerce store on Pingdom Tools and here are the results:
That’s a lot of wait time for one request
Despite being just 1.1 KB in size, the wc-ajax=get_refreshed_fragments request takes 0.76 seconds to execute. If your site takes 3 seconds or less to load, that’s over 25% of the page load time. This test site is hosted on a cloud VPS, so you can imagine the load times on a cheaper hosting plan.
This post by WebNots covers the issue in greater detail. You can use the free Disable Cart Fragments or Disable Cart Fragments by Optimocha plugins to disable this taxing request.
If you disable this request, then it’s recommended enabling the option ‘Redirect to the cart page after successful addition’ in your WooCommerce → Products settings panel.
Remember to enable this setting afterward
Enabling this behavior will ensure that the user is redirected to the Cart page after adding a product to their cart.
Speed isn’t an important factor for only your store’s frontend. A snappy backend is just as crucial to manage your store with ease and make quick changes whenever needed.
Working efficiently on your WooCommerce admin panel is the key to being productive. It also frees up your time to do more essential stuff for your WooCommerce store’s success, like online marketing.
Below are a few ways to fix a slow WooCommerce dashboard.
Does the problem only occur with the WordPress admin dashboard and not the whole website? If it’s the latter, then apply all the optimizations listed earlier first.
Why? Because in most cases, making your WooCommerce store load faster on the frontend will optimize the backend too. We can attribute this to freeing up resources on your server.
If your admin dashboard lags even after optimizing the frontend, then carry on to the following suggestions.
Make sure to update WordPress, WooCommerce, plugins, extensions, and the theme frequently. If a theme or plugin is no longer supported by its developers, then it’s time to consider ditching them.
Likewise, if a theme/plugin adds unnecessary bloat to your dashboard, start looking for better alternatives. For instance, you might want to consider alternatives to plugins that serve aggressive ads in your dashboard.
Example of banner in WordPress admin
This issue is so prevalent that there are plugins solely dedicated to removing bloat from some of the most popular WordPress plugins.
Caching plugins are a great way to speed up your WordPress site. However, if not configured properly, they can lead to unexpected results. That includes slowing down your backend.
For instance, W3 Total Cache is one of the most popular caching plugins for WordPress. It’s free, supports plenty of caching options, does JS and CSS minification, integrates with a CDN, and is used by 1+ million websites.
Cache options in W3 Total Cache
W3 Total Cache features the following cache options:
Having a lot of options is confusing, especially to beginners who don’t understand what each type of caching does.
Object and database caching speed up the website by reducing the number of database queries, but they do so at the cost of offloading the work to the server’s memory.
Ideally, this shouldn’t pose a problem if your hosting server is smart or powerful enough. For instance, if your WordPress site is hosted with Kinsta, you don’t need to worry about caching as it’s already implemented at the server level.
Unfortunately, that’s not the case with every hosting provider.
In that scenario, you need to depend on a third-party caching plugin such as W3 Total Cache. Its simple settings make it super easy to enable all types of cache with just a single click.
In the W3 Total Cache → General Settings panel, disable object cache and/or database cache. Then check whether you see any improvements in your admin panel’s responsiveness.
Disable Database and Object Cache
Experimenting with the cache isn’t as simple as ticking or unpicking options in your plugin settings. You should also check whether your site works properly after making the changes and flushing your old cache.
Kinsta customers can boost their overall optimization by taking advantage of the code minification feature that is built right into the MyKinsta dashboard. This feature allows customers to enable automatic CSS and JavaScript minification with a simple click, effectively speeding up their sites with zero manual effort.
Some WordPress plugins are a great resource hog on your web server. They end up using most of your server’s CPU and RAM.
You can use the free Query Monitor plugin to find the troublesome plugins. It’ll show you all the scripts, styles, and HTTP API calls that are being loaded by your website, along with their size and loading time. Look out for the ones that have the most number of requests and the slowest load times.
On the test site below, the Classic Editor plugin loads the slowest on the admin side. Other plugins like Loginizer, All-in-One WP Migration, and WP Bakery (formerly Visual Composer) also show up as potential bloat.
Query Monitor helps you troubleshoot performance issues
We found that the migration and Classic Editor plugins are unnecessary. Removing these two plugins fixed the admin speed considerably.
WooCommerce stores with an international audience use translation plugins like WPML to serve the site dynamically in multiple languages. It’s a great plugin with a lot of features, but it can also slow down your admin backend considerably.
You can gain some performance advantage by switching to a lean translation plugin such as Polylang. It doesn’t have as many features but works great for most use cases.
Plugins that have a lot of ongoing processes/scans will slow your WordPress backend. Some examples include sitemap generators, analytics graphs and charts, page builders, and chat plugins.
If you install Query Monitor, remember to uninstall it when done as it uses a lot of server resources to perform the scans.
CDN helps to serve your WooCommerce store at lightning speed to users all around the world. It does this by saving a snapshot of your site’s resources and delivering them from the nearest server to the user.
Most CDNs disable caching on the WordPress backend by default. But some CDNs don’t, and this can slow down your store’s admin panel drastically. In such a case, you need to exclude your admin dashboard from the CDN’s cache to improve its performance.
If you’re using Cloudflare, you can set up a Page Rule to disable Cloudflare features on WordPress admin pages. Here’s how to do that:
Cloudflare Page Rules to bypass WordPress admin
It should take around 3 minutes for the settings to take effect.
If you’re using KeyCDN, then you can use their WordPress Cache Enabler Plugin to do the same. For other CDNs, please reach out to their support to sort this out.
The WordPress Heartbeat API enables near-real-time updates by maintaining a regular connection between your browser and your server. The API sends requests to the server every 15-60 seconds and then triggers events (or callbacks) upon receiving data.
It allows some amazing features such as autosaving posts, locking posts, and login expiration warnings. However, when you’re logged in as an admin, sending a few requests to the server every minute can slow down your admin panel.
WP Rocket’s free Heartbeat Control plugin allows you to manage the frequency of these API requests on the dashboard, frontend, and post editor. It even gives you the option to disable the API altogether.
Modify or disable WordPress Heartbeat API
Start by increasing the frequency of time. If that doesn’t fix your WooCommerce backend’s speed issues, consider disabling the heartbeat API.
If applying all the above optimizations still doesn’t fix your WooCommerce store’s speed issues, then…
Just like running a car with flat tires, no matter how many optimizations you make, your site won’t get any faster if it’s hosted on a lousy server. A significant portion of your site’s performance depends on the quality of your hosting.
There are different types of hosting for WordPress sites which fall under two main category: Managed and Unmanaged. The first is perfect for most users, as the hosting provider handles all the server optimizations for WordPress. The latter is better suited for technically proficient users who can tweak and manage the server on their own.
For a WooCommerce website, go for Managed WordPress Hosting. Keep in mind that managed hosting tends to be more expensive than unmanaged hosting.
You can choose from 4 major types of Managed WordPress Hosting. Each comes with its own pros and cons, so select the one that aligns with your budget and goals. I’ve compared them in the infographic below for various features.
4 main types of Managed WordPress Hosting
Each type of hosting can be offered under multiple plans at different price points. So, when scouting for a hosting within your budget, look at the features offered to decide whether it fulfills your requirements.
WooCommerce sites are incredibly dynamic by nature. They generate a lot of data and requests that cannot be cached.
For instance, the checkout page is unique for each user and cannot be served from a cache. As a result, the server needs to be robust enough to run your site smoothly, even if your site attracts low traffic.
The recommended features you should look out for when deciding on a WooCommerce hosting plan are:
With these requirements in mind, you can safely eliminate Shared Hosting.
A Virtual Private Server (VPS) is like shared hosting, except you have a virtual space in a shared server dedicated solely to you. If you’re on a strict budget, you can get started with a mid-range VPS plan. However, if your site attracts more traffic, then you’ll have to upgrade soon.
This leaves us with Cloud Hosting and Dedicated Server options. Both are great for WooCommerce sites if they fulfill your requirements.
The prices for dedicated server plans are towards the higher side as compared to cloud hosting plans, which can range from ~$50/month to thousands of dollars per month.
Kinsta’s business cloud hosting plans check off all the recommended WooCommerce requirements. Its container-based hosting is perfect for WooCommerce as it scales automatically to handle sudden traffic and load surges.
If you want to extend the features further, Kinsta offers add-ons such as Redis, extra backups, Nginx reverse proxy, and more.
Below is an example of performance gains after Kinsta migrated an ecommerce site to Google Cloud Platform’s new Compute-Optimized VMs (C2).
Massive performance benefits after migration
From ~665 ms to ~500 ms, that’s a whopping ~25% increase in performance!
If you’re spending a considerable amount of money on marketing, you’re pushing away all your leads if your site is slow, so it’s well worth opting for the fastest WordPress hosting solutions.
Ultimately, you’re better off spending a few extra dollars every month on quality hosting, rather than spending hours pulling out your hair and wondering why your site still has a high bounce rate.
Time is literally money for an ecommerce site. A fast WooCommerce store boosts user experience, SEO, revenue, and ROI.
While you don’t have to follow all the speed optimization tips listed in this post, we recommend you to go through all of them. This will help you identify any bottlenecks in your site. No one likes to wait for a site to load. Let’s speed up WooCommerce!
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
Original article source at: https://kinsta.com/
1661302740
Fomantic (Semantic) UI wrapper for Shiny
With this library it is easy to wrap Shiny with Fomantic UI (previously Semantic). Add a few simple lines of code to give your UI a fresh, modern and highly interactive look.
library(shiny)
ui <- fluidPage(
div(
div(
a("Link"),
p("Lorem ipsum, lorem ipsum, lorem ipsum"),
actionButton("button", "Click")
)
)
)
library(shiny.semantic)
ui <- semanticPage(
div(class = "ui raised segment",
div(
a(class="ui green ribbon label", "Link"),
p("Lorem ipsum, lorem ipsum, lorem ipsum"),
actionButton("button", "Click")
)
)
)
We show how shiny.semantic
can be used to style an app and change it’s look.
See more examples with code in the examples
folder:
You can install a stable shiny.semantic
release from CRAN repository:
install.packages("shiny.semantic")
and the latest version with remotes
:
remotes::install_github("Appsilon/shiny.semantic@develop")
(master
branch contains the stable version. Use develop
branch for latest features)
To install previous versions you can run:
remotes::install_github("Appsilon/shiny.semantic", ref = "0.1.0")
Firstly, you will have to invoke shinyUI()
with semanticPage()
instead of standard Shiny UI definitions like e.g. bootstrapPage()
. From now on, all components can be annotated with Fomantic UI specific CSS classes and also you will be able to use shiny.semantic components.
Basic example for rendering a simple button. will look like this:
library(shiny)
library(shiny.semantic)
ui <- semanticPage(
title = "My page",
div(class = "ui button", icon("user"), "Icon button")
)
server <- function(input, output) {}
shinyApp(ui, server)
For better understanding it’s good to check Fomantic UI documentation.
Note #1
At the moment you have to pass page title in semanticPage()
semanticPage(title = "Your page title", ...)
Note #2
The shiny
package works with Bootstrap library under the hood. shiny.semantic
uses Fomantic UI. Sometimes using both of these libraries may cause troubles with rendering specific UI elements. That is why by default we turn off Bootstrap dependencies.
However, you can switch off suppressing bootstrap by calling semanticPage(suppress_bootstrap = FALSE, ...)
We welcome contributions of all types!
We encourage typo corrections, bug reports, bug fixes and feature requests. Feedback on the clarity of the documentation and examples is especially valuable.
If you want to contribute to this project please submit a regular PR, once you’re done with new feature or bug fix.
Changes in documentation
Both repository README.md file and an official documentation page are generated with Rmarkdown, so if there is a need to update them, please modify accordingly a README.Rmd file and use “Knit”.
Documentation is rendered with pkgdown
. Just run pkgdown::build_site()
after rendering new README.md.
Changes in vignettes
If you modified or added a new vignette, please rebuild them with devtools::build_vignettes()
.
Important:
Please follow the code style from out styleguide.
We have a Contributor Code of Conduct. Make sure to check it and to follow it.
We used the latest versions of dependencies for this library, so please update your R environment before installation.
However, if you encounter any problems, try the following:
Up-to-date R language environment
Installing specific dependent libraries versions
install.packages("shiny", version='0.14.2.9001')
Some bugs may be related directly to Semantic UI. In that case please try to check issues on its repository.
Some bugs may be related to Bootstrap. Please make sure you have it suppressed. Instructions are above in How to use it? section.
dsl.R
to make using this package smootherAppsilon is the Full Service Certified RStudio Partner. Learn more at appsilon.com.
Get in touch support+opensource@appsilon.com
Author: Appsilon
Source Code: https://github.com/Appsilon/shiny.semantic
License: Unknown, MIT licenses found
1659757740
Logecom is simple yet powerful and elegant middleware-based logging utility inspired by Nodejs Express library.
There are many logging libraries present with different approaches and interfaces. If you want to migrate from one logger to another, you must refactor lots of entry points in your application where particular logger is initialized or used.
The idea is to abstract from logging process as much as possible and to define simple common interface with minimal overhead and give a stack to implement any logging pipeline with desired functionality in single place.
Basically there is the only interface introduced for any log processing: LogTranslator
By implementing it in different ways it is possible to achieve any result. You can transform, format, collect, print or send, and even use another logger! - anything you want inside the pipeline.
Implementing LogTranslator
by Logecom
itself makes it possible to create complex logs translation logic when one logger pipeline can be applied up to another (conditionally, for example) if needed ;)
There are several LogTranslator
implementations available "out of the box" covering the most common logging use cases:
HttpFormatter
- Allows to log HTTP interaction easilyConsoleTransport
- Default console printer. Provide simple and compact log entries formatting with different ways of printing: using stdout
, stderr
, developer.log()
or print()
methodsTo start using Logecom logger first you need to configure a desired pipeline. By default there is no any configuration. Typically in addition to simple textual events you would likely to want at least to find and format HTTP log entries and catch all unhandled errors.
For Flutter application this configuration may look like this:
void main() {
final method = PrintingMethod.stdErr;
// typical logging pipeline
Logecom.instance.pipeline = [
HttpFormatter(
printRpcContent: config.logPrintRpcContent,
hideAuthData: config.logHideAuthData,
colorize: method == PrintingMethod.stdErr || method == PrintingMethod.stdOut,
),
ConsoleTransport(
config: ConsoleTransportConfig(
printingMethod: method,
timestampFormat: method == PrintingMethod.print ? '' : 'yyyy-mm-dd HH:MM:ss.S',
),
),
];
// this logger us used to specify uncategorized (Global) events
final logger = Logecom.createLogger('Global');
FlutterError.onError = (FlutterErrorDetails details) {
logger.error('Flutter Error', [details.exception, details.stack]);
};
void onUnhandledException(Object error, StackTrace stack) {
logger.error('Unhandled Exception', [error, '\n$stack']);
}
Isolate.current.addErrorListener(RawReceivePort((List<dynamic> pair) async {
final error = pair.first;
final StackTrace stack = pair.last;
logger.error('Unhandled Isolate Error', [error, '\n$stack']);
}).sendPort);
/// all application code must be inside this function
/// to handle ALL errors properly
void bootstrap() {
// [AppView] is your application entry widget
runApp(AppView());
}
runZonedGuarded(bootstrap, onUnhandledException);
}
To use common logging API you need to create a specific Logger instance with desired category using Logecom.createLogger()
factory method. Category usually specifies the events source. A good practice would be to use current class or package name for this purpose.
class AppViewState extends State<AppView> {
// it is possible to pass class type or any string desired
final logger = Logecom.createLogger(AppView);
@override
void initState() {
super.initState();
// use logger instance to log events
logger.log('State initialized');
}
}
Using default ConsoleTransport
the code above will print this:
2021-06-19 22:12:43.326 [LOG] AppView State initialized
NOTE: If you DO NOT see any logs: Check that correct
printingMethod
is set toConsoleTransportConfig
. Not all printing methods are possible to use in all environments. For example, you will NOT see any logs if you setPrintingMethod.stdErr
for Flutter application that runs inside the iPhone Simulator! This is a known issue. Please refer toPrintingMethod
inline documentation for more details.
Dio is a popular HTTP client library available in pub.dev. To log its requests you can use Interceptor
implementation like this:
import 'package:dio/dio.dart';
import 'package:logecom/logecom.dart';
class DioLogInterceptor extends Interceptor {
DioLogInterceptor(this._logger);
final Logger _logger;
final _requestStartTime = Map<RequestOptions, DateTime>();
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
_requestStartTime[options] = DateTime.now();
handler.next(options);
}
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
final startTime = _requestStartTime[err.requestOptions] ?? DateTime.now();
_requestStartTime.remove(err.requestOptions);
_logger.log(
'HTTP',
HttpLogContext(
method: err.requestOptions.method,
url: err.requestOptions.uri,
statusCode: err.response?.statusCode ?? -1,
statusMessage: err.response?.statusMessage ?? err.message,
duration: DateTime.now().difference(startTime),
responseData: err.response?.data,
requestData: err.response?.requestOptions.data,
headers: _getHeaders(err.requestOptions.headers),
),
);
handler.next(err);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
final startTime = _requestStartTime[response.requestOptions] ?? DateTime.now();
_requestStartTime.remove(response.requestOptions);
_logger.log(
'HTTP',
HttpLogContext(
method: response.requestOptions.method,
url: response.requestOptions.uri,
statusCode: response.statusCode ?? 0,
statusMessage: response.statusMessage ?? '',
duration: DateTime.now().difference(startTime),
responseData: response.data,
requestData: response.requestOptions.data,
headers: _getHeaders(response.requestOptions.headers),
),
);
handler.next(response);
}
Map<String, String> _getHeaders(Map<String, dynamic> headers) {
return headers.map((key, value) {
if (value is String) {
return MapEntry(key, value);
} else if (value is List) {
return MapEntry(key, value.join('; '));
} else {
return MapEntry(key, value.toString());
}
});
}
}
Usage example is as follows:
class AuthService {
AuthService() {
client.interceptors.addAll([
DioLogInterceptor(logger),
]);
}
final logger = Logecom.createLogger(AuthService);
final client = Dio();
...
}
Enjoy ;)
Run this command:
With Dart:
$ dart pub add logecom
With Flutter:
$ flutter pub add logecom
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
logecom: ^0.0.5
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:logecom/logecom.dart';
Author: Koldoon
Source Code: https://github.com/koldoon/logecom_dart
License: MIT license
1657302120
composer require ali1/brute-force-shield
When applying protection, a Ali1\BruteForceShield\Configuration object can be provided.
$configuration = new Configuration();
$configuration->setTimeWindow(600)
->setTotalAttemptsLimit(10);
Configuration method | Details |
---|---|
setTimeWindow(int $timeWindow) | Time in seconds until Brute Force Protection resets (default: 300) |
setTotalAttemptsLimit(int $totalAttempts) | Number of attempts before blocking further challenges (default: 8) |
addUnencryptedKey(string $keyName) | By default, all entered user data is irreversibly hashed when prepared for storage. Use addUnencryptedKey for each key for which you want the data to be stored plaintext to aid debugging or security logging (i.e. usernames) |
setStricterLimitOnKey(string $keyName, int $limitAttempts) | This optional method is useful in id/password type scenarios. You can configure the shield to further limit the number of attempts if using the same id/username repeatedly (i.e. use setStricterLimitOnKey('username', 7) and setTotalAttemptsLimit(10) to allow 7 attempts for a user, and then another 3 if user tries a different username) |
As you will need your own architecture to store data and log blocked events, it is recommended to create a method, function, component or middleware to use this library.
Check out this CakePHP component as an example of a helper method you could use.
However if you want to use it directly, here is an example:
public function login()
{
// prior to actually verifying data
$bruteConfig = new Configuration();
$bruteConfig->setTotalAttemptsLimit(10)
->setStricterLimitOnKey('username', 7)
->addUnencryptedKey('username');
$cacheKey = 'BruteforceData.login.' . str_replace(':', '.', $_SERVER['REMOTE_ADDR']);
$userDataRaw = Cache::read($cacheKey); // replace with your way of retrieving stored user data
$shield = new BruteForceShield();
$userData = $userDataRaw ? json_decode($userDataRaw, true) : null;
$userData = $shield->validate($userData, $_POST, $bruteConfig);
Cache::write($cacheKey, json_encode($userData)); // replace with your way of storing user data
if (!$shield->isValidated()) {
Log::alert(
"Bruteforce blocked\nIP: {$this->getController()->getRequest()->getEnv('REMOTE_ADDR')}\n",
json_encode($userData)
); // replace with your own method of logging
throw new TooManyAttemptsException(); // replace with your way of error handling and stopping execution
}
// now you can process the login attempt in the normal way
}
Author: Ali1
Source Code: https://github.com/Ali1/BruteForceShield
License: MIT license
1650055620
Using powerful machine learning algorithms is easy using Ray.io and Python.
https://github.com/ClarityCoders/RayTutorial
1650042300
優れたフォームを構築することは、現代のWeb開発では常に困難な作業と見なされてきました。外側のフォームは、選択ボックス、テキストフィールド、ラジオボタン、およびチェックボックスのグループにすぎません。ただし、テーマ設定、検証、およびユーザーにとって直感的なものにすることは、すぐにイライラする可能性があります。
複雑なフォームの処理はすべての開発者にとって面倒であり、フロントエンド開発の主要な問題点の1つになっています。複数の状態を制御し、それらを簡単に入力できるように相互作用させる機能の必要性から、Formik、React Hook Form、Veevalidate、Vuelidate、FormKitなどのライブラリが誕生しました。
この投稿では、FormKitと、検証、スタイル設定、ローカリゼーションを使用してVue.jsで強力なフォームを作成するのにどのように役立つかを紹介します。
FormKitは、開発者のエクスペリエンスを一流に保ちながら、Vueであらゆる種類のフォームを開発するのに役立つ強力なフレームワークです。FormKitの背後にあるチームは、人気のあるVueFormulateライブラリで得られたものと同じです。このライブラリに精通している場合は、Vueでフォームを作成するための革新的なアプローチを覚えているでしょう。
VueFormulateは、フォーム要素を作成するために小道具とスロットを多用する単一のコンポーネントを開発者に提供しました。このアプローチにより、フォームの作成、処理、検証が簡単になりました。
FormKitはVueFormulateの拡張バージョンであり、開発者に微妙な魔法のタッチで同じ利点を提供します。今日、FormKitは、開発者が優れたフォームを作成できるように作成された本格的なフレームワークとしての地位を確立しています。
プロジェクトにFormKitをインストールするには、FormKitのインストールドキュメントの最初の手順に従う必要があります。
FormKitは、フォームを作成する2つの簡単な方法を提供し<FormKit/>
ます。コンポーネントを使用する方法とJSONスキーマからフォームを生成する方法です。
<FormKit/>
FormKitを使用すると、単一のFormKitコンポーネントを使用して、高度に制御可能なテキストフィールド、選択ボックス、およびその他のフォーム要素を作成できます。このコンポーネントには、フォームに追加する入力要素を高度にカスタマイズできる特定の小道具が付属しています。
<template>
<FormKit
label="Short word"
type="text"
help="Type any short word"
validation="required|matches:/^[a-zA-Z]+$/|length:5"
value="Hello"
/>
</template>
<input>
この単一のコンポーネントは、HTMLのタグがさまざまなtype
属性(つまり、<input type="text">
対)を使用する方法と同様に、他の入力タイプを作成できます<input type="checkbox">
。
このアプローチは、開発者に学習するAPIを少なくするだけでなく、最も直感的な方法で提供するため、強力です。FormKitコンポーネントは、フォームの作成に必要な明示的な小道具を提供し、表示する必要のあるすべての属性(小道具)をレンダリングされたHTML入力に渡すことができます。
入力をフォーム(または複数のフォーム)のように動作させる必要があるほとんどの場合、<FormKit/>
コンポーネントは、子のFormKitコンポーネントからすべての値をアクティブに収集するラッパーになることができます。name
結果のデータオブジェクトのプロパティ名として、各入力のを使用します。このラッパーを使用すると、Vueの入力に付加されたv-model属性を使用する場合と同様に、フォームの値を取得または編集することもできます。
これを行うには<FormKit type="form">
、グローバルフォームが必要な場合、およびフォーム<FormKit type="group">
の一部をグループ化する場合に備えて、入力を単にラップします。これは、フォーム要素を相互に作用させたり、フォームの状態をリセットしたり、APIに送信したりするのに非常に役立ちます。これは、複数のソースから複数の変数をリッスンする必要があるため、バニラVueでは開発者にとって不便になる可能性があります。
単一の入力が有効でない場合、ラッパーはフォーム全体を無効にし、送信を不可能にします。
<FormKit
type="form"
submit-label="Login"
:errors="['No server.', 'More errors here']"
>
<FormKit type="email" label="Email" />
<FormKit type="password" label="Password" />
</FormKit>
動的フォームは、フォーム処理で高い需要がある機能です。多くの場合、開発者は、事前に指定されていない、または回答と検証をその場で作成できるカスタム構造に従うフォームを作成する必要があります。
<FormKitSchema>
FormKitは、コンポーネントとその:schema
プロップを使用してこの優れた機能を提供します。
<script setup>
const schema = [
{
$formkit: 'email',
label: 'Email address',
validation: 'required'
}
]
</script>
<template>
<FormKit type="form">
<FormKitSchema :schema="schema" />
</FormKit>
</template>
FormKitのJSONスキーマは非常に強力です。上記のような単純なフォームの作成から、最も複雑なフォームまでさまざまです。スキーマは、条件付きロジック、ブール演算子、ループ、スロット、データスコープなどの一流の機能をサポートしており、生成されたフォームを必要に応じてカスタム化できます。
<FormKitSchema
:schema="[
{
$formkit: 'email',
label: 'Email address',
}
]"
/>
上記のコードは、単一の電子メール入力を作成します。これは、検証、パスワード、インタラクションなどで拡張できます。
FormKitは、フォーム用に事前に作成された20を超える検証ルールを使用および組み合わせることにより、フォームを簡単に検証するのに役立ちます。これらのルールにはさまざまな使用方法があるため、開発者はプロジェクトに最も適切と思われるものを選択できます。
<!-- validation as string -->
<FormKit
type="text"
label="Number"
validation="required|number|between:0,10"
validation-visibility="live"
help="Enter a number between 0 and 10."
/>
<!-- validation as array -->
<FormKit
type="text"
label="Phone"
placeholder="xxx-xxx-xxxx"
:validation="[['required'], ['matches', /^\d{3}-\d{3}-\d{4}$/]]"
validation-visibility="live"
:validation-messages="{
matches: 'Phone number must be formatted: xxx-xxx-xxxx',
}"
/>
FormKitでは、ルールは拡張可能でカスタマイズ可能であり、検証を処理するためにサードパーティのライブラリを必要としません。フォームのカスタムルールの作成は、引数として値を取得し、内部の条件に従ってブール値を返す関数を作成するのと同じくらい簡単です。
// ./validation-custom-rules/yes-rule.js
// ensures that the value is always yes
export default function yes(node) {
return node.value === 'yes' || node.value === 'YES'
}
// main.js ---------
import { createApp } from 'vue'
import App from './App.vue'
import { plugin, defaultConfig } from '@formkit/vue'
import yes from './my-custom-rules/yes-rule'
// prettier-ignore
createApp(App).use(plugin, defaultConfig({
rules: { yes },
})).mount('#app')
FormKitでの検証は、開発者が優れたフォームを作成できるように簡素化されていますが、私たちが享受しているシンプルさを維持しながら、適切にスケーリングできるように構築されています。フォームがより複雑になり、より多くのカスタムルールとフィールド間のより大きな相互作用が必要な場合、FormKitとVueの非常識なコンポーネントのモジュール性を組み合わせることで、コードをシンプルで理解しやすくしながら、複雑なフォームと状態を作成できます。
ネイティブフォームのスタイリングは簡単ではありません。チェックボックス、テキスト領域、テキストフィールド、およびラジオボタンはすべて<input>
フィールドですが、同じスタイルにすることはできません。FormKitは、Genesisと呼ばれる基本テーマを提供します。これはオープンソースであり、プロジェクトに適合させることができます。
FormKitは、シンプルでありながら堅牢なスタイリング機能を提供することで、さらに多くのことを実現します。これについては、以下のセクションで説明します。
ほとんどのフロントエンド開発者は、従うべきデザインまたはテーマシステムを持っており、FormKitは、優先順位に従ってクラスを追加する複数の方法を提供することにより、それを可能にします。
ご存知かもしれませんが、入力フィールド全体を表す単一のコンポーネントを使用すると、スタイルを設定するのが面倒になる可能性がありますが、FormKitを使用すると、適切な要素にカスタムクラスを提供するための非常に特殊な小道具、オプション、関数を簡単に提供できます。次のいずれかの方法を使用して、すべてのセクションのクラスを変更できます(特異性の高いものから低いものへ)。
{section-key}-class
小道具(最も具体的)classes
小道具_classes
オプションrootClasses
構成機能(最も具体的でない)これらは、開発者が入力のスタイルを設定するために使用できる属性であり、入力がどのように入力されているかについてユーザーにより良いフィードバックを提供するのに役立ちます。、、、、、およびはdata-type
、CSSで単純なHTML属性としてスタイル設定されますdata-invalid
。data-multipledata-completedata-errors
<style>
[data-invalid] .formkit-inner {
border-color: red;
box-shadow: 0 0 0 1px red;
}
[data-complete] .formkit-inner {
border-color: red;
box-shadow: 0 0 0 1px green;
}
[data-complete] .formkit-inner::after {
content: '✅';
display: block;
padding: 0.5em;
}
</style>
スキーマは、フォームコンポーネントと同じようにスタイルを設定できます。属性と小道具のバインドが可能になり、フォームにクラスとプロパティを簡単に追加できるようになります。
上記に加えて、FormKitは、クラスをその場で追加および削除できるようにすることで、テーマを次のレベルに引き上げるのに役立つクラスの追加とリセットも受け入れます。
上記のコードスニペットに表示されているように、FormKitのクラスは、Vueの場合と同じようにバインドできるため、スタイリングの柔軟性が高まります。
Tailwind CSSを使用している場合、FormKitは必要な複数のインラインスタイルをサポートするだけでなく@formkit/tailwindcss
、構成ファイルでフォームにテーマを設定する機能を提供するテンプレートを使用してよりクリーンなコードを作成するのに役立つパッケージ()も提供します。Tailwindガイドを使用したスタイリングは、FormKitドキュメントで入手できます。
国際化とは、ソフトウェアをさまざまな言語や地域の特性に適応させるプロセスです。
執筆時点では、FormKitには23の異なるロケールが付属しており、使用、交換、オーバーライド、さらにはvue-i18nなどの有名なライブラリとの組み合わせも可能です。
FormKitで追加のアクティブな言語を設定すると、次のように機能します。
import { createApp } from 'vue'
import App from 'App.vue'
import { plugin, defaultConfig } from '@formkit/vue'
import { fr, en } from '@formkit/i18n'
const app = createApp(App)
app.use(
plugin,
defaultConfig({
// Define additional locales
locales: { fr, en },
// Define the active locale
locale: 'en',
})
)
app.mount('#app')
これらの言語は、事前に作成されたFormKitルールとメッセージに適用されます。カスタムルールに関する独自のメッセージがある場合は、それらをvue-i18nライブラリと組み合わせて追加し、VueSFCに適切なロケールを提供できます。
プラグインを使用して、FormKitの機能を拡張できます。これらは、FormKit要素(ノード)を引数として取り、それを微調整する関数です。これらの関数は、ノードが作成されるたび、およびプラグインが追加されるたびに呼び出されます。プラグインの使用例は、サンプルページで確認できます。
デバウンスは、一部の重いタスクがそれほど頻繁に実行されないようにするために使用されるプログラミング手法であり、コードのパフォーマンスを低下させます。
FormKitは、デバウンスされた入力をオンデマンドで提供し、開発者:delay="<time in milliseconds>"
が検証を遅延して実行できる単一の小道具を追加することで、パフォーマンスの高いフォームを作成できるようにします。
FormKitは、検証エラーを適切に処理し、非常に包括的な方法でユーザーに流すことができます。ここで、サーバーで検証のすべてまたは一部を処理し、それらをフロントエンドに返す必要がある場合があります。これらのエラーは、errors
or input-errors
prop、またはnode.setErrors()
orを使用してフォームに追加できます$formkit.setErrors()
。
FormKitはNuxt.jsと完璧に統合され、Nuxtのすべての機能とともに提供するすべてのものにアクセスできます。
FormKitは、非常に柔軟なフォーム処理システムを提供するため、フォームを構築するためのフレームワークとしての地位を確立しています。スキーマはFormKitノードオブジェクトの配列であり、各オブジェクトはHTML要素、コンポーネント、またはテキストノードに対応します。このスキーマは、既存のVue変数を参照し、編集可能な属性と小道具を使用して任意のマークアップまたはコンポーネントをレンダリングできます。
FormKit Coreには、FormKitのほとんどすべての低レベル関数が含まれています。これにより、開発者にフォーム内のコンポーネントの明確に定義されたツリー構造を提供することにより、低レベルの入力処理が可能になります。FormKit Core関数は、フォームの状態の編集、トラバース、リッスン、および追跡に役立ちます。これはより高度であると考えられていますが、モジュラーコード構造が必要な場合に役立ちます。
FormKitには優れたドキュメントがあり、ほとんどのAPIは十分にドキュメント化され、構造化されています。ドキュメントは完全に参照された検索機能を提供し、必要なほとんどすべてを見つけるのに役立ちます。
FormKitプレイグラウンドを使用すると、APIを好きなだけ操作できます。テーマを微調整したり、グローバル構成ファイルを編集したり、必要に応じてFormKitを使用して複数のコンポーネントを作成したりすることができます。
FormKitのようなライブラリはゲームチェンジャーです。これらは、最新のWeb開発における主要なフォームの問題を解決するためのシンプルなソリューションを提供し、開発者が他の方法では面倒な作業を行うのに楽しい時間を過ごせるようにします。
FormKitは、開発プロセスを強化し、ユーザーに非常に強力なフォームを提供するという点で驚異的です。
より詳細な比較が必要な場合に備えて、FormKitは、Vueのエコシステム内の他のフォームライブラリとの比較に優れています。
ソース:https ://blog.logrocket.com/powerful-vue-js-form-development-formkit/
1650042120
La creación de grandes formularios siempre se ha considerado una tarea difícil en el desarrollo web moderno. Los formularios en el exterior son solo un grupo de cuadros de selección, campos de texto, botones de radio y casillas de verificación. Sin embargo, crear temas, validarlos y hacerlos intuitivos para el usuario puede volverse frustrante rápidamente.
Manejar formularios complejos se convierte en una molestia para todos los desarrolladores, lo que lo convierte en uno de los principales puntos débiles en el desarrollo de frontend. La necesidad de la capacidad de controlar múltiples estados y hacerlos interactuar entre sí mientras se mantienen fáciles de llenar dio origen a bibliotecas como Formik , React Hook Form , Veevalidate, Vuelidate, FormKit y otras.
En esta publicación, presentaremos FormKit y cómo puede ayudarnos a crear formularios potentes en Vue.js con validación, estilo y localización.
FormKit es un marco poderoso que ayuda a desarrollar cualquier tipo de formulario en Vue mientras mantiene la experiencia del desarrollador de primer nivel. El equipo detrás de FormKit es el mismo que creó la popular biblioteca VueFormulate . Si está familiarizado con esta biblioteca, recordará su enfoque innovador para crear formularios en Vue.
VueFormulate ofreció a los desarrolladores un componente único que utilizaba en gran medida accesorios y ranuras para crear elementos de formulario. Este enfoque facilitó la redacción, el manejo y la validación de formularios.
FormKit es una versión mejorada de VueFormulate que ofrece a los desarrolladores los mismos beneficios con un sutil toque de magia. Hoy, FormKit se presenta como un marco completo creado para ayudar a los desarrolladores a escribir excelentes formularios.
Para instalar FormKit en su proyecto, debe seguir los primeros pasos en los documentos de instalación de FormKit .
FormKit ofrece dos formas simples de crear formularios: usando el <FormKit/>
componente o generando el formulario a partir de un esquema JSON.
<FormKit/>
componenteCon FormKit, puede crear campos de texto altamente controlables, cuadros de selección y otros elementos de formulario con un solo componente de FormKit. Este componente viene con accesorios específicos que brindan una alta personalización del elemento de entrada que desea agregar a su formulario:
<template>
<FormKit
label="Short word"
type="text"
help="Type any short word"
validation="required|matches:/^[a-zA-Z]+$/|length:5"
value="Hello"
/>
</template>
Este único componente puede crear otros tipos de entrada, de forma similar a cómo la <input>
etiqueta de HTML utiliza varios type
atributos (es decir, <input type="text">
versus <input type="checkbox">
).
Este enfoque es poderoso porque no solo proporciona a los desarrolladores menos API para aprender, sino que también lo hace de la manera más intuitiva. El componente FormKit proporciona accesorios explícitos necesarios para crear formularios y puede pasar a la entrada HTML renderizada todos los atributos (accesorios) que necesita que muestren.
En la mayoría de los casos en los que necesita que sus entradas se comporten como un formulario (o múltiples formularios), el <FormKit/>
componente puede convertirse en un contenedor que recopila activamente todos los valores de los componentes secundarios de FormKit. Utiliza el name
de cada entrada como el nombre de la propiedad en el objeto de datos resultante. Este contenedor también le permite obtener o editar valores de formulario como lo haría con el atributo v-model adjunto a cualquier entrada en Vue.
Para hacer esto, simplemente envuelva sus entradas en <FormKit type="form">
caso de que necesite un formulario global y <FormKit type="group">
si desea agrupar parte de un formulario. Esto es de gran ayuda para hacer que los elementos del formulario interactúen entre sí, restablecer el estado del formulario o enviarlo a una API, lo que en Vanilla Vue puede resultar inconveniente para el desarrollador, ya que es posible que tenga que escuchar múltiples variables de múltiples fuentes.
El contenedor también invalidará todo el formulario si una sola entrada no es válida, lo que hace que sea imposible enviarlo:
<FormKit
type="form"
submit-label="Login"
:errors="['No server.', 'More errors here']"
>
<FormKit type="email" label="Email" />
<FormKit type="password" label="Password" />
</FormKit>
Los formularios dinámicos son una característica de gran demanda en el manejo de formularios. Los desarrolladores a menudo necesitan crear formularios que pueden seguir una estructura personalizada que no se ha especificado previamente, o cuyas respuestas y validaciones se pueden crear sobre la marcha.
FormKit ofrece esta gran habilidad usando el <FormKitSchema>
componente y su :schema
accesorio:
<script setup>
const schema = [
{
$formkit: 'email',
label: 'Email address',
validation: 'required'
}
]
</script>
<template>
<FormKit type="form">
<FormKitSchema :schema="schema" />
</FormKit>
</template>
El esquema JSON de FormKit es extremadamente poderoso. Abarca desde la creación de formas simples como la anterior hasta las más complejas. Los esquemas admiten funciones de primer nivel como lógica condicional, operadores booleanos, bucles, ranuras y alcance de datos, lo que le permite personalizar los formularios generados como desee:
<FormKitSchema
:schema="[
{
$formkit: 'email',
label: 'Email address',
}
]"
/>
El código anterior crea una sola entrada de correo electrónico. Esto podría ampliarse con validación, contraseñas, interacciones y mucho más .
FormKit lo ayuda a validar sus formularios fácilmente mediante el uso y la combinación de más de 20 reglas de validación escritas previamente para sus formularios. Estas reglas tienen varias formas de ser utilizadas, por lo que el desarrollador puede elegir la que le parezca más adecuada a su proyecto:
<!-- validation as string -->
<FormKit
type="text"
label="Number"
validation="required|number|between:0,10"
validation-visibility="live"
help="Enter a number between 0 and 10."
/>
<!-- validation as array -->
<FormKit
type="text"
label="Phone"
placeholder="xxx-xxx-xxxx"
:validation="[['required'], ['matches', /^\d{3}-\d{3}-\d{4}$/]]"
validation-visibility="live"
:validation-messages="{
matches: 'Phone number must be formatted: xxx-xxx-xxxx',
}"
/>
En FormKit, las reglas son extensibles, personalizables y no requieren una biblioteca de terceros para manejar la validación. Crear reglas personalizadas para sus formularios es tan fácil como escribir una función que obtenga un valor como argumento y devuelva un valor booleano de acuerdo con los condicionales que se encuentran dentro:
// ./validation-custom-rules/yes-rule.js
// ensures that the value is always yes
export default function yes(node) {
return node.value === 'yes' || node.value === 'YES'
}
// main.js ---------
import { createApp } from 'vue'
import App from './App.vue'
import { plugin, defaultConfig } from '@formkit/vue'
import yes from './my-custom-rules/yes-rule'
// prettier-ignore
createApp(App).use(plugin, defaultConfig({
rules: { yes },
})).mount('#app')
La validación en FormKit se simplificó para ayudar a los desarrolladores a escribir buenos formularios, pero se creó para escalar adecuadamente manteniendo la simplicidad que disfrutamos. En caso de que sus formularios se vuelvan más complejos y requieran más reglas personalizadas y mayores interacciones entre los campos, FormKit combinado con la increíble modularidad de los componentes de Vue puede ayudarnos a crear formularios y estados complejos mientras mantiene el código simple y fácil de entender.
Diseñar formas nativas no es fácil. Las casillas de verificación, las áreas de texto, los campos de texto y los botones de radio son todos <input>
campos, pero no se les puede aplicar el mismo estilo. FormKit proporciona un tema base llamado Génesis , que es de código abierto y se puede adaptar a su proyecto.
FormKit también hace más al proporcionar funciones de estilo simples pero sólidas, que analizaremos en las secciones a continuación.
La mayoría de los desarrolladores frontend tienen un diseño o un sistema de temas a seguir, y FormKit lo permite al ofrecer múltiples formas de agregar clases ordenadas por precedencia.
Como sabrá, tener un solo componente para representar un campo de entrada completo puede ser engorroso de diseñar, pero FormKit lo facilita al proporcionar accesorios, opciones y funciones muy específicos para proporcionar clases personalizadas al elemento correcto. Las clases se pueden modificar para todas las secciones usando cualquiera de los siguientes métodos (de mayor a menor especificidad):
{section-key}-class
accesorios (más específicos)classes
accesorioclasses
opción de configuraciónrootClasses
función de configuración (menos específica)Estos son atributos que los desarrolladores pueden usar para diseñar la entrada para ayudar a proporcionar una mejor retroalimentación al usuario sobre cómo se está llenando. data-type
, data-invalid
, data-multiple
, data-complete
y data-errors
tienen estilo en CSS como atributos HTML simples:
<style>
[data-invalid] .formkit-inner {
border-color: red;
box-shadow: 0 0 0 1px red;
}
[data-complete] .formkit-inner {
border-color: red;
box-shadow: 0 0 0 1px green;
}
[data-complete] .formkit-inner::after {
content: '✅';
display: block;
padding: 0.5em;
}
</style>
Los esquemas se pueden diseñar tanto como el componente de formulario. Habilitan el enlace de atributos y accesorios, lo que facilita agregar clases y propiedades en sus formularios.
Además de lo anterior, FormKit también acepta agregar y restablecer clases que ayudan a llevar su tematización al siguiente nivel al permitirle agregar y eliminar clases sobre la marcha.
Como se muestra en los fragmentos de código anteriores, las clases en FormKit se pueden vincular como en Vue, lo que permite una mayor maleabilidad en el estilo.
En caso de que esté utilizando Tailwind CSS, FormKit no solo es compatible con los múltiples estilos en línea que necesita, sino que también proporciona un paquete ( @formkit/tailwindcss
) para ayudarlo a escribir un código más limpio con plantillas que brindan la capacidad de crear un tema para sus formularios en un archivo de configuración. La guía de estilos con Tailwind está disponible en los documentos de FormKit.
La internacionalización es el proceso de adaptar el software a diferentes idiomas y peculiaridades regionales.
Al momento de escribir este artículo, FormKit se envía con 23 configuraciones regionales diferentes que se pueden usar, intercambiar, anular e incluso combinar con bibliotecas conocidas como vue-i18n .
La configuración de idiomas adicionales y activos en FormKit funciona de la siguiente manera:
import { createApp } from 'vue'
import App from 'App.vue'
import { plugin, defaultConfig } from '@formkit/vue'
import { fr, en } from '@formkit/i18n'
const app = createApp(App)
app.use(
plugin,
defaultConfig({
// Define additional locales
locales: { fr, en },
// Define the active locale
locale: 'en',
})
)
app.mount('#app')
Estos idiomas se aplican a las reglas y mensajes de FormKit preescritos. En caso de que tenga sus propios mensajes para reglas personalizadas, puede agregarlos y combinarlos con la biblioteca vue-i18n para proporcionar la configuración regional adecuada en sus SFC de Vue.
Los complementos se pueden utilizar para ampliar la funcionalidad de FormKit. Son funciones que toman un elemento FormKit (nodo) como argumento y lo modifican. Estas funciones se llaman cada vez que se crea un nodo y cuando se agrega un complemento. Se pueden ver ejemplos de uso de complementos en la página de ejemplos .
La eliminación de rebotes es una práctica de programación utilizada para garantizar que algunas tareas pesadas no se activen con tanta frecuencia que reduzcan el rendimiento del código.
FormKit proporciona entradas antirrebote a pedido, lo que permite a los desarrolladores crear formularios de alto rendimiento al agregar un accesorio único :delay="<time in milliseconds>"
en el que las validaciones se pueden realizar con un retraso.
FormKit puede manejar con gracia sus errores de validación y transmitirlos al usuario de una manera muy integral. Ahora, uno puede necesitar manejar toda o parte de la validación en el servidor y devolverlos a la interfaz. Estos errores se pueden agregar al formulario usando errors
o input-errors
prop, o node.setErrors()
o $formkit.setErrors()
.
FormKit se integra a la perfección con Nuxt.js y brinda acceso a todo lo que tiene para ofrecer junto con todas las funciones de Nuxt.
FormKit se acuña a sí mismo como un marco para crear formularios porque ofrece un sistema de manejo de formularios muy flexible. Un esquema es una matriz de objetos de nodo de FormKit y cada objeto corresponde a un elemento HTML, un componente o un nodo de texto. Este esquema puede hacer referencia a las variables de Vue existentes y representar cualquier marcado o componente con atributos y accesorios editables.
FormKit Core contiene casi todas las funciones de bajo nivel en FormKit. Esto permite el manejo de entrada de nivel inferior al proporcionar a los desarrolladores una estructura de árbol bien definida de los componentes dentro del formulario. Las funciones de FormKit Core ayudan a editar, atravesar, escuchar y rastrear el estado del formulario. Esto se considera más avanzado, pero puede ser útil cuando necesita tener una estructura de código modular.
FormKit tiene una excelente documentación y la mayor parte de la API está bien documentada y estructurada. Los documentos proporcionan una funcionalidad de búsqueda referenciada completa, que lo ayuda a encontrar casi todo lo que necesita.
El área de juegos de FormKit te permite jugar con la API todo lo que quieras. Tiene la capacidad de modificar temas, editar el archivo de configuración global y crear múltiples componentes utilizando FormKit cuando sea necesario.
Las bibliotecas como FormKit cambian las reglas del juego; ofrecen una solución simple para resolver el principal problema de forma en el desarrollo web moderno, y permiten a los desarrolladores pasar un buen rato con lo que de otro modo sería una tarea tediosa.
FormKit es alucinante en la forma en que potencia su proceso de desarrollo y presenta formularios extremadamente poderosos para los usuarios.
En caso de que necesite una comparación más profunda, FormKit ha hecho un buen trabajo al compararse con otras bibliotecas de formularios en el ecosistema de Vue.
Fuente: https://blog.logrocket.com/powerful-vue-js-form-development-formkit/
1633111020
Power Automateでは、目的の結果を得ることができるように、モジュラー算術演算を実行する必要がある場合があります。例として、ホテルにいる顧客に基づいてテーブルを待っている顧客の数を確認できます。これにより、顧客は待機している顧客の数に関する情報を取得して、それに応じて計画を立てることができます。
ステップ1
次の図に示すように、URLmake.powerapps.comを使用してユーザー名とパスワードを入力して必要なPowerApps環境にログインし、左側の[フロー]をクリックします。
ステップ2
手順1の後、[新しいフロー]をクリックし、インスタントクラウドフローを選択して、トリガーを手動でトリガーし、次の図に示すように[作成]をクリックします。
ステップ3
後はステップ2、並列分岐を追加して、など一部の名前フローでMOD関数とは、取る初期化変数アクションをし、としてそれをステップ名を提供総顧客、その後、片側のように入力を提供
名前:顧客
タイプ:整数
値:17
下の図に示すように。
ステップ4
手順3の後、並列ブランチの反対側で変数の初期化アクションを実行し、5つのテーブルのテーブルあたりの最大顧客数として名前を付けて提供します。
名前:テーブル座ることができる最大容量
タイプ:整数
値:3
下の図に示すように。
ステップ5
ステップ4の後、作成アクションを実行し、「テーブルを待機している顧客の数を取得」という名前を付けます。2つのパラメーターdividendとdivisorが両方とも数値であることを期待するmod関数を入力に提供します。
Mod(dividend: number,divisor: number)
ベーシック
コピー
ステップ3、ステップ4の式に値を指定します
mod(variables('Customers'),variables('Table Maximum Capacity Allowed To Sit'))
ベーシック
コピー
次の図に示すように、[ OK ] / [更新]をクリックします。
ステップ6
手順5の後、フローを保存し、フローをテストして実行すると、次の図に示すように、5つのテーブルがそれぞれ3つのメンバーで占められているため、17のメンバーの中で2つのメンバーが待機していると推測される3つの数値が書き込まれる結果を確認します。
ノート
このようにして、PowerAutomateフローのModのような算術演算を簡単に実行できます。
Link: https://www.c-sharpcorner.com/article/usage-of-mod-function-in-power-automate/
1632474000
What started as a spec has blossomed into a community of developers who share a desire to bring the joy of GraphQL to more teams at their company. Over 12 community projects in 9 languages—along with multiple database vendors—have implemented federation as the industry standard for composing graphs together.
1625623380
Select this video to find the best FREE Photoshop alternatives. What are the best FREE Photoshop alternatives? This video will help you decide. Don’t want to pay the money for Photoshop then check out these photo editing and digital painting programs.
Krita: https://krita.org/
Medibang Paint: https://medibangpaint.com/
Gimp: https://www.gimp.org/
PhotoScape X: http://x.photoscape.org/
Pixlr: https://pixlr.com/
Subscribe: https://www.youtube.com/c/TeachersTech/featured
#powerful