Инструменты генеративного искусственного интеллекта в Photoshop Beta

Adobe Photoshop выпустила новый инструмент под названием Generative Fill, который управляется генератором изображений Firefly с искусственным интеллектом. Этот инструмент позволяет пользователям легко расширять фотографии, добавлять или удалять элементы с помощью текстовых подсказок и обеспечивает больший контроль, чем существующие инструменты, такие как Content-Aware Fill. Благодаря интеграции в Photoshop Generative Fill расширяет доступ к возможностям создания изображений с помощью ИИ. Давайте посмотрим на специфику и возможности этого нового инструмента.

Инструмент генеративной заливки Photoshop предоставляет множество вариантов изменения и изменения изображения.

Вот несколько примеров того, чего вы можете достичь с помощью генеративного ИИ:

  1. Удаление объекта : Вы можете использовать генеративную заливку, чтобы удалить нежелательные элементы из изображения. Просто выберите объект, который нужно удалить, предоставьте текстовое сообщение, объясняющее удаление, и генеративное заполнение интеллектуально заполнит область материалом, который соответствует окружающему изображению.
  2. Добавление объекта: вы можете использовать генеративную заливку, чтобы добавить дополнительные элементы к вашим фотографиям. Например, вы можете улучшить фотографию пейзажа, добавив деревья, дома или другие объекты. Генеративное заполнение создаст возможности, которые могут быть объединены с изображением, если вы предоставите текстовое приглашение с указанием желаемого добавления.
  3. Расширение изображения: вы можете использовать генеративное заполнение для расширения границ изображения, обычно называемое закрашиванием. Эта возможность удобна, когда вы хотите увеличить изображение, не искажая и не расширяя текущую информацию. Создайте дополнительные пиксели, соответствующие исходному изображению, что приведет к естественному расширению.
  4. Создание фона: с помощью генеративной заливки вы можете редактировать или добавлять фон к своим фотографиям. Генеративное заполнение создаст возможности, которые идеально сочетаются с материалом переднего плана, если предоставляется текстовая подсказка с описанием желаемого фона, например, «закатный пляж» или «городской горизонт».
  5. Творческое исследование: генеративное заполнение предлагает пространство для исследовательского мышления. Вы можете ввести многочисленные текстовые подсказки, чтобы изучить различные возможности и создать несколько вариантов редактирования. Это позволяет быстро повторять и визуализировать многие концепции, расширяя ваши творческие возможности.

Как получить доступ к генеративному ИИ в Photoshop

Adobe объявила, что Firefly Generative Fill скоро станет опцией по умолчанию в Photoshop. Однако в настоящее время эта возможность доступна только в бета-версии Photoshop. Выполните следующие простые шаги, чтобы получить доступ к бета-функциям:

  1. Купите подписку на Adobe Creative Cloud, которая содержит Photoshop, а также другие отдельные продукты, или пакет фотографий, который включает Lightroom.
  2. Запустите программу Creative Cloud для настольных ПК на своем ПК.
  3. Найдите и выберите «Бета-приложения» в левом столбце приложения.
  4. Найдите приложение «Photoshop (бета)» и нажмите кнопку «Установить».
  5. По завершении установки бета-версия Photoshop будет отображаться в разделе «Установленные бета-приложения».
  6. Чтобы запустить бета-версию Photoshop, нажмите кнопку «Открыть».
  7. В Windows выберите «Справка» > «О Photoshop» в строке меню, чтобы убедиться, что вы используете бета-версию. На Mac «Photoshop (Beta)» появится в строке меню, заменив стандартное название «Photoshop».

Выполнив эти шаги, вы можете получить доступ к бета-версии Photoshop и протестировать экспериментальные функции, такие как Firefly Generative Fill, прежде чем они станут доступны для широкой публики. Воспользуйтесь возможностью изучить и узнать о возможностях этого интересного инструмента.

Как использовать Photoshop AI: генеративное заполнение в действии

Если вы знакомы с генеративным искусственным интеллектом, использование «Photoshop AI» и его новой функции генеративного заполнения не составит труда. Просто выполните следующие действия:

  1. Откройте бета-приложение Photoshop на своем ПК.
  2. Используя соответствующий инструмент выделения, выберите точную область изображения, которую вы хотите отредактировать.
  3. Выберите «Генеративное заполнение» в раскрывающемся меню.
  4. Введите описание или подсказку, указывающую, что вы хотите создать в указанном регионе. Например, вы можете ввести «пляжная сцена» или «городской пейзаж».
  5. В зависимости от вашего ввода Photoshop создаст различные версии или возможности.
  6. Photoshop автоматически применит изменения к изображению, когда вы сделаете выбор. Вы можете увидеть изменения в режиме реального времени, прежде чем принять решение.
  7. Параметры инструмента «Генеративное заполнение» настраиваются, что позволяет настроить его производительность в соответствии с вашими потребностями.

Возможности генеративного искусственного интеллекта Adobe Photoshop

Новейшие возможности искусственного интеллекта Adobe Photoshop предоставляют художникам и дизайнерам множество мощных инструментов, помогающих им улучшить свой творческий процесс. Давайте посмотрим на захватывающие возможности Adobe Photoshop AI:

  1. Работает на Firefly. Базовая модель искусственного интеллекта Firefly была обучена с использованием обширной библиотеки лицензированных изображений высокого разрешения из Adobe Stock. Это гарантирует уникальность создаваемой информации и отсутствие нарушений прав интеллектуальной собственности.
  2. Идея для изображения: художники могут использовать генеративный ИИ для изменения изображений, плавно добавляя, удаляя или расширяя их содержимое. Эта функция позволяет вносить быстрые и динамичные изменения, предлагая новые возможности для творческого самовыражения.
  3. Неразрушающее редактирование. Генеративные слои позволяют экспериментировать с новыми стилями и эффектами, не затрагивая исходное изображение. Художники могут свободно экспериментировать с различными возможностями и повторять свои проекты, не беспокоясь о потере оригинального произведения искусства.
  4. Повышение творческих способностей на скорости: функции Photoshop на основе искусственного интеллекта позволяют художникам раскрыть свой творческий потенциал и создавать уникальные высококачественные изображения с высокой скоростью. Эта трансформирующая скорость производства позволяет художникам экспериментировать с новыми идеями и создавать множество замечательных работ.
  5. Доступность веб-инструмента: генеративный ИИ также доступен в виде онлайн-инструмента в рамках бета-версии Firefly. Это означает, что люди могут протестировать его возможности до общего выпуска. Это обновление расширяет горизонты пользователей Photoshop, предоставляя им новые интересные возможности для творчества.

Окунитесь в будущее искусственного интеллекта Photoshop: художники получают непревзойденную творческую гибкость и продуктивность, используя возможности искусственного интеллекта Adobe Photoshop. Photoshop остается отраслевым стандартом, используя возможности искусственного интеллекта, позволяя художникам исследовать и расширять границы своего воображения. Исследуйте интригующий мир Photoshop AI прямо сейчас и раскройте свой творческий потенциал.

Эта статья поможет вам изучить Adobe Powerful Generative AI Tools в бета-версии Photoshop. Мы верим, что это было полезно для вас. Пожалуйста, не стесняйтесь делиться своими мыслями и отзывами в разделе комментариев ниже.

Оригинальный источник статьи: https://www.cloudbooklet.com/

#photoshop #AI #powerful

Инструменты генеративного искусственного интеллекта в Photoshop Beta

在 Photoshop Beta 中推出强大的生成式 AI 工具

Adobe Photoshop 发布了一款名为 Generative Fill 的新工具,由 AI 图片生成器 Firefly 驱动。该工具使用户能够使用文本提示轻松扩展照片、添加或删除项目,并提供比当前工具(如内容识别填充)更多的控制。通过与 Photoshop 的集成,Generative Fill 拓宽了对 AI 图片制作功能的访问。让我们看看这个新工具的细节和可能性。

Photoshop 的 Generative Fill 工具提供了多种图片修改和更改选项。

以下是您可以使用生成式 AI 实现的一些示例:

  1. 对象移除:您可以使用生成填充从图像中移除不需要的项目。只需选择要移除的对象,提供解释移除的文本提示,Generative Fill 就会智能地用适合周围图像的材料填充该区域。
  2. 对象添加:您可以使用生成填充为您的照片添加额外的元素。例如,您可以通过添加树木、房屋或其他东西来改善风景照片。如果您提供指定所需添加的文本提示,生成填充将产生可能合并到图像中的可能性。
  3. Image Extension:您可以使用Generative Fill来扩展图像的边界,通常称为out painting。当您希望在不扭曲或扩展当前信息的情况下放大图像时,此功能会派上用场。生成与原始图像对齐的附加像素,从而产生自然延伸。
  4. 背景创建:使用生成填充,您可以编辑或添加背景到您的照片。如果提供描述所需背景的文本提示,例如“日落海滩”或“城市天际线”,生成填充将产生与前景材料完美融合的可能性。
  5. 创造性探索:生成填充为探索性思维提供了空间。您可以输入多个文本提示来探索不同的可能性并产生多个编辑选项。这使您能够快速迭代和可视化许多概念,从而拓宽您的创意选择。

如何在 Photoshop 中访问生成式 AI

Adobe 宣布 Firefly 生成填充将很快成为 Photoshop 中的默认选项。但是,此功能目前仅在 Photoshop 的测试版中可用。按照以下简单步骤获取对测试版功能的访问权限:

  1. 购买 Adob​​e Creative Cloud 的订阅,其中包含 Photoshop 以及其他单独的产品,或包含 Lightroom 的摄影包。
  2. 在您的 PC 上启动 Creative Cloud 桌面程序。
  3. 从应用程序的左栏中找到并选择“测试版应用程序”。
  4. 查找“Photoshop (Beta)”应用程序并单击“安装”按钮。
  5. 安装完成后,Photoshop beta 将显示在“已安装的 beta 应用程序”下。
  6. 要启动 Photoshop beta,请单击“打开”按钮。
  7. 在 Windows 上,从菜单栏转到“帮助”>“关于 Photoshop”以检查您使用的是测试版。在 Mac 上,“Photoshop (Beta)”将出现在菜单栏中,取代标准的“​​Photoshop”标题。

通过执行这些步骤,您可以访问 Photoshop 的测试版并在Firefly Generative Fill 等实验性功能向更广泛的公众开放之前对其进行测试。利用这个机会探索和了解这个有趣工具的功能。

如何使用 Photoshop AI:生成填充动作

如果您熟悉生成式 AI,那么使用“Photoshop AI”及其新的生成式填充功能将轻而易举。只需按照以下步骤操作:

  1. 在您的 PC 上打开 Photoshop beta 应用程序。
  2. 使用适当的选择工具,选择要编辑的图像的精确区域。
  3. 从下拉菜单中选择“生成填充”。
  4. 输入说明或提示,指示您要在指定区域中创建的内容。例如,您可以键入“海滩场景”或“城市景观”。
  5. 根据您的输入,Photoshop 将产生各种版本或可能性。
  6. 当您进行选择时,Photoshop 会自动将更改应用到图像。在做出决定之前,您可能会实时看到变化。
  7. 生成填充工具的参数是可配置的,允许您根据需要调整其性能。

Adobe Photoshop生成 AI的功能

Adobe Photoshop 的最新 AI 功能为艺术家和设计师提供了大量强大的工具,帮助他们改进创作过程。让我们来看看 Adob​​e Photoshop AI 令人兴奋的功能:

  1. 由 Firefly 提供支持:底层 AI 模型 Firefly 使用来自 Adob​​e Stock 的大量许可高分辨率图片库进行训练。这保证了创建的信息是唯一的,并且没有知识产权被滥用。
  2. 从想法到图像:艺术家可以使用生成式 AI 通过平滑地添加、删除或扩展其内容来修改图片。此功能允许快速和动态的变化,为创意表达提供新的途径。
  3. 非破坏性编辑:生成层允许您在不影响源图像的情况下试验新的样式和效果。艺术家可以自由地尝试不同的可能性并迭代他们的设计,而不必担心丢失原始艺术作品。
  4. 快速增强创造力: Photoshop 的人工智能功能使艺术家能够释放他们的创造力,并快速创作出与众不同的高质量艺术品。这种不断变化的生产速度使艺术家能够尝试新的想法并创作出大量非凡的作品。
  5. Web 工具可访问性:作为 Firefly 测试版的一部分,Generative AI 也可以作为在线工具访问。这意味着人们可以在正式发布之前测试其功能。此次升级拓宽了 Photoshop 用户的视野,为他们的创作提供了有趣的新选择。

拥抱 Photoshop AI 的未来:艺术家使用 Adob​​e Photoshop 的 AI 功能获得无与伦比的创作灵活性和生产力。Photoshop 通过使用 AI 的力量保持行业标准,允许艺术家探索和突破他们想象力的界限。立即探索 Photoshop AI 的迷人世界,释放您的创造潜能。

本文旨在帮助您学习 Photoshop Beta 中的 Adob​​e 强大的生成式 AI 工具。我们相信它对您有所帮助。请随时在下面的评论部分分享您的想法和反馈。

文章原文出处:https: //www.cloudbooklet.com/

#photoshop #AI #powerful

在 Photoshop Beta 中推出强大的生成式 AI 工具

Introduces Powerful Generative AI Tools in Photoshop Beta

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:

  1. Object Removal: You may use Generative Fill to eliminate undesired items from an image. Simply choose the object to be removed, provide a text prompt explaining the removal, and Generative Fill will intelligently fill in the region with material that fits in with the surrounding image.
  2. Object Addition: You may use Generative Fill to add additional elements to your photos. You may, for example, improve a landscape photograph by adding trees, houses, or other things. Generative Fill will produce possibilities that may be merged into the image if you provide a text prompt specifying the desired addition.
  3. Image Extension: You may use Generative Fill to expand an image’s boundaries, commonly known as out painting. This capability comes in handy when you wish to enlarge an image without distorting or extending the current information. Generate additional pixels that align with the original image, resulting in a natural extension.
  4. Background Creation: Using Generative Fill, you may edit or add backgrounds to your photographs. Generative Fill will produce possibilities that blend perfectly with the foreground material if a text prompt describing the desired backdrop, such as “sunset beach” or “city skyline,” is provided.
  5. Creative Exploration: Generative Fill offers a space for exploratory thinking. You may enter numerous text prompts to explore different possibilities and produce several editing alternatives. This enables you to swiftly iterate and visualize many concepts, broadening your creative options.

How to Access Generative AI in Photoshop

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:

  1. Buy a subscription to Adobe’s Creative Cloud, which contains Photoshop as well as other individual products, or the photography package that includes Lightroom.
  2. Launch the Creative Cloud desktop program on your PC.
  3. Locate and choose “Beta apps” from the app’s left column.
  4. Look for the “Photoshop (Beta)” app and click the “Install” button.
  5. When the installation is complete, Photoshop beta will be shown under “Installed beta apps.”
  6. To start Photoshop beta, click the “Open” button.
  7. On Windows, go to Help > About Photoshop from the menu bar to check you are using the beta version. On a Mac, “Photoshop (Beta)” will appear in the Menu Bar, replacing the standard “Photoshop” title.

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.

How to Use Photoshop AI: Generative Fill in Action

If you’re familiar with generative AI, using “Photoshop AI” and its new generative fill function is a breeze. Simply follow these steps:

  1. Open the Photoshop beta application on your PC.
  2. Using the proper selection tool, choose the precise region of the image that you want to edit.
  3. Select “Generative Fill” from the drop-down menu.
  4. Enter a description or prompt indicating what you want created in the specified region. For example, you may type “a beach scene” or “a cityscape.”
  5. Based on your input, Photoshop will produce various versions or possibilities.
  6. Photoshop will automatically apply the changes to the image as you make a selection. You may see the changes in real time before making your decision.
  7. The Generative Fill tool’s parameters are configurable, allowing you to tailor its performance to your needs.

Features of Adobe Photoshop Generative AI

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:

  1. Powered by Firefly: The underlying AI model, Firefly, was trained using a massive library of licensed, high-resolution pictures from Adobe Stock. This guarantees that the created information is unique and that no intellectual property rights are abused.
  2. Idea to Image: Artists may use Generative AI to modify pictures by smoothly adding, deleting, or expanding their content. This feature allows for rapid and dynamic changes, offering up new avenues for creative expression.
  3. Non-Destructive Editing: Generative layers allow you to experiment with new styles and effects without affecting the source image. Artists may freely experiment with different possibilities and iterate on their designs without concern of losing the original artwork.
  4. Enhance Creativity at Speed: Photoshop’s AI-powered features allow artists to unleash their creativity and create distinctive, high-quality artwork at a rapid speed. This transforming velocity of production allows artists to experiment with new ideas and create a plethora of remarkable works.
  5. Web Tool Accessibility: Generative AI is also accessible as an online tool as part of the Firefly beta. This implies that people can test its capabilities before the general release. This upgrade broadens Photoshop users’ horizons, presenting them with interesting new options for their creative endeavors.

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/

#photoshop #AI #powerful

Introduces Powerful Generative AI Tools in Photoshop Beta
Lawson  Wehner

Lawson Wehner

1679470320

A Powerful toolkit To Enhance Your Development Experience with Jotai

Jotai DevTools

🚀 Features

  • Debug 🐞 atom values with ease
  • Out-of-the-box 🔌 support for async/suspendible atoms
  • Built-in Dark mode 🌗
  • ✅ Supports custom store
  • ✅ Works with provider-less mode
  • ✅ Works with Next.js
  • ✅ Supports custom nonce for CSP
  • ✅ Hides private atoms with ability to configure (requires Jotai >=2.0.3)
  • ✅ Tree-shakable and built for non-production environments

📺 Preview

Jotai DevTools Screenshot

☝️ Prerequisites

  • Jotai version >=1.11.0 (highly recommended to use 2.x.x)
  • React version >=17.0.0

📦 Setup

# yarn
yarn add jotai-devtools

# npm
npm install jotai-devtools --save

✨ UI DevTools

Enhance your development experience with the UI based Jotai DevTool

Demo

Babel plugin setup - (Optional but highly recommended)

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"
  ]
}

Next JS setup

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;

Available props

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;
  };
};

Provider-less

import { DevTools } from 'jotai-devtools';

const App = () => {
  return (
    <>
      <DevTools />
      {/* your app */}
    </>
  );
};

With Provider

import { createStore } from 'jotai';
import { DevTools } from 'jotai-devtools';

const customStore = createStore();

const App = () => {
  return (
    <Provider store={customStore}>
      <DevTools store={customStore} />
      {/* your app */}
    </Provider>
  );
};

Hooks

Detailed documentation is available on https://jotai.org/docs/api/devtools

import {
  useAtomsSnapshot,
  useGotoAtomsSnapshot,
  useAtomsDebugValue,
  // Redux devtool hooks
  useAtomDevtools,
  useAtomsDevtools,
} from 'jotai-devtools';

Migration guides

Migrate Jotai to V2

Find the official migration guide on jotai.org

Migrate 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';

Other announcements

First announcement


Download Details:

Author: Himself65
Source Code: https://github.com/Himself65/jotai-devtools 
License: MIT license

#typescript #powerful #toolkit 

A Powerful toolkit To Enhance Your Development Experience with Jotai

Best 17 Powerful Ways To Speed Up Your WooCommerce Store

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

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

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.

Why Speed Matters for an Online Store

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.

Average Website Speed Index in the US by Google

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 versus bounce rate chart by Google

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.

WordPress sites performance stats from HTTPArchive.org

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.

Measuring the Speed of a WooCommerce Store

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.

Pingdom Tools example speed test report

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.

A tweet by Gary Illyes, Webmaster Trends Analyst, Google

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.

How to Speed Up WooCommerce

A speed test report will give you an actionable plan to optimize your slow WooCommerce site. Excited? Let’s get started!

1. Optimize WooCommerce Settings for Performance

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.

WordPress settings to limit the number of post revisions

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.

Optimizing the WordPress discussion settings

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.

Disabling product reviews in WooCommerce settings

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.
 

2. Get a Fast WooCommerce Theme

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

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.

Using filters to search smartly for themes on wp.org

Filter down your ecommerce theme search

WP Rocket tested a bunch of popular WooCommerce themes for speed and came up with the following results.

WooCommerce themes size and requests report by WP Rocket

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.

Opt for a fast WooCommerce theme (Image source: WP Rocket)

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.

3. Go Easy on Plugins and WooCommerce Extensions

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.

A screenshot of plugins available on wp.org

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 Store page

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.

4. Increase WordPress Memory Limit

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.

5. Compress Images and Optimize Delivery

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:

The median WordPress page weight in 2020 as per HTTPArchive.org

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):

  1. Choose the right format for your images (JPEG, PNG, SVG, WebP).
  2. Compress the images efficiently using the right tools.
  3. Use responsive images to optimize delivery for various devices.
  4. Lazy-load offscreen and hidden images.
  5. Offload image delivery to fast CDNs.

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 through the WordPress Customizer

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:

Compressing images losslessly on Compressor.io

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.
 

6. Deliver Static Resources via CDN

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

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).

An infographic showing how CDNs help with serving static content faster

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:

7. Strip Unused Scripts and Stylesheets

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.

An example of GTMetrix's Waterfall Chart

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.

The Network tab under Google Chrome's DevTools

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 with Asset CleanUp plugin

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 the Stripe payment gateway script from loading on a page with Asset CleanUp plugin

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.

8. HTTP/2 is Extremely Essential

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. versus HTTP/2 major benefits

HTTP 1.1 vs HTTP/2 (Image source: Cloudflare)

The performance increase with HTTP/2 is due to multiple reasons:

  • Better multiplexing and parallelism over a single TCP connection.
  • HPACK compression for headers with Huffman encoding algorithm.
  • ALPN extension for faster encryption.
  • Proactive server pushes instead of waiting for requests.

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.

9. Cache WooCommerce to Speed It Up

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.

An infographic of how web caching works

How web caching works

  1. The user makes a request through their browser for a website. For example, they type in www.kinsta.com in their browser.
  2. The browser then makes a request for a webpage (HTML document) to display to the user. A DNS server handles this request, which results in revealing the hosting server’s IP.
  3. Returning the webpage is handled by an application (e.g. WordPress, Joomla, etc.) hosted on a web server. With static websites, an application may not even be necessary.
  4. The application runs the scripts (e.g. PHP, JavaScript,etc.) and (5) queries the database (e.g. MySQL, MongoDB, etc.) to build a webpage. It then returns the webpage to the browser, which renders it and shows it to the user.

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.

An example of improvement in WordPress load times after migrating to Kinsta

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.

10. Clean Up Your WooCommerce Database

A database is an organized collection of all your website’s data. In a WooCommerce store, it includes:

  • Site content such as product pages, categories, tags, user data, reviews, site-wide settings, theme, plugins, etc.
  • Transaction data such as order details, payments, inventory, etc.

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.

Delete Old Revisions

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 post revisions with 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.

Limit the Number of Revisions Stored

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.

Using the WP Revisions Control plugin to limit the number of post revisions

Set the number of revisions with WP Revisions Control

Disable Revisions Altogether (If They’re Unnecessary)

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.

Clean up Expired Transients

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.

Delete Expired Transients plugin panel screen

Deleted all your expired transients easily

Clean up Your Database Tables

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 under phpMyAdmin

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.

Disable Non-Critical Features That Tax the Database

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's

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 is known to be taxing on your server

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:

  1.  
    1.  

Reminder: Always take a backup before editing your database or WordPress core files.

11. Optimize Your Store for Mobile-First Experience

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.

Total number of Internet users in the world

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.

Kinsta's mobile versus desktop traffic in Google Analytics

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.

A bar chart graph of conversion rate by devices

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.

58% smartphone users are more likely to buy from mobile-optimized websites

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 tool

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.

WooCommerce Product Search plugin screenshot

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:

  • WooCommerce Social Login — Eliminates the need for time-consuming account creation or login process. Let your users log in with their social accounts such as Facebook, Twitter, Google, etc.
  • Variation Swatches and Photos — Say goodbye to annoying dropdown menus to select product variations. Instead, give your users easy-to-tap buttons for all your product options.
  • One Page Checkout — Don’t let your customers abandon your site that easily. Allow them to purchase what they want instantly with no extra steps. If you think guest checkout is a great fit for your store, then you can look into enabling it.
  • Checkout Field Editor — Add, remove or change fields from your checkout page. For instance, if you only sell digital products, you do not need to collect shipping addresses.
  • Bolt / Stripe / Amazon Pay / PayPal — Payments are the bane of mobile shopping experience. You can choose from different WooCommerce payment gateway extensions to make it easier to collect payments.

Bolt payment gateway extension for WooCommerce

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.

12. Disable Get Refreshed Fragments AJAX Request

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:

Load time chart for WooCommerce's Get Refreshed Fragments Ajax request

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.

WooCommerce Product settings panel to enable Redirect to Cart behavior

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.

Optimizing WooCommerce Admin Panel

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.

Frontend Optimizations First, Backend Optimizations Second

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.

13. Remove Bloat and Update Everything Regularly

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.

Yoast SEO plugin Big Banner Animated Ad inside the WordPress 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.

14. Disable Object and Database Cache

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.

WordPress W3 Total Cache General Settings Panel

Cache options in W3 Total Cache

W3 Total Cache features the following cache options:

  • Page Cache.
  • Opcode Cache.
  • Database Cache.
  • Object Cache.
  • Browser Cache.
  • Fragment Cache.

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.

W3 Total Cache Disable Database and Object Cache

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.

15. Remove Plugins with High Resource Usage

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 plugin dashboard to find the slowest plugins

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.

Info

If you install Query Monitor, remember to uninstall it when done as it uses a lot of server resources to perform the scans.

16. Use Proper CDN Settings for WordPress

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:

  1. Go to the Page Rules section under your Cloudflare dashboard.
  2. Add *example.com/wp-admin/* in the URL field.
  3. In the settings fields, choose Cache Level and Bypass options.
  4. You can also add extra settings such as Disable Performance and Disable Security (not recommended). These settings are optional.
  5. Then click Save and Deploy.

Cloudflare Page Rules section for disabling cache on admin panel WordPress

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.

17. Streamline WordPress Heartbeat API

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.

WordPress Heartbeat Control plugin panel

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…

WooCommerce Speed Starts with Quality Hosting

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.

An infographic of 4 main types of Managed WordPress hosting

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:

  • Server-level caching with WooCommerce-specific cache rules in place.
  • 2 to 4 PHP workers to handle WooCommerce’s uncached requests without timing them out.
  • WordPress memory limit of 128 MB or more (256 MB is the default on Kinsta).
  • Scalable infrastructure to handle surges in traffic and load.
  • Automatic daily backups (hourly preferred) to ensure that your ecommerce data is safe and secure.
  • A fully secure hosting platform with security features such as regular malware scans, IP Geolocation, and abusive IPs blocking, free SSL, SFTP, SSH, HTTP/2, and TLS 1.3.
  • Nginx or LiteSpeed web server software.
  • Support for developer-friendly features: PHP 8, LXC containers, WP-CLI, Git, MariaDB, Staging environments, etc.
  • High uptime with data centers spread all across the world. Go for the one that has servers close to where your target audience is.
  • Cloudflare integration for increased performance and security.
  • A reliable 24/7 support team to resolve any issues quickly.
  • Great user reviews and a stellar track record.

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).

Performance increase chart after Kinsta upgraded an ecommerce site to GCP's new C2 platform

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.

If your site is generating $1k/day, a 100-millisecond delay might cost you $25k in lost sales annually. Scary, uh?😱💸 Stop losing money and read this guide on speeding up WooCommerce!CLICK TO TWEET

Summary

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:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

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/

#woocommerce #store #powerful 

Best 17 Powerful Ways To Speed Up Your WooCommerce Store
Nat  Grady

Nat Grady

1661302740

Shiny.semantic: Shiny Support for Powerful Semantic UI Library

shiny.semantic 

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.

  • shiny

shiny

library(shiny)
ui <- fluidPage(
  div(
    div(
      a("Link"),
      p("Lorem ipsum, lorem ipsum, lorem ipsum"),
      actionButton("button", "Click")
    )
  )
)
  • shiny.semantic

semantic

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")
    )
  )
)

Shiny.semantic demos

Case studies

🔗 Churn analytics🔗 Fraud detection

Before and after

We show how shiny.semantic can be used to style an app and change it’s look.

🔗 BEFORE Utah Division of Water Quality (DWQ)🔗 AFTER Utah Division of Water Quality (DWQ)

Component examples

Components live demo

See more examples with code in the examples folder:

How to install?

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")

How to use it?

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, ...)

How to contribute?

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.

Troubleshooting

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

  • shiny
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.

Future enhacements

  • create all update functions for input components to mimic shiny as close as possible
  • add some glue code in dsl.R to make using this package smoother
  • adding more semantic components
  • new version release on CRAN

Appsilon

Appsilon is the Full Service Certified RStudio Partner. Learn more at appsilon.com.

Get in touch support+opensource@appsilon.com

Download Details:

Author: Appsilon
Source Code: https://github.com/Appsilon/shiny.semantic 
License: Unknown, MIT licenses found

#r #powerful #ui 

Shiny.semantic: Shiny Support for Powerful Semantic UI Library
Hunter  Krajcik

Hunter Krajcik

1659757740

Logecom: Simple Yet Powerful Logging Library for Dart Projects

Logecom is simple yet powerful and elegant middleware-based logging utility inspired by Nodejs Express library.

Output example

Motivation

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 ;)

Features

There are several LogTranslator implementations available "out of the box" covering the most common logging use cases:

  • HttpFormatter - Allows to log HTTP interaction easily
  • ConsoleTransport - Default console printer. Provide simple and compact log entries formatting with different ways of printing: using stdout, stderr, developer.log() or print() methods

Getting started

To 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);  
}

Usage

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 to ConsoleTransportConfig. Not all printing methods are possible to use in all environments. For example, you will NOT see any logs if you set PrintingMethod.stdErr for Flutter application that runs inside the iPhone Simulator! This is a known issue. Please refer to PrintingMethod inline documentation for more details.

Log Dio HTTP requests

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 ;)

Installing

Use this package as a library

Depend on it

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.

Import it

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

#flutter #dart #powerful #logging 

Logecom: Simple Yet Powerful Logging Library for Dart Projects

BruteforceShield: Powerful Easy to Use Plug-in Brute Force Protection

Brute Force Shield

Features

  • Use for IP address-based protection but can be used with other unique identifiers
  • Does not count re-attempts with same challenge details (e.g. if a user tries the same username/password combination a few times)
  • Designed to use with any data store (file, mysql, cache library) and any framework
  • Can block multiple attempts at the same username earlier than the normal limit (to give users a chance to enter the correct username if they have been trying with the wrong one)

Requirements

  • Composer
  • PHP 7.2 or higher
  • Any data store to persist the User History data between requests

Installation

composer require ali1/brute-force-shield

Configuration

When applying protection, a Ali1\BruteForceShield\Configuration object can be provided.

    $configuration = new Configuration();
    $configuration->setTimeWindow(600) 
        ->setTotalAttemptsLimit(10);
Configuration methodDetails
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)

Usage

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

#php #powerful 

BruteforceShield: Powerful Easy to Use Plug-in Brute Force Protection

Power Machine Learning using Ray.io and Python

Using powerful machine learning algorithms is easy using Ray.io and Python.

https://github.com/ClarityCoders/RayTutorial

#powerful #python #ray 

Power Machine Learning using Ray.io and Python
坂本  篤司

坂本 篤司

1650042300

FormKitを使用した強力なVue.jsフォーム開発

優れたフォームを構築することは、現代のWeb開発では常に困難な作業と見なされてきました。外側のフォームは、選択ボックス、テキストフィールド、ラジオボタン、およびチェックボックスのグループにすぎません。ただし、テーマ設定、検証、およびユーザーにとって直感的なものにすることは、すぐにイライラする可能性があります。

複雑なフォームの処理はすべての開発者にとって面倒であり、フロントエンド開発の主要な問題点の1つになっています。複数の状態を制御し、それらを簡単に入力できるように相互作用させる機能の必要性から、Formik、React Hook Form、Veevalidate、Vuelidate、FormKitなどのライブラリが誕生まし

この投稿では、FormKitと、検証、スタイル設定、ローカリゼーションを使用してVue.jsで強力なフォームを作成するのにどのように役立つかを紹介します。

FormKitとは何ですか?

FormKitは、開発者のエクスペリエンスを一流に保ちながら、Vueであらゆる種類のフォームを開発するのに役立つ強力なフレームワークです。FormKitの背後にあるチームは、人気のあるVueFormulateライブラリで得られたものと同じです。このライブラリに精通している場合は、Vueでフォームを作成するための革新的なアプローチを覚えているでしょう。

VueFormulateは、フォーム要素を作成するために小道具とスロットを多用する単一のコンポーネントを開発者に提供しました。このアプローチにより、フォームの作成、処理、検証が簡単になりました。

FormKitはVueFormulateの拡張バージョンであり、開発者に微妙な魔法のタッチで同じ利点を提供します。今日、FormKitは、開発者が優れたフォームを作成できるように作成された本格的なフレームワークとしての地位を確立しています。

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を使用したフォームの検証

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の非常識なコンポーネントのモジュール性を組み合わせることで、コードをシンプルで理解しやすくしながら、複雑なフォームと状態を作成できます。

FormKitを使用したフォームのスタイリング

ネイティブフォームのスタイリングは簡単ではありません。チェックボックス、テキスト領域、テキストフィールド、およびラジオボタンはすべて<input>フィールドですが、同じスタイルにすることはできません。FormKitは、Genesisと呼ばれる基本テーマを提供します。これはオープンソースであり、プロジェクトに適合させることができます。

FormKitは、シンプルでありながら堅牢なスタイリング機能を提供することで、さらに多くのことを実現します。これについては、以下のセクションで説明します。

カスタムクラス

ほとんどのフロントエンド開発者は、従うべきデザインまたはテーマシステムを持っており、FormKitは、優先順位に従ってクラスを追加する複数の方法を提供することにより、それを可能にします。

ご存知かもしれませんが、入力フィールド全体を表す単一のコンポーネントを使用すると、スタイルを設定するのが面倒になる可能性がありますが、FormKitを使用すると、適切な要素にカスタムクラスを提供するための非常に特殊な小道具、オプション、関数を簡単に提供できます。次のいずれかの方法を使用して、すべてのセクションのクラスを変更できます(特異性の高いものから低いものへ)。

  • {section-key}-class小道具(最も具体的)
  • classes小道具_
  • 構成classesオプション
  • rootClasses構成機能(最も具体的でない)

外側の属性

これらは、開発者が入力のスタイルを設定するために使用できる属性であり、入力がどのように入力されているかについてユーザーにより良いフィードバックを提供するのに役立ちます。、、、、、およびはdata-type、CSSで単純なHTML属性としてスタイル設定されますdata-invaliddata-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の場合と同じようにバインドできるため、スタイリングの柔軟性が高まります。

TailwindCSSを使用したスタイリング

Tailwind CSSを使用している場合、FormKitは必要な複数のインラインスタイルをサポートするだけでなく@formkit/tailwindcss、構成ファイルでフォームにテーマを設定する機能を提供するテンプレートを使用してよりクリーンなコードを作成するのに役立つパッケージ()も提供します。Tailwindガイドを使用したスタイリングは、FormKitドキュメントで入手できます。

国際化(i18n)

国際化とは、ソフトウェアをさまざまな言語や地域の特性に適応させるプロセスです。

執筆時点では、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要素(ノード)を引数として取り、それを微調整する関数です。これらの関数は、ノードが作成されるたび、およびプラグインが追加されるたびに呼び出されます。プラグインの使用例は、サンプルページで確認できます

組み込みのデバウンス

デバウンスは、一部の重いタスクがそれほど頻繁に実行されないようにするために使用されるプログラミング手法であり、コードのパフォーマンスを低下させます。

FormKitは、デバウンスされた入力をオンデマンドで提供し、開発者:delay="<time in milliseconds>"が検証を遅延して実行できる単一の小道具を追加することで、パフォーマンスの高いフォームを作成できるようにします。

組み込みのエラー処理(サーバー側を含む)

FormKitは、検証エラーを適切に処理し、非常に包括的な方法でユーザーに流すことができます。ここで、サーバーで検証のすべてまたは一部を処理し、それらをフロントエンドに返す必要がある場合があります。これらのエラーは、errorsor input-errorsprop、またはnode.setErrors()orを使用してフォームに追加できます$formkit.setErrors()

サーバー側のレンダリング

FormKitはNuxt.jsと完璧に統合され、Nuxtのすべての機能とともに提供するすべてのものにアクセスできます。

強力なスキーマ

FormKitは、非常に柔軟なフォーム処理システムを提供するため、フォームを構築するためのフレームワークとしての地位を確立しています。スキーマはFormKitノードオブジェクトの配列であり、各オブジェクトはHTML要素、コンポーネント、またはテキストノードに対応します。このスキーマは、既存のVue変数を参照し、編集可能な属性と小道具を使用して任意のマークアップまたはコンポーネントをレンダリングできます。

低レベル関数(FormKit Core)

FormKit Coreには、FormKitのほとんどすべての低レベル関数が含まれています。これにより、開発者にフォーム内のコンポーネントの明確に定義されたツリー構造を提供することにより、低レベルの入力処理が可能になります。FormKit Core関数は、フォームの状態の編集、トラバース、リッスン、および追跡に役立ちます。これはより高度であると考えられていますが、モジュラーコード構造が必要な場合に役立ちます。

包括的なドキュメントとFormKitプレイグラウンド

FormKitには優れたドキュメントがあり、ほとんどのAPIは十分にドキュメント化され、構造化されています。ドキュメントは完全に参照された検索機能を提供し、必要なほとんどすべてを見つけるのに役立ちます。

FormKitプレイグラウンドを使用すると、APIを好きなだけ操作できます。テーマを微調整したり、グローバル構成ファイルを編集したり、必要に応じてFormKitを使用して複数のコンポーネントを作成したりすることができます。

結論

FormKitのようなライブラリはゲームチェンジャーです。これらは、最新のWeb開発における主要なフォームの問題を解決するためのシンプルなソリューションを提供し、開発者が他の方法では面倒な作業を行うのに楽しい時間を過ごせるようにします。

FormKitは、開発プロセスを強化し、ユーザーに非常に強力なフォームを提供するという点で驚異的です。

より詳細な比較が必要な場合に備えて、FormKitは、Vueのエコシステム内の他のフォームライブラリとの比較に優れています。

ソース:https ://blog.logrocket.com/powerful-vue-js-form-development-formkit/

#vue #formkit  #powerful 

FormKitを使用した強力なVue.jsフォーム開発

Potente Desarrollo De Formularios Vue.js Con FormKit

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.

¿Qué es FormKit?

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.

Creación de formularios con FormKit

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.

Creando formularios con el <FormKit/>componente

Con 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 typeatributos (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 namede 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>

Generación de formularios a partir de un esquema

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 :schemaaccesorio:

<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 .

Validación de formularios con FormKit

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.

Formas de estilo con FormKit

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.

Clases personalizadas

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):

  • Los {section-key}-classaccesorios (más específicos)
  • el classesaccesorio
  • La classesopción de configuración
  • La rootClassesfunción de configuración (menos específica)

Atributos exteriores

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-completey data-errorstienen 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>

estilo esquemático

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.

Estilo con Tailwind CSS

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.

Internacionalización (i18n)

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.

Más funciones interesantes de FormKit

Complementos

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 .

Antirrebote incorporado

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.

Manejo de errores incorporado (incluido el lado del servidor)

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 errorso input-errorsprop, o node.setErrors()o $formkit.setErrors().

Representación del lado del servidor

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.

Un esquema poderoso

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.

Funciones de bajo nivel (FormKit Core)

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.

Documentación completa y área de juegos FormKit

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.

Conclusión

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/

#vue #formkit  #powerful 

Potente Desarrollo De Formularios Vue.js Con FormKit

PowerAutomateでのMod関数の使用

Power Automateでは、目的の結果を得ることができるように、モジュラー算術演算を実行する必要がある場合があります。例として、ホテルにいる顧客に基づいてテーブルを待っている顧客の数を確認できます。これにより、顧客は待機している顧客の数に関する情報を取得して、それに応じて計画を立てることができます。

ステップ1

次の図に示すように、URLmake.powerapps.comを使用してユーザー名とパスワードを入力して必要なPowerApps環境にログインし、左側の[フロー]をクリックします。

PowerAutomateでのMod関数の使用

ステップ2

手順1の後、[新しいフロー]をクリックし、インスタントクラウドフローを選択して、トリガーを手動でトリガーし、次の図に示すように[作成]をクリックします

PowerAutomateでのMod関数の使用

ステップ3

後はステップ2、並列分岐を追加して、など一部の名前フローでMOD関数とは、取る初期化変数アクションをし、としてそれをステップ名を提供総顧客、その後、片側のように入力を提供

名前:顧客

タイプ:整数

値:17

下の図に示すように。

PowerAutomateでのMod関数の使用

ステップ4

手順3の後、並列ブランチの反対側で変数の初期化アクションを実行、5つのテーブルのテーブルあたりの最大顧客数として名前を付けて提供します。

名前:テーブル座ることができる最大容量

タイプ:整数

値:3

下の図に示すように。

PowerAutomateでのMod関数の使用

ステップ5

ステップ4の後、作成アクションを実行し、「テーブル待機している顧客の数を取得」という名前を付けます。2つのパラメーターdividendとdivisorが両方とも数値であることを期待するmod関数を入力に提供します。

Mod(dividend: number,divisor: number)

ベーシック

コピー

ステップ3、ステップ4の式に値を指定します

mod(variables('Customers'),variables('Table Maximum Capacity Allowed To Sit'))

ベーシック

コピー

次の図に示すように、[ OK ] / [更新]をクリックします。

PowerAutomateでのMod関数の使用

ステップ6

手順5の後、フローを保存し、フローをテストして実行すると、次の図に示すように、5つのテーブルがそれぞれ3つのメンバーで占められているため、17のメンバーの中で2つのメンバーが待機していると推測される3つの数値が書き込まれる結果を確認します。

PowerAutomateでのMod関数の使用

ノート

  1. 式を試すときは、必ずフローを保存して実行してください。
  2. MSのドキュメントは ここにあります

結論

このようにして、PowerAutomateフローのModのような算術演算を簡単に実行できます。

Link: https://www.c-sharpcorner.com/article/usage-of-mod-function-in-power-automate/

#powerful #automation 

PowerAutomateでのMod関数の使用
Tamale  Moses

Tamale Moses

1632474000

Learn Powerful New GraphQL tools

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.

#graphql #powerful 
 

Learn Powerful New GraphQL tools

5 Powerful and FREE Photoshop Alternatives

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

5 Powerful and FREE Photoshop Alternatives