<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dmitrii Pashkevich on Medium]]></title>
        <description><![CDATA[Stories by Dmitrii Pashkevich on Medium]]></description>
        <link>https://medium.com/@dipiash?source=rss-ab2d8c832e5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jG9p4QsAq9_lz3WLbsc9OA.jpeg</url>
            <title>Stories by Dmitrii Pashkevich on Medium</title>
            <link>https://medium.com/@dipiash?source=rss-ab2d8c832e5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:32:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dipiash/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TanStack DB Query: Step-by-step guide to combining parameter-based loading and normalized storage]]></title>
            <link>https://medium.com/@dipiash/tanstack-db-query-step-by-step-guide-to-combining-parameter-based-loading-and-normalized-storage-f1e7eb3ff55e?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e7eb3ff55e</guid>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tanstack]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 16:37:05 GMT</pubDate>
            <atom:updated>2025-09-27T16:37:05.312Z</atom:updated>
            <content:encoded><![CDATA[<h3>TanStack DB + TanStack Query: Step-by-step guide to combining parameter-based loading and normalized storage</h3><p>In this guide, I will demonstrate how to use <a href="https://tanstack.com/query/latest">TanStack Query</a> v5 and <a href="https://tanstack.com/db/latest">TanStack DB</a> to achieve a seamless user interface with incremental updates without “locally rewriting” the useQuery cache (excluding pagination options).<br>The query parameters will be kept on the TanStack Query side, and the data will be kept in the normalized TanStack DB store.<br>Also it will look at common mistakes and optimistic updates with rollback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*823tOYboKzz051AeIcyxuQ.jpeg" /><figcaption>TanStack DB + TanStack Query (React)</figcaption></figure><blockquote><strong>Be note on 27.09.2025</strong></blockquote><blockquote><em>TanStack DB </em><a href="https://github.com/TanStack/db/discussions/469"><em>does not currently support parameterized queries</em></a><em> and only allows you to query the entire collection at once.</em></blockquote><h4>Introduction</h4><ul><li>React Query controls the network and parameters (page, perPage, filters).</li><li>TanStack DB is responsible for storing cached data based on IDs (normalized data out of the box) and “live” selections in the user interface.</li><li>This example shows how to use a simple page model: wipe and insert. Previous pages are not saving.</li><li>Do optimistic updates via useMutation (onMutate → onError → onSuccess).</li></ul><h4>Project Structure</h4><pre>.<br>├─ dist/             # Generated Vite build output (ignored in source control)<br>├─ src/<br>│  ├─ api/<br>│  │  ├─ client/     # Shared QueryClient instance<br>│  │  ├─ handlers/   # Mock REST handlers simulating backend behavior<br>│  │  └─ types/      # TypeScript DTOs for API payloads<br>│  ├─ db/            # TanStack DB collections and sync helpers<br>│  ├─ hooks/         # Reusable hooks for data fetching and mutations<br>│  ├─ App.tsx        # Users table UI and pagination logic<br>│  └─ index.tsx      # React entry point and root render<br>├─ eslint.config.mjs # Project-wide ESLint configuration<br>├─ package.json      # Scripts, dependencies, and metadata<br>├─ tsconfig.json     # TypeScript compiler options<br>└─ vite.config.ts    # Vite build and dev server configuration</pre><h4>Guide</h4><p>The first step is to create a basic query client.</p><pre>// src/api/client/queryClient.ts<br><br>import { QueryClient } from &#39;@tanstack/react-query&#39;<br><br>export const queryClient = new QueryClient()</pre><p>The second step is to describe the types of users and user lists that will receive from the API.</p><blockquote>These types can be generated from the Open API schema. I described how to do this in the <a href="https://medium.com/quadcode-life/fully-typed-forms-based-on-api-schema-with-react-hook-form-openapi-typescript-and-yup-validation-93ba1321368b">article</a>.</blockquote><pre>// src/api/types/users.types.ts<br><br>export type User = {<br>  id: number<br>  email: string<br>  first_name: string<br>  last_name: string<br>}<br><br>export type UsersList = {<br>  totalCount: number<br>  data: User[]<br>}</pre><p>Next, mock requests for obtaining a list of data and updating a single entity from that list will be described.</p><pre>// src/api/handlers/users.mock.ts<br><br>import { User, UsersList } from &#39;../types/users.types&#39;<br><br>export const fetchUsersMock = async (parameters: { page?: number; perPage?: number } = {}): Promise&lt;UsersList&gt; =&gt; {<br>  const page = parameters.page ?? 1<br>  const perPage = parameters.perPage ?? 10<br>  const totalCount = 125<br><br>  const start = (page - 1) * perPage + 1<br>  const end = Math.min(start + perPage - 1, totalCount)<br><br>  const data: User[] = []<br><br>  for (let id = start; id &lt;= end; id++) {<br>    data.push({<br>      first_name: `User${id}`,<br>      id,<br>      last_name: `Demo`,<br>      email: `@example.com&quot;&gt;user${id}@example.com`,<br>    })<br>  }<br><br>  await new Promise((resolve) =&gt; setTimeout(resolve, 300)) // simulate network<br><br>  return { data, totalCount }<br>}<br><br>export const updateUserMock = async (id: number, patch: Partial&lt;User&gt;): Promise&lt;User&gt; =&gt; {<br>  const current: User = {<br>    first_name: `User${id}`,<br>    id,<br>    last_name: `Demo`,<br>    email: `@example.com&quot;&gt;user${id}@example.com`,<br>  }<br>  const updated = { ...current, ...patch }<br><br>  await new Promise((resolve) =&gt; setTimeout(resolve, 200))<br><br>  return updated<br>}</pre><blockquote><strong>Important:</strong> This is a mockup, it does not save changes. If you leave the page and return, your edits will disappear (as expected for a demo).</blockquote><p>Next, let’s describe the TanStack DB collection for storing users in a normalized store.</p><pre>// src/db/usersCollection.ts<br><br>import { createCollection } from &#39;@tanstack/react-db&#39;<br><br>import { queryCollectionOptions, type QueryCollectionUtils } from &#39;@tanstack/query-db-collection&#39;<br><br>import { queryClient } from &#39;../api/client/queryClient&#39;<br>import { User } from &#39;../api/types/users.types&#39;<br><br>export const usersCollection = createCollection&lt;User, number | string, QueryCollectionUtils&lt;User&gt;&gt;(<br>  queryCollectionOptions&lt;User&gt;({<br>    id: &#39;users&#39;,<br>    getKey: (u) =&gt; u.id,<br>    queryClient,<br>    queryFn: async ({ queryKey }) =&gt; queryClient.getQueryData&lt;User[]&gt;(queryKey) ?? [],<br>    queryKey: [&#39;users:collection&#39;],<br>    startSync: true,<br>  }),<br>)<br><br>// Guaranteed readiness before direct recordings.<br>export const ensureUsersCollectionIsReady = async () =&gt; {<br>  if (!usersCollection.isReady()) {<br>    usersCollection.startSyncImmediate()<br>    await usersCollection.stateWhenReady()<br>  }<br>}</pre><p>The next step is to explain how user requests are handled with the transfer of pagination parameters to the request and the passing of data from the response to the previously created collection.</p><p>For each <em>page</em>/<em>perPage</em>, make a request via React Query, clear the store and insert the current page data. To display data in the UI, read from the collection via useLiveQuery(…select…).</p><pre>// src/hooks/useUsersPage.ts<br><br>import { useLiveQuery } from &#39;@tanstack/react-db&#39;<br>import { useQuery, useQueryClient } from &#39;@tanstack/react-query&#39;<br><br>import { fetchUsersMock } from &#39;../api/handlers/users.mock&#39;<br>import { type UsersList } from &#39;../api/types/users.types&#39;<br>import { ensureUsersCollectionIsReady, usersCollection } from &#39;../db/usersCollection&#39;<br><br>type Parameters_ = { page: number; perPage: number }<br><br>export const USERS_LIST_KEY = &#39;users:list&#39;<br>const USERS_LIST_TOTAL_KEY = &#39;users:list:total&#39;<br><br>export const useUsersPage = (parameters: Parameters_) =&gt; {<br>  const queryClient = useQueryClient()<br><br>  const { error, isFetching } = useQuery&lt;UsersList&gt;({<br>    queryFn: async () =&gt; {<br>      const dto = await fetchUsersMock(parameters)<br><br>      await ensureUsersCollectionIsReady()<br><br>      usersCollection.utils.writeBatch(() =&gt; {<br>        const incoming = new Map(dto.data.map((u) =&gt; [u.id, u]))<br><br>        // remove old items which no in new data<br>        // need this to avoid DuplicateKeyInBatchError<br>        for (const [k] of usersCollection.entries()) {<br>          if (!incoming.has(k as number)) {<br>            usersCollection.utils.writeDelete(k)<br>          }<br>        }<br><br>        // insert / update with new items<br>        for (const u of incoming.values()) {<br>          usersCollection.utils.writeUpsert(u)<br>        }<br>      })<br><br>      queryClient.setQueryData([USERS_LIST_TOTAL_KEY], dto.totalCount)<br><br>      return dto<br>    },<br>    queryKey: [USERS_LIST_KEY, parameters],<br>    retry: false,<br>  })<br><br>  const { data: users = [] } = useLiveQuery((q) =&gt;<br>    q.from({ u: usersCollection }).select(({ u }) =&gt; ({<br>      first_name: u.first_name,<br>      id: u.id,<br>      last_name: u.last_name,<br>      email: u.email,<br>    })),<br>  )<br><br>  const totalCount = queryClient.getQueryData&lt;number&gt;([USERS_LIST_TOTAL_KEY]) || 0<br><br>  return { error, isFetching, totalCount, users }<br>}</pre><blockquote><strong>Why was Query and DB separated?</strong></blockquote><blockquote><strong>TanStack DB </strong><a href="https://github.com/TanStack/db/discussions/469"><strong>does not currently support parameterized queries</strong></a><strong> and only allows you to query the entire collection at once. </strong>Thats why it’s convenient.</blockquote><blockquote>Query parameters (pages/filters) live separately in React Query and data lives in a normalized store. This makes updating records by ID easier, as well as performing optimistic updates without touching the loading logic. It also eliminates the need to rewrite the logic provided by TanStack DB via <a href="https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata">setQueryData</a> from TanStack Query from scratch.</blockquote><p>Next, describe an optimistic update with a rollback in case of an error.</p><p><em>onMutate</em> — patch the UI immediately. <em>onError</em> — rollback on error. onSuccess — apply data from server.</p><pre>// src/hooks/useOptimisticUserUpdate.ts<br><br>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;<br><br>import { updateUserMock } from &#39;../api/handlers/users.mock&#39;<br>import { type User } from &#39;../api/types/users.types&#39;<br>import { ensureUsersCollectionIsReady, usersCollection } from &#39;../db/usersCollection&#39;<br>import { USERS_LIST_KEY } from &#39;./useUsersPage&#39;<br><br>type UpdateUserContext = { id: number; prev?: User }<br><br>export const useOptimisticUserUpdate = () =&gt; {<br>  const queryClient = useQueryClient()<br><br>  return useMutation&lt;User, Error, { id: number; patch: Partial&lt;User&gt; }, UpdateUserContext&gt;({<br>    mutationFn: ({ id, patch }) =&gt; updateUserMock(id, patch),<br>    // 1. Patch the UI immediately<br>    onMutate: async ({ id, patch }) =&gt; {<br>      await queryClient.cancelQueries({ queryKey: [USERS_LIST_KEY] })<br>      await ensureUsersCollectionIsReady()<br><br>      const previous = usersCollection.get(id)<br><br>      if (previous) {<br>        usersCollection.utils.writeUpdate({ ...previous, ...patch })<br>      }<br><br>      return { id, prev: previous }<br>    },<br>    // 2. Rollback on error<br>    onError: async (_error, _variables, context) =&gt; {<br>      if (context?.prev) {<br>        await ensureUsersCollectionIsReady()<br>        usersCollection.utils.writeUpdate(context.prev)<br>      }<br>    },<br>    // 3. Apply data from server<br>    onSuccess: async (serverUser) =&gt; {<br>      await ensureUsersCollectionIsReady()<br>      usersCollection.utils.writeUpsert(serverUser)<br>    },<br>  })<br>}</pre><p>Next, demonstrate how everything works together by showing a working example of a table with pagination and <em>first_name</em> updates.</p><pre>// src/App.tsx<br><br>import { QueryClientProvider } from &#39;@tanstack/react-query&#39;<br>import { useState } from &#39;react&#39;<br><br>import { queryClient } from &#39;./api/client/queryClient&#39;<br>import { useOptimisticUserUpdate } from &#39;./hooks/useOptimisticUserUpdate&#39;<br>import { useUsersPage } from &#39;./hooks/useUsersPage&#39;<br><br>const PER_PAGE = 10<br><br>const UsersTable = () =&gt; {<br>  const [page, setPage] = useState(1)<br>  const { error, isFetching, totalCount, users } = useUsersPage({ page, perPage: PER_PAGE })<br>  const { mutate: patchUser } = useOptimisticUserUpdate()<br><br>  if (error) {<br>    return (<br>      &lt;div style={{ padding: 16, border: &#39;1px solid #f33&#39;, borderRadius: 8 }}&gt;<br>        &lt;div style={{ fontWeight: 600, marginBottom: 8 }}&gt;Error&lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br><br>  return (<br>    &lt;div style={{ fontFamily: &#39;sans-serif&#39;, padding: 16 }}&gt;<br>      &lt;h3&gt;<br>        Users ({totalCount}) {isFetching ? &#39;…&#39; : &#39;&#39;}<br>      &lt;/h3&gt;<br>      &lt;table&gt;<br>        &lt;thead&gt;<br>          &lt;tr&gt;<br>            &lt;th&gt;ID&lt;/th&gt;<br>            &lt;th&gt;Email&lt;/th&gt;<br>            &lt;th&gt;Name&lt;/th&gt;<br>            &lt;th&gt;Actions&lt;/th&gt;<br>          &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          {users.map((u) =&gt; (<br>            &lt;tr key={u.id}&gt;<br>              &lt;td&gt;{u.id}&lt;/td&gt;<br>              &lt;td&gt;{u.email}&lt;/td&gt;<br>              &lt;td&gt;<br>                {u.first_name} {u.last_name}<br>              &lt;/td&gt;<br>              &lt;td&gt;<br>                &lt;button onClick={() =&gt; patchUser({ id: u.id, patch: { first_name: &#39;UPDATED&#39; } })}&gt;Rename to UPDATED (optimistic)&lt;/button&gt;<br>              &lt;/td&gt;<br>            &lt;/tr&gt;<br>          ))}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>      &lt;div style={{ display: &#39;flex&#39;, alignItems: &#39;center&#39;, gap: 8, marginTop: 12 }}&gt;<br>        &lt;button disabled={page === 1 || isFetching} onClick={() =&gt; setPage((p) =&gt; Math.max(1, p - 1))} style={{ padding: &#39;6px 10px&#39; }}&gt;<br>          ← Prev<br>        &lt;/button&gt;<br>        &lt;div style={{ padding: &#39;0 8px&#39; }}&gt;Page {page}&lt;/div&gt;<br>        &lt;button disabled={isFetching || PER_PAGE * page &gt;= totalCount} onClick={() =&gt; setPage((p) =&gt; p + 1)} style={{ padding: &#39;6px 10px&#39; }}&gt;<br>          Next →<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export const App = () =&gt; (<br>  &lt;QueryClientProvider client={queryClient}&gt;<br>    &lt;UsersTable /&gt;<br>  &lt;/QueryClientProvider&gt;<br>)</pre><h3>Conclusion</h3><p>This article outlines the responsibilities of two powerful tools. TanStack Query v5 handles network and query parameters, and TanStack DB manages normalized storage and provides instant UI updates via “live” queries. This division eliminates the need for manual useQuery cache patching, makes the code more predictable, and simplifies local changes by ID.</p><p>Also examined a simple, straightforward wipe-insert pattern for pagination, ensuring that only the current page is displayed on the screen. Additionally, demonstrated how to read data via useLiveQuery(…select(…)), returning regular objects and enabling reactivity on specific fields.</p><p>Implemented a real optimistic update with rollback (onMutate → onError → onSuccess), where the UI updates immediately, errors are handled without “flickering,” and successful server responses resolve the issue.</p><p>In short, the combination of TanStack Query and TanStack DB provides clean architecture, a smooth user experience, and controllable data. You can manage queries where it makes sense and update the UI exactly where you need to.</p><p>In practice, pay attention to the little things that often cause problems (please find below).</p><p>The final code you can find on Github: <a href="https://github.com/dipiash/tanstack-db-react-query-template">https://github.com/dipiash/tanstack-db-react-query-template</a></p><p>The demo: <a href="https://dipiash.github.io/tanstack-db-react-query-template/">https://dipiash.github.io/mantine-scrollable-tabs/</a></p><h3>As a bonus… Common mistakes and how to fix them</h3><h4><em>useLiveQuery</em> returns <em>{ type: ‘ref’ }</em> instead of data</h4><pre>// Do not do this<br>// returns ref/proxy — UI does not see field changes<br>const { data: users = [] } = useLiveQuery((q) =&gt;<br>    q.from({ u: usersCollection }).select(({ u }) =&gt; u),<br>  )<br><br>// Do this<br>// always explicitly list the fields for which you want reactivity.<br>const { data: users = [] } = useLiveQuery((q) =&gt;<br>    q.from({ u: usersCollection }).select(({ u }) =&gt; ({<br>      first_name: u.first_name,<br>      id: u.id,<br>      last_name: u.last_name,<br>      email: u.email,<br>    })),<br>  )</pre><h4><em>Can not convert object to primitive value</em></h4><pre>// Do not do this<br>// u.id — it&#39;s a proxy; Number(u.id) will throw an error/give an incorrect result<br>const { data } = useLiveQuery((q) =&gt;<br>  q.from({ u: usersCollection })<br>   .where(({ u }) =&gt; Number(u.id) &gt; 10)<br>   .select(({ u }) =&gt; ({ id: u.id })),<br>)<br><br>// Do this<br>// use builders from @tanstack/db: eq, lt, gt, inArray, between, etc.<br>import { gt } from &#39;@tanstack/db&#39;<br><br>const { data } = useLiveQuery((q) =&gt;<br>  q.from({ u: usersCollection })<br>   .where(({ u }) =&gt; gt(u.id, 10))<br>   .select(({ u }) =&gt; ({ id: u.id })),<br>)</pre><h4>DuplicateKeyInBatchError error</h4><pre>// Do not do this<br>// in ONE batch, delete and upsert by ONE id<br>usersCollection.utils.writeBatch(() =&gt; {<br>  usersCollection.utils.writeDelete(42)<br>  usersCollection.utils.writeUpsert({ id: 42, first_name: &#39;A&#39;, last_name: &#39;B&#39;, email: &#39;a@b.c&#39; })<br>})<br><br>// Do this<br>// split into two batches<br>usersCollection.utils.writeBatch(() =&gt; {<br>  usersCollection.utils.writeDelete(42)<br>})<br>usersCollection.utils.writeBatch(() =&gt; {<br>  usersCollection.utils.writeUpsert({ id: 42, first_name: &#39;A&#39;, last_name: &#39;B&#39;, email: &#39;a@b.c&#39; })<br>})<br><br>// Do this<br>// OR deduplicate in advance<br>usersCollection.utils.writeBatch(() =&gt; {<br>  const incoming = new Map(dto.data.map((u) =&gt; [u.id, u]))<br><br>  // remove old items which no in new data<br>  for (const [k] of usersCollection.entries()) {<br>    if (!incoming.has(k as number)) {<br>      usersCollection.utils.writeDelete(k)<br>    }<br>   }<br><br>   // insert / update with new items<br>   for (const u of incoming.values()) {<br>     sersCollection.utils.writeUpsert(u)<br>   }<br>})</pre><h4>SyncNotInitializedError: write until the collection is ready</h4><pre>// Do not do this<br>// direct entries before the collection was moved to ready<br>usersCollection.utils.writeUpsert(user)<br><br>// Do this<br>// guarantee ready (once at startup or before recording)<br>if (!usersCollection.isReady()) {<br>  usersCollection.startSyncImmediate()<br>  await usersCollection.stateWhenReady()<br>}<br>usersCollection.utils.writeUpsert(user)</pre><h4>Key type mismatch: ‘42’ vs 42</h4><pre>// Do not do this<br>// if you use a number keys, but you are searching for a string<br>usersCollection.get(&#39;42&#39;) // undefined<br><br>// Do this<br>// use one type of key and bring in the input<br>const id = Number(maybeStringId)<br>usersCollection.get(id)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e7eb3ff55e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Production-ready listener for Supabase realtime Postgres changes in Node.js]]></title>
            <link>https://medium.com/@dipiash/supabase-realtime-postgres-changes-in-node-js-2666009230b0?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2666009230b0</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 12:04:47 GMT</pubDate>
            <atom:updated>2025-08-23T12:05:22.840Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I will show you how to transform an unreliable Supabase Realtime subscription that dropped every 30 minutes into a robust, self-healing service with clean teardown, exponential backoff and dependency injection. We’ll work through the process step by step, from creating the client to setting up a subscription class that you can use in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jR3FmMDbje5sJRRI7LMICg.png" /><figcaption>Supabase realtime Postgres changes subscription log</figcaption></figure><h4>Introduction</h4><p>Taking an <a href="https://supabase.com/docs/guides/realtime/postgres-changes">example</a> from the Supabase Realtime documentation and adding a little production: keeping the connection open and performing automatic retries, reveals some issues.</p><ul><li>The channel may signal CHANNEL_ERROR and then close (CLOSED), which is essentially the same incident and makes it easy to schedule two retries.</li><li>Uncleaned timers and non-unique channel names can lead to races and duplicate events.</li><li>Sometimes it seems that the connection is simply hanging and then it breaks off steadily after ~30 minutes.</li></ul><p>As a result, instead of a simple retry, days of troubleshooting begin. Somewhere it doesn’t retry, somewhere it freezes and somewhere it crashes and doesn’t recover.</p><p>Let’s make it clear.</p><h4>Creating the Supabase client</h4><pre>import { createClient } from &#39;@supabase/supabase-js&#39;<br><br>const supabaseUrl = process.env.SUPABASE_URL!<br>const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY!<br><br>export const supabaseClient = createClient(supabaseUrl, supabaseKey)</pre><p>For simplicity I’m not importing the generated database schema here. If you have one, I recommend using it. This will give you autocompletion, safer filters and typed payloads.</p><h4>The subscription class’s target interface</h4><p>One small, composable unit that:</p><ul><li>listens to INSERT events on a single table;</li><li>calls a handler for each payload;</li><li>reconnects with exponential backoff.</li></ul><p>It should be easy to test because Supabase client is injectable.</p><pre>interface SupabaseOnInsertListenerPropertiesInterface&lt;TableType extends { [key: string]: any }&gt; {<br>  /**<br>   * The multiplier of the exponential backoff between reconnection attempts<br>   * Default is `1.5`<br>   *<br>   * @example The result: 30s → 45s → 67.5s ...<br>   **/<br>  backoffMultiplier?: number<br>  /**<br>   * Basic delay (in milliseconds) before the first retry<br>   * Default is `30_000`ms<br>   */<br>  baseRetryDelay?: number<br>  /**<br>   * The base name of the channel<br>   */<br>  channelBaseName: string<br>  /**<br>   * The database schema to listen to<br>   * Default is `public`<br>   */<br>  databaseSchemaName?: string<br>  /**<br>   * The maximum number of reconnection attempts after which the service gives up<br>   * Default is `10`<br>   */<br>  maxRetries?: number<br>  /**<br>   * Upper limit of delay between attempts (in milliseconds). Used as a cap for backoff<br>   * Default is `300_000`ms.<br>   */<br>  maxRetryDelay?: number<br>  /**<br>   * INSERT event handler. Called for each payload<br>   */<br>  onInsert: (payload: RealtimePostgresInsertPayload&lt;TableType&gt;) =&gt; void<br>  /**<br>   * The number of reconnection attempts made since the last successful subscription<br>   */<br>  retryCount?: number<br>  /**<br>   * Supabase Client<br>   */<br>  supabaseClient: Pick&lt;SupabaseClient, &#39;channel&#39; | &#39;removeChannel&#39;&gt;<br>  /**<br>   * The database table to listen to<br>   */<br>  tableName: string<br>}</pre><h4>Service configuration</h4><p>It sets all configurable parameters and initialises the state for isRetrying and retryTimeout.</p><pre>export class SupabaseOnInsertListenerService&lt;TableType extends { [key: string]: any }&gt; {<br>  private backoffMultiplier: number<br>  private baseRetryDelay: number<br>  private channel: null | ReturnType&lt;typeof this.supabaseClient.channel&gt; = null<br>  private channelBaseName: string<br>  private databaseSchemaName: string<br>  private isRetrying = false<br>  private maxRetries: number<br>  private maxRetryDelay: number<br>  private onInsert: (payload: RealtimePostgresInsertPayload&lt;TableType&gt;) =&gt; void<br>  private retryCount: number<br>  private retryTimeout: ReturnType&lt;typeof setTimeout&gt; | undefined<br>  private supabaseClient: Pick&lt;SupabaseClient, &#39;channel&#39; | &#39;removeChannel&#39;&gt;<br>  private tableName: string<br><br>  constructor({<br>    backoffMultiplier = 1.5,<br>    baseRetryDelay = 30_000,<br>    channelBaseName,<br>    databaseSchemaName = &#39;public&#39;,<br>    maxRetries = 10,<br>    maxRetryDelay = 300_000,<br>    onInsert,<br>    retryCount = 0,<br>    supabaseClient,<br>    tableName,<br>  }: SupabaseOnInsertListenerPropertiesInterface&lt;TableType&gt;) {<br>    this.maxRetries = maxRetries<br>    this.baseRetryDelay = baseRetryDelay<br>    this.maxRetryDelay = maxRetryDelay<br>    this.backoffMultiplier = backoffMultiplier<br>    this.retryCount = retryCount<br>    this.tableName = tableName<br>    this.onInsert = onInsert<br>    this.channelBaseName = channelBaseName<br>    this.supabaseClient = supabaseClient<br>    this.databaseSchemaName = databaseSchemaName<br>  }<br><br>  subscribe = async () =&gt; {}<br><br>  private removeExistingChannel = async () =&gt; {}<br><br>  private resetRetries = () =&gt; {}<br><br>  private retryToSubscribe = async () =&gt; {}<br><br>  // ...<br>}</pre><p>I have added a few class methods that need to be implemented below:</p><ul><li>the <em>removeExistingChannel</em> function safely drops the previous channel before creating a new one;</li><li><em>resetRetries</em> help once we have re-established the subscription. Any pending retries must be cancelled and all counters must be reset;</li><li><em>retryToSubscribe</em> handle transient failures gently. Don’t spam the provider; escalate wait times with exponential backoff with a cap. Schedule a single future subscribe();</li><li><em>subscribe</em> function is the core function for handling Supabase subscriptions to Postgres changes. Handle all subscription statuses (SUBSCRIBED, TIMED_OUT, CLOSED, CHANNEL_ERROR).</li></ul><h4><em>removeExistingChannel </em>class <em>method</em></h4><p>There must always be exactly one active channel. Skip teardown and you’ll get duplicate events and race conditions. The process is simple: drop the previous channel safely before creating a new one.</p><pre>private removeExistingChannel = async () =&gt; {<br>  if (!this.channel) {<br>    return<br>  }<br><br>  try {<br>    await this.supabaseClient.removeChannel(this.channel)<br>    console.info(`Realtime channel (${this.channel.topic}) cleaned up on new call`)<br>  } catch (error) {<br>    console.error(`Error cleaning up old channel:`, error)<br>  } finally {<br>    this.channel = null<br>  }<br>}</pre><h4><em>resetRetries</em> class method</h4><p>It is essential that once the subscription has been re-established, any pending retries are cancelled and all counters are cleared. The way to do this is to clear and null the timer and reset the flags.</p><pre>private resetRetries = () =&gt; {<br>  this.isRetrying = false<br>  this.retryCount = 0<br><br>  clearTimeout(this.retryTimeout)<br>  this.retryTimeout = undefined<br>}</pre><h4><em>retryToSubscribe</em> class method</h4><p>Handle transient failures. Don’t spam and escalate wait times. Use exponential backoff with a cap and schedule a single future <em>subscribe()</em>.</p><pre>private retryToSubscribe = async () =&gt; {<br>  this.isRetrying = true<br>  this.retryCount += 1<br><br>  if (this.retryCount &gt; this.maxRetries) {<br>    console.error(`Max retries (${this.maxRetries}) exceeded`)<br><br>    return<br>  }<br><br>  const delay = Math.min(this.baseRetryDelay * Math.pow(this.backoffMultiplier, this.retryCount - 1), this.maxRetryDelay)<br><br>  console.warn(`Retry attempt ${this.retryCount} in ${Math.round(delay / 1000)}s`)<br><br>  clearTimeout(this.retryTimeout)<br>  this.retryTimeout = setTimeout(() =&gt; {<br>    this.isRetrying = false<br>    this.subscribe()<br>  }, delay)<br>}</pre><h4><em>subscribe</em> class method</h4><p>It’s the core function, that:</p><ul><li>tear down any old channel;</li><li>build a unique channel name: ${this.channelBaseName}-${Date.now()}. This will avoid collisions if the previous channel hasn’t fully shut down yet;</li><li>attach an INSERT handler.</li></ul><p>Than handle status updates:</p><ul><li>SUBSCRIBED indicate that all good;</li><li>CHANNEL_ERROR, CLOSED, TIMED_OUT indicate that need to schedule a retry.</li><li>If already retrying, skip duplicate scheduling.</li></ul><pre>subscribe = async () =&gt; {<br>  await this.removeExistingChannel()<br><br>  console.info(&#39;Creating new realtime subscription...&#39;)<br><br>  // Add Date.now() to exclude collision between retries<br>  const channelName = `${this.channelBaseName}-${Date.now()}`<br><br>  console.info(`Channel name is: ${channelName}`)<br><br>  this.channel = this.supabaseClient.channel(channelName)<br><br>  this.channel<br>    .on&lt;TableType&gt;(&#39;postgres_changes&#39;, { event: &#39;INSERT&#39;, schema: this.databaseSchemaName, table: this.tableName }, async (payload) =&gt; {<br>      console.info(&#39;Insert received:&#39;, payload)<br><br>      this.onInsert(payload)<br>    })<br>    .subscribe(async (status, error) =&gt; {<br>      console.info(`Channel status: ${status}`)<br><br>      if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {<br>        console.info(&#39;Realtime subscription established&#39;)<br><br>        this.resetRetries()<br><br>        return<br>      }<br><br>      if (this.isRetrying) {<br>        console.warn(`Skipping retry due to: isRetrying = ${this.isRetrying}`)<br><br>        return<br>      }<br><br>      if (status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR) {<br>        console.error(&quot;Can&#39;t subscribe on channel:&quot;, error)<br>      }<br><br>      if (<br>        status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR ||<br>        status === REALTIME_SUBSCRIBE_STATES.CLOSED ||<br>        status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT<br>      ) {<br>        await this.retryToSubscribe()<br>      }<br>    })<br>}</pre><h4>How to use SupabaseOnInsertListenerService</h4><pre>// ... All the code above<br><br>interface TableSchemaInterface {<br>  id: number<br>  // ...<br> }<br><br>const visaSlotsOnInsertChannel = new SupabaseOnInsertListenerService&lt;TableSchemaInterface&gt;({<br>  supabaseClient,<br>  tableName: &#39;table_name_example&#39;,<br>  channelBaseName: &#39;table_name_example-insert&#39;,<br>  onInsert: (payload: RealtimePostgresInsertPayload&lt;VisaSlot&gt;) =&gt; {<br>    console.info(&#39;Payload received:&#39;, payload.new)<br>  },<br>})<br><br>visaSlotsOnInsertChannel.subscribe()</pre><h4>Conclusion</h4><p>You will now learn how to transform a “toy” Supabase Realtime subscription into a production-ready service.<br>Establish key reliability practices: clean teardown, one retry per incident, and accurate logs. This listener is resistant to temporary failures, does not spawn “hanging” channels, does not get caught in retry loops, correctly clears timers, and recovers predictably. It is straightforward to type (database schema) and improve in the future.</p><p><em>P.S.<br></em>Use “logger“ injection instead of ‘console.log’</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2666009230b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tabs component with scrolling support]]></title>
            <link>https://medium.com/@dipiash/tabs-component-with-scrolling-support-2fbf128c078d?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fbf128c078d</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[requestanimationframe]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mutationobserver]]></category>
            <category><![CDATA[scrollintoview]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 20:06:11 GMT</pubDate>
            <atom:updated>2025-04-12T10:18:59.231Z</atom:updated>
            <content:encoded><![CDATA[<h4>Smooth tab navigation: scrollIntoView, MutationObserver and requestAnimationFrame in action</h4><p>In this article, we’ll look at how to improve the Tabs component by adding horizontal scrolling and auto-scrolling to the active tab. We’ll look at how to use CSS, MutationObserver and requestAnimationFrame based throttling to make sure that the active tab always stays in view — when mounted, DOM changes and window resizing. The result will be a flexible and responsive interface for working with a large number of tabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*CgLG3wOjcN_evnJEnBozYg.png" /></figure><h4>Introduction</h4><p>The Tabs component allows users to switch between different panels to display content. The Mantine library is used for implementation, which makes it easy to work with the <a href="https://mantine.dev/core/tabs/">Tabs</a> component and its styling.</p><p>However, out of the box, the <a href="https://mantine.dev/core/tabs/">Tabs</a> component in the horizontal orientation in Mantine does not support tab scrolling. Instead, if tabs don’t fit within the width of the container, they are automatically moved to a new line. This can be inconvenient, especially if the user has many tabs. So next I will show you how you can add scrolling to this element and make it usable for any screen size.</p><p>To solve this problem, you can use the CSS property overflow-x: auto on the list to enable horizontal scrolling. However, this will not be enough, because when the page loads, the active tab may be outside the visible area, and the user will not see it immediately.</p><h4>Corner cases</h4><p>In order to solve our problem, we need to consider the following cases:<br>1. When loading the page, scroll to the active tab, even if it is out of the screen visibility<br>2. If the outermost tabs are partially visible (on the sides of the list), it is necessary, when clicking on one of them, to place it completely in the visibility area<br>3. If the browser window is resized, the active tab should remain in the visibility area</p><h4>Make Tabs scrollable</h4><p>In Mantine, the Tabs component has three variants (default, outline, pills). In order to form an example of work for all three variants, let’s enter the necessary constants.</p><pre>// src/components/Tabs/base/constants.ts<br><br>import { ComboboxItem, TabsVariant } from &quot;@mantine/core&quot;;<br><br>export const TabsVariants: Record&lt;TabsVariant, TabsVariant&gt; = {<br>    default: &#39;default&#39;,<br>    outline: &#39;outline&#39;,<br>    pills: &#39;pills&#39;,<br>}<br><br>export const TabsVariantsOptions: ComboboxItem[] = [<br>    { value: TabsVariants.default, label: &#39;Default&#39; },<br>    { value: TabsVariants.outline, label: &#39;Outline&#39; },<br>    { value: TabsVariants.pills, label: &#39;Pills&#39; },<br>]</pre><p>Next need to describe styles according to the <a href="https://mantine.dev/core/tabs/?t=styles-api">styles API</a> for the Tabs component that will allow to add horizontal scrolling to it.</p><ol><li><em>.tab</em> — allow to style the tabs element regardless of the Tabs variant.</li><li><em>.list </em>— allow to style the tab list item to add scrolling.</li></ol><pre>/* src/components/Tabs/Tabs.module.scss */<br><br>.tab {<br>  &amp;[data-orientation=&quot;horizontal&quot;] {<br>    &amp;[data-variant=&quot;default&quot;] {<br>      border-color: var(--tab-border-color);<br><br>      &amp;:where([data-active]) {<br>        border-color: var(--tabs-color);<br>      }<br>    }<br><br>    &amp;[data-variant=&quot;outline&quot;] {<br>      border-bottom-color: var(--tabs-color);<br><br>      &amp;:where([data-active]) {<br>        border-color: var(--tabs-color);<br>        border-bottom: none;<br>      }<br>    }<br>  }<br>}<br><br>.list {<br>  &amp;[data-orientation=&quot;horizontal&quot;] {<br>    display: flex;<br>    flex-wrap: nowrap;<br><br>    scrollbar-width: none;<br>    overflow-x: auto;<br>    -ms-overflow-style: none;<br>    &amp;::-webkit-scrollbar {<br>      display: none;<br>    }<br><br>    &amp;[data-variant=&quot;outline&quot;] {<br>      --tab-border-color: transparent;<br>    }<br>  }<br>}</pre><p>Let’s apply the obtained styles to the Tabs component.</p><pre>// src/components/Tabs/index.tsx<br><br>import { useState } from &quot;react&quot;;<br>import { ComboboxItem, Select, Stack, Tabs as MantineTabs, TabsVariant } from &quot;@mantine/core&quot;;<br>import { TabsVariants, TabsVariantsOptions } from &quot;./base/constants&quot;;<br>import classes from &quot;./Tabs.module.scss&quot;;<br><br><br>export const Tabs = () =&gt; {<br>    const [variant, setVariant] = useState&lt;TabsVariant&gt;(TabsVariants.default);<br><br>    const handleChangeTabsVariant = (value: string | null, _: ComboboxItem) =&gt; {<br>        if (value === null) {<br>            setVariant(TabsVariants.default);<br><br>            return;<br>        }<br><br>        setVariant(TabsVariants[value as TabsVariant])<br>    }<br><br>    return (<br>        &lt;Stack gap=&quot;xl&quot;&gt;<br>            &lt;Select<br>                label=&quot;Tabs variant&quot;<br>                data={TabsVariantsOptions}<br>                value={variant}<br>                onChange={handleChangeTabsVariant}<br>            /&gt;<br><br>            &lt;MantineTabs classNames={{ list: classes.list, tab: classes.tab }} color=&quot;teal&quot; variant={variant} defaultValue=&quot;tab7&quot;&gt;<br>                &lt;MantineTabs.List&gt;<br>                    &lt;MantineTabs.Tab value=&quot;tab1&quot;&gt;<br>                        Tab 1<br>                    &lt;/MantineTabs.Tab&gt;<br>                    &lt;MantineTabs.Tab<br>                        value=&quot;tab2&quot;<br>                    &gt;<br>                        Tab 2<br>                    &lt;/MantineTabs.Tab&gt;<br>                    &lt;MantineTabs.Tab<br>                        value=&quot;tab3&quot;<br>                    &gt;<br>                        Tab 3<br>                    &lt;/MantineTabs.Tab&gt;<br><br>                    &lt;MantineTabs.Tab<br>                        value=&quot;tab4&quot;<br>                    &gt;<br>                        Tab 4<br>                    &lt;/MantineTabs.Tab&gt;<br><br>                    &lt;MantineTabs.Tab<br>                        value=&quot;tab5&quot;<br>                    &gt;<br>                        Tab 5<br>                    &lt;/MantineTabs.Tab&gt;<br>                    &lt;MantineTabs.Tab<br>                        value=&quot;tab6&quot;<br>                    &gt;<br>                        Tab 6<br>                    &lt;/MantineTabs.Tab&gt;<br>                    &lt;MantineTabs.Tab<br>                        value=&quot;tab7&quot;<br>                    &gt;<br>                        Tab 7<br>                    &lt;/MantineTabs.Tab&gt;<br>                &lt;/MantineTabs.List&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab1&quot;&gt;<br>                    Tab 1 content<br>                &lt;/MantineTabs.Panel&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab2&quot;&gt;<br>                    Tab 2 content<br>                &lt;/MantineTabs.Panel&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab3&quot;&gt;<br>                    Tab 3 content<br>                &lt;/MantineTabs.Panel&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab4&quot;&gt;<br>                    Tab 4 content<br>                &lt;/MantineTabs.Panel&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab5&quot;&gt;<br>                    Tab 5 content<br>                &lt;/MantineTabs.Panel&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab6&quot;&gt;<br>                    Tab 6 content<br>                &lt;/MantineTabs.Panel&gt;<br><br>                &lt;MantineTabs.Panel value=&quot;tab7&quot;&gt;<br>                    Tab 7 content<br>                &lt;/MantineTabs.Panel&gt;<br>            &lt;/MantineTabs&gt;<br>        &lt;/Stack&gt;<br>    );<br>};</pre><p>Gained the ability to horizontally scroll tabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*7reH6klvybSFmAesCzLM2g.png" /><figcaption>Scrollable horizontal tabs example</figcaption></figure><h4>Corner cases solution</h4><p>Next hook solves all 3 cases mentioned above scroll. As a result, this hook makes the tab interface as convenient and predictable for the user as possible:</p><ul><li>scroll immediately after page loading;</li><li>scroll when changing the active tab;</li><li>scroll when the window is resized.</li></ul><p>See below step-by-step explanation of how the useScrollableTabs hook works.</p><pre>// src/components/Tabs/base/useScrollableTabs.ts<br><br>import { useEffect, useRef } from &quot;react&quot;;<br>import { rafThrottle } from &quot;../../../shared/utils/rafThrottle&quot;;<br><br>const ACTIVE_TAB_SELECTOR = &#39;[aria-selected=&quot;true&quot;]&#39;<br><br>const scrollToActiveTab = (element: HTMLDivElement | null, scrollIntoViewOptions?: ScrollIntoViewOptions) =&gt; {<br>    const activeTab = element?.querySelector&lt;HTMLButtonElement&gt;(ACTIVE_TAB_SELECTOR);<br><br>    if (activeTab) {<br>        activeTab.scrollIntoView({ behavior: &quot;smooth&quot;, inline: &quot;center&quot;, block: &quot;nearest&quot;, ...scrollIntoViewOptions });<br>    }<br>};<br><br>export const useScrollableTabs = () =&gt; {<br>    const tabListReference = useRef&lt;HTMLDivElement | null&gt;(null);<br><br>    useEffect(() =&gt; {<br>        // 1. Scroll immediately after mounting<br>        scrollToActiveTab(tabListReference.current, { behavior: &#39;instant&#39; });<br><br>        // 2. Scroll when tab is active<br>        const observer = new MutationObserver(() =&gt; {<br>            scrollToActiveTab(tabListReference.current);<br>        });<br><br>        if (tabListReference.current) {<br>            observer.observe(tabListReference.current, {<br>                attributes: true,<br>                subtree: true,<br>            });<br>        }<br><br>        // 3. Add resize handler<br>        const throttledHandleResize = rafThrottle(() =&gt; {<br>            scrollToActiveTab(tabListReference.current);<br>        });<br><br>        window.addEventListener(&quot;resize&quot;, throttledHandleResize);<br><br>        return () =&gt; {<br>            observer.disconnect();<br>            window.removeEventListener(&quot;resize&quot;, throttledHandleResize);<br>        }<br>    }, []);<br><br>    return {<br>        tabListReference,<br>    };<br>};</pre><p><strong><em>1. Scroll to the active tab on initial page load, even if it’s out of view</em></strong></p><p>Right after the component mounts, we call scrollToActiveTab, which selects the active tab using the selector [aria-selected=&quot;true&quot;] and calls its scrollIntoView method.</p><p>The options { behavior: &quot;smooth&quot;, inline: &quot;center&quot;, block: &quot;nearest&quot; } make the scrolling is smooth and centers the tab horizontally within its container.</p><p><strong><em>2. Scroll to the active tab when the user clicks on a tab at the edge of the list</em></strong></p><p>Use a MutationObserver to detect changes in the active tab. The observer watches for attributes and subtree changes within the tab container (tabListReference). Whenever a tab becomes active (i.e., receives aria-selected=&quot;true&quot;), scrollToActiveTab is triggered. This ensures that any newly selected tab is smoothly scrolled into the center of the viewport.</p><p><strong><em>3. Keep the active tab visible when the browser window is resized</em></strong></p><p>Add a resize event listener on the window. For performance optimization, use rafThrottle to limit how often the scroll function is called. As a result, whenever the window is resized, we re-run scrollToActiveTab to ensure the active tab remains in view.</p><pre>// src/shared/utils/rafThrottle.ts<br>export const rafThrottle = &lt;T extends (...args: any[]) =&gt; void&gt;(fn: T) =&gt; {<br>    let raf: number;<br><br>    return (...args: Parameters&lt;T&gt;) =&gt; {<br>        if (raf) {<br>            cancelAnimationFrame(raf);<br>        }<br><br>        raf = requestAnimationFrame(() =&gt; {<br>            fn(...args);<br>        });<br>    };<br>};</pre><h4>Summary</h4><p>The Tabs component now has the following improvements:</p><ul><li>support for horizontal tab scrolling;</li><li>automatic scrolling to the active tab on mounts, DOM changes and window resizing;</li><li>throttling with rafThrottle to optimize performance;</li><li>flexible styling and support for different tab display options.</li></ul><p>These changes make the component more user-friendly and responsive to the user, especially with a large number of tabs.</p><p>The final code you can find on Github: <a href="https://github.com/dipiash/mantine-scrollable-tabs">https://github.com/dipiash/mantine-scrollable-tabs</a></p><p>The demo: <a href="https://dipiash.github.io/mantine-scrollable-tabs/">https://dipiash.github.io/mantine-scrollable-tabs/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fbf128c078d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fully typed forms based on API schema with react-hook-form,  openapi-typescript and yup validation]]></title>
            <link>https://medium.com/quadcode-life/fully-typed-forms-based-on-api-schema-with-react-hook-form-openapi-typescript-and-yup-validation-93ba1321368b?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ba1321368b</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[openapi-typescript]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[yup]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 12:25:55 GMT</pubDate>
            <atom:updated>2025-02-12T12:25:55.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Fully typed forms based on API schema with react-hook-form, openapi-typescript and yup validation" src="https://cdn-images-1.medium.com/max/720/1*npbP6EhpqqlTEMrpMdOxjg.png" /></figure><h3>Fully typed forms based on API schema with react-hook-form, openapi-typescript and yup validation</h3><p>Hello everyone, my name is Dmitrii Pashkevich and I’m a Frontend Developer at Quadcode. This article will explain to you the approach to creating fully typed forms in React applications using <a href="https://www.react-hook-form.com/">react-hook-form</a>, <a href="https://openapi-ts.dev/cli">openapi-typescript</a> and the <a href="https://github.com/jquense/yup">yup</a> validation. This method relies on an API schema to ensure that the form data exactly matches with the types from the backend API schema, simplifying development and reducing errors in the process. Whether you are a Frontend or a Full-stack Engineer looking to improve form reliability, I hope you find this material useful. Enjoy reading it!</p><h3>About</h3><p>Let’s consider an example of creating the form with POST request and a basic entity “Offer” consisting of 4 fields:</p><ul><li><em>name</em> — full name of the “Offer”. Field: string; mandatory; maximum length 1024 characters;</li><li><em>short_name</em> — short name of the “Offer”. Field: string; mandatory; maximum length 1024 characters;</li><li><em>advertiser_id</em> — advertiser id to which the “Offer” belongs. Field: number; mandatory for filling;</li><li><em>model</em> — alias of the model on which the “Offer” works. Field: string; mandatory; maximum length 1024 characters.</li></ul><h3>Project preparation</h3><p>Let’s create a basic React project using the generator from Vite with the directory name <em>fully-typed-form</em>.</p><pre>npm create vite@latest</pre><p>The command will result in a directory containing a simple React application. To keep things simple, let’s assume that the server API will be described as a yaml file containing a description of the Open API schema, which allows you to send a request to create an “Offer” entity.</p><p>Let’s start a file describing the Open API schema — <em>fully-typed-form/server/offers.openapi.yaml</em>.</p><pre>openapi: 3.1.0<br>info:<br>  title: Example API for article<br>  description: Article &quot;Fully typed forms based on API schema with react-hook-form,  openapi-typescript and yup validation&quot;<br>  version: 1.0.0<br>servers:<br>  - url: &#39;https&#39;<br>paths:<br>  /api/offers:<br>    post:<br>      summary: Create offer<br>      requestBody:<br>        required: true<br>        content:<br>          application/json:<br>            schema:<br>              $ref: &#39;#/components/schemas/OfferPostBody&#39;<br>      responses:<br>        &#39;201&#39;:<br>          description: Created<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/OfferId&#39;<br>components:<br>  schemas:<br>    OfferPostBody:<br>      required:<br>        - name<br>        - short_name<br>        - advertiser_id<br>        - model<br>      properties:<br>        name:<br>          description: Full offer name<br>          type: string<br>          maxLength: 1024<br>          x-oapi-codegen-extra-tags:<br>            validate: &quot;required,notBlank,lte=1024&quot;<br>        short_name:<br>          description: Short offer name<br>          type: string<br>          maxLength: 1024<br>          x-oapi-codegen-extra-tags:<br>            validate: &quot;required,notBlank,lte=1024&quot;<br>        advertiser_id:<br>          description: Id of the advertiser<br>          type: integer<br>          x-oapi-codegen-extra-tags:<br>            validate: &quot;required&quot;<br>        model:<br>          description: Model alias<br>          type: string<br>          x-oapi-codegen-extra-tags:<br>            validate: &quot;required,notBlank,lte=1024&quot;<br><br>    OfferId:<br>      type: object<br>      properties:<br>        id:<br>          type: string<br>          description: Id of the offer</pre><p>In order to generate an API-based schema, let’s use the openapi-typescript library, which is a tool designed to generate TypeScript types based on OpenAPI specifications. It helps to automatically generate data types to work with the API, which greatly simplifies the integration process and increases code reliability.</p><p>Let’s execute the type generation command for the above API schema.</p><pre>npx openapi-typescript server/offers.openapi.yaml -o src/shared/types/api/offers.types.generated.ts --make-paths-enum --root-types-no-schema-prefix --root-types --path-params-as-types --alphabetize</pre><p>The output is a generated file <em>src/shared/types/api/offers.types.generated.ts</em> containing types corresponding to the scheme described above.</p><pre>/**<br>* This file was auto-generated by openapi-typescript.<br>* Do not make direct changes to the file.<br>*/<br><br>export interface paths {<br>   &quot;/api/offers&quot;: {<br>       parameters: {<br>           query?: never;<br>           header?: never;<br>           path?: never;<br>           cookie?: never;<br>       };<br>       get?: never;<br>       put?: never;<br>       /** Create offer */<br>       post: {<br>           parameters: {<br>               query?: never;<br>               header?: never;<br>               path?: never;<br>               cookie?: never;<br>           };<br>           requestBody: {<br>               content: {<br>                   &quot;application/json&quot;: components[&quot;schemas&quot;][&quot;OfferPostBody&quot;];<br>               };<br>           };<br>           responses: {<br>               /** @description Created */<br>               201: {<br>                   headers: {<br>                       [name: string]: unknown;<br>                   };<br>                   content: {<br>                       &quot;application/json&quot;: components[&quot;schemas&quot;][&quot;OfferId&quot;];<br>                   };<br>               };<br>           };<br>       };<br>       delete?: never;<br>       options?: never;<br>       head?: never;<br>       patch?: never;<br>       trace?: never;<br>   };<br>}<br>export type webhooks = Record&lt;string, never&gt;;<br>export interface components {<br>   schemas: {<br>       OfferId: {<br>           /** @description Id of the offer */<br>           id?: string;<br>       };<br>       OfferPostBody: {<br>           /** @description Id of the advertiser */<br>           advertiser_id: number;<br>           /** @description Model alias */<br>           model: string;<br>           /** @description Full offer name */<br>           name: string;<br>           /** @description Short offer name */<br>           short_name: string;<br>       };<br>   };<br>   responses: never;<br>   parameters: never;<br>   requestBodies: never;<br>   headers: never;<br>   pathItems: never;<br>}<br>export type OfferId = components[&#39;schemas&#39;][&#39;OfferId&#39;];<br>export type OfferPostBody = components[&#39;schemas&#39;][&#39;OfferPostBody&#39;];<br>export type $defs = Record&lt;string, never&gt;;<br>export type operations = Record&lt;string, never&gt;;<br>export enum ApiPaths {<br>   PostApiOffers = &quot;/api/offers&quot;<br>}</pre><p>The example project will be described using <a href="https://feature-sliced.design/">FSD</a> (Feature-Sliced Design), so if you don’t want to read about prep work, auxiliary utilities, types and components, you can go straight to the Widgets layer (OfferFormCreate) and skip the description of sections related to shared and features layer.</p><p>Next, to implement the form we need to install the following modules.</p><pre>npm install react-hook-form @hookform/resolvers yup</pre><p>We’ll also install and connect Mantine UI components so to avoid writing unnecessary styles.</p><pre>npm install @mantine/core @mantine/hooks<br>npm install --save-dev postcss postcss-preset-mantine postcss-simple-vars</pre><p>Also install and connect <a href="https://www.npmjs.com/package/@tanstack/react-query">Tanstack React Query</a> to work with API requests.</p><pre>npm install @tanstack/react-query</pre><p>The configuration and connection of Mantine, Tanstack React Query can be found in the file: <em>src/App.tsx</em>.</p><h3>Shared layer</h3><p>Located in <em>src/shared</em> and will contain helper utilities, types, API requests, etc.</p><h4>API requests</h4><p>The <em>src/shared/api/offers.api.ts</em> contains an emulation of the request to create an offerer.</p><pre>import { OfferPostBody } from &#39;../types/api/offers.types.generated.ts&#39;<br><br>export const apiOfferPost = async (values: OfferPostBody) =&gt; {<br> await new Promise((resolve) =&gt; setTimeout(resolve, 1000))<br><br> console.info(values)<br>}</pre><h4>CreateEnumObject utility</h4><p>To simplify the work with typing and description of form fields, let’s create an auxiliary utility to turn Union type into an object: <em>src/shared/types/utils/createEnumObject.ts</em>.</p><pre>export const createEnumObject = &lt;T extends string&gt;(o: { [P in T]: P }) =&gt; {   return o }</pre><p>This utility will be useful for following the uniform naming of form fields among the project files.</p><h4>FormSelect component</h4><p>This is an auxiliary wrapper component over <a href="https://mantine.dev/core/select/">Mantine Select</a> that will allow this component to be connected to a react-hook-form by using <a href="https://react-hook-form.com/docs/usecontroller">useController</a>. This is necessary because it is not possible to use <a href="https://react-hook-form.com/docs/useform/register">form.register</a> to control a field because the type for onChange (a component parameter) is different.</p><pre>// react-hook-form onChange<br>export type ChangeHandler = (event: {<br>   target: any;<br>   type?: any;<br>}) =&gt; Promise&lt;void | boolean&gt;;<br><br>// VS<br><br>// Mantine Select onChange<br>onChange?: (value: string | null, option: ComboboxItem) =&gt; void;</pre><p>The full code of the component can be found in the file: <em>src/shared/components/FormSelect</em>.</p><pre>import { type FieldValues, useController } from &#39;react-hook-form&#39;<br><br>import { Select as MantineSelect } from &#39;@mantine/core&#39;<br><br>import { FormSelectPropertiesType } from &#39;./FormSelect.types.ts&#39;<br><br>export const FormSelect = &lt;T extends FieldValues&gt;({<br> name,<br> control,<br> defaultValue,<br> onChange,<br> rules,<br> shouldUnregister,<br> ...properties<br>}: FormSelectPropertiesType&lt;T&gt;) =&gt; {<br> const {<br>   field: { onChange: fieldOnChange, value, ...field },<br>   fieldState,<br> } = useController&lt;T&gt;({<br>   name,<br>   control,<br>   defaultValue,<br>   rules,<br>   shouldUnregister,<br> })<br><br> return (<br>   &lt;MantineSelect<br>     onChange={(value, option) =&gt; {<br>       fieldOnChange(value)<br>       onChange?.(value, option)<br>     }}<br>     error={fieldState.error?.message}<br>     value={value}<br>     {...field}<br>     {...properties}<br>   /&gt;<br> )<br>}</pre><h3>Features layer</h3><p>Because the form will contain interactive elements for working with advertisers and models, let’s place them in the features layer.</p><h4>AdvertiserSelect component</h4><p>The full code can be found in the file: <em>src/features/AdvertiserSelect</em>.</p><pre>import type { AdvertiserSelectPropertiesInterface } from &#39;./AdvertiserSelect.types.ts&#39;<br><br>import { FormSelect } from &#39;../../shared/components/FormSelect/FormSelect.tsx&#39;<br>import { ADVERTISERS_LIST } from &#39;./base/constant.ts&#39;<br><br>export const AdvertiserSelect = ({ name, form, ...rest }: AdvertiserSelectPropertiesInterface) =&gt; (<br> &lt;FormSelect name={name} control={form.control} data={ADVERTISERS_LIST} required searchable {...rest} /&gt;<br>)</pre><h4>ModelSelect component</h4><p>The full code can be found in the file: <em>src/features/ModelSelect</em>.</p><pre>import type { ModelSelectPropertiesInterface } from &#39;./ModelSelect.types.ts&#39;<br><br>import { FormSelect } from &#39;../../shared/components/FormSelect/FormSelect.tsx&#39;<br>import { MODELS_LIST } from &#39;./base/constant.ts&#39;<br><br>export const ModelSelect = ({ name, form, ...rest }: ModelSelectPropertiesInterface) =&gt; (<br> &lt;FormSelect name={name} control={form.control} data={MODELS_LIST} required searchable {...rest} /&gt;<br>)</pre><h3>Widgets layer (OfferFormCreate)</h3><p>Next, let’s move on to the main part of the article — organizing a typed form using react-hook-form and validation via yup.</p><p>On this layer, let’s create a directory that will contain the form widget for creating an offerer: <em>src/widgets/offers/OfferFormCreate</em>.</p><p>The form widget will consist of:</p><ul><li>description of field constants based on the type obtained from the API;</li><li>description of labels and placeholders objects for form fields;</li><li>description of validation scheme;</li><li>a hook for controlling the form;</li><li>form component.</li></ul><h4>Field object and validation scheme</h4><p>In order to describe the typed scheme for our form, let’s create a file: <em>src/widgets/offers/OfferFormCreate/base/constants.ts</em>.</p><p>The following code comments describe the what and why.</p><pre>import * as yup from &#39;yup&#39;<br><br>import { OfferPostBody } from &#39;../../../../shared/types/api/offers.types.generated.ts&#39;<br>import { createEnumObject } from &#39;../../../../shared/types/utils/createEnumObject.ts&#39;<br><br><br>// Constants for yup schema validation<br>const OFFER_NAME_MAX_LENGTH = 1024<br>const OFFER_SHORT_NAME_MAX_LENGTH = 1024<br><br><br>// This object contains all fields from OfferPostBody type keys.<br>// This object created by createEnumObject<br>// After that action we can use OFFER_CREATE_FORM_FIELDS in all places where we need to use filed names<br>export const OFFER_CREATE_FORM_FIELDS = createEnumObject&lt;keyof OfferPostBody&gt;({<br> advertiser_id: &#39;advertiser_id&#39;,<br> name: &#39;name&#39;,<br> short_name: &#39;short_name&#39;,<br> model: &#39;model&#39;,<br>})<br><br>// Labels mapped to form fields<br>export const OFFER_CREATE_FORM_FIELDS_LABEL: Record&lt;keyof typeof OFFER_CREATE_FORM_FIELDS, string&gt; = {<br> [OFFER_CREATE_FORM_FIELDS.advertiser_id]: &#39;Advertiser&#39;,<br> [OFFER_CREATE_FORM_FIELDS.name]: &#39;Name&#39;,<br> [OFFER_CREATE_FORM_FIELDS.short_name]: &#39;Short name&#39;,<br> [OFFER_CREATE_FORM_FIELDS.model]: &#39;Model&#39;,<br>}<br><br>// Placeholders mapped to form fields<br>export const OFFER_CREATE_FORM_FIELDS_PLACEHOLDER: Record&lt;keyof typeof OFFER_CREATE_FORM_FIELDS, string&gt; = {<br> [OFFER_CREATE_FORM_FIELDS.advertiser_id]: &#39;Select advertiser&#39;,<br> [OFFER_CREATE_FORM_FIELDS.name]: &#39;Type name&#39;,<br> [OFFER_CREATE_FORM_FIELDS.short_name]: &#39;Type short name&#39;,<br> [OFFER_CREATE_FORM_FIELDS.model]: &#39;Select model&#39;,<br>}<br><br>// This is a yup schema. It describes validation options for each field in OfferPostBody<br>export const OFFER_CREATE_FORM_VALIDATION_SCHEMA: yup.ObjectSchema&lt;OfferPostBody&gt; = yup.object({<br> [OFFER_CREATE_FORM_FIELDS.advertiser_id]: yup<br>   .number()<br>   .required()<br>   .nonNullable()<br>   .label(OFFER_CREATE_FORM_FIELDS_LABEL[OFFER_CREATE_FORM_FIELDS.advertiser_id]),<br> [OFFER_CREATE_FORM_FIELDS.name]: yup<br>   .string()<br>   .required()<br>   .nonNullable()<br>   .max(OFFER_NAME_MAX_LENGTH)<br>   .label(OFFER_CREATE_FORM_FIELDS_LABEL[OFFER_CREATE_FORM_FIELDS.name]),<br> [OFFER_CREATE_FORM_FIELDS.short_name]: yup<br>   .string()<br>   .required()<br>   .nonNullable()<br>   .max(OFFER_SHORT_NAME_MAX_LENGTH)<br>   .label(OFFER_CREATE_FORM_FIELDS_LABEL[OFFER_CREATE_FORM_FIELDS.short_name]),<br> [OFFER_CREATE_FORM_FIELDS.model]: yup.string().required().nonNullable().label(OFFER_CREATE_FORM_FIELDS_LABEL[OFFER_CREATE_FORM_FIELDS.model]),<br>})</pre><h4>Hook for working with the form</h4><p>Next, create a form via react-hook-form and connect the validation scheme described above to it. In order to isolate the work with our form we create a hook: <em>src/widgets/offers/OfferFormCreate/base/hooks/useOfferFormCreate.ts</em>.</p><p>Further in the comments to the code, the what and why are described.</p><pre>import { useMutation } from &#39;@tanstack/react-query&#39;<br>import { useForm } from &#39;react-hook-form&#39;<br><br>import { yupResolver } from &#39;@hookform/resolvers/yup&#39;<br>import * as yup from &#39;yup&#39;<br><br>import { apiOfferPost } from &#39;../../../../../shared/api/offers.api.ts&#39;<br>import { OFFER_CREATE_FORM_FIELDS, OFFER_CREATE_FORM_VALIDATION_SCHEMA } from &#39;../constants.ts&#39;<br><br>// yup.InferType is a utility from the Yup library used to extract a TypeScript type from a validation schema.<br>// It allows you to automatically generate data types based on a Yup schema, helping to avoid code duplication and mismatches between types.<br>type OfferFormCreateSchemaType = yup.InferType&lt;typeof OFFER_CREATE_FORM_VALIDATION_SCHEMA&gt;<br><br>// This hook is used to create a form for creating a new offer<br>export const useOfferFormCreate = () =&gt; {<br>  // It&#39;s a mutation hook from the @tanstack/react-query library. It&#39;s handle API request to create new offer<br>  const { isPending, mutate } = useMutation({<br>    mutationFn: apiOfferPost,<br>  })<br><br>  // This hook is used to create a form for creating a new offer and handle fields<br>  // This hook is typed with OfferFormCreateSchemaType.<br>  // This hook used a validation schema to validate fields (resolver).<br>  const form = useForm&lt;OfferFormCreateSchemaType&gt;({<br>    resolver: yupResolver(OFFER_CREATE_FORM_VALIDATION_SCHEMA),<br>  })<br><br>  // This function is used to handle form submit<br>  const handleSubmit = (values: OfferFormCreateSchemaType) =&gt; {<br>    mutate(values)<br>  }<br><br>  // This function is used to get error message for each field<br>  const getFieldErrorMessage = (fieldName: keyof typeof OFFER_CREATE_FORM_FIELDS) =&gt; form.formState.errors[fieldName]?.message?.toString()<br><br>  return {<br>    form,<br>    getFieldErrorMessage,<br>    handleSubmit,<br>    isPending, // This property is used to check if the API request is pending<br>  }<br>}</pre><h4>Form</h4><p>Now all that is left is to implement the form description using the above hook: <em>useOfferFormCreate</em>. Further in the comments to the code, it is described what and why.</p><pre>import { Button, Stack, TextInput } from &#39;@mantine/core&#39;<br><br>import { AdvertiserSelect } from &#39;../../../features/AdvertiserSelect&#39;<br>import { ModelSelect } from &#39;../../../features/ModelSelect&#39;<br>import { OFFER_CREATE_FORM_FIELDS, OFFER_CREATE_FORM_FIELDS_LABEL, OFFER_CREATE_FORM_FIELDS_PLACEHOLDER } from &#39;./base/constants.ts&#39;<br>import { useOfferFormCreate } from &#39;./base/hooks/useOfferFormCreate.ts&#39;<br><br>// This component is used to create a form for creating a new offer<br>export const OfferFormCreate = () =&gt; {<br> // This hook is used to get form instance and other helpers<br> const { form, getFieldErrorMessage, handleSubmit, isPending } = useOfferFormCreate()<br><br> return (<br>   &lt;form noValidate onSubmit={form.handleSubmit(handleSubmit)}&gt;<br>     &lt;Stack&gt;<br>       {/* Offer name */}<br>       &lt;TextInput<br>         label={OFFER_CREATE_FORM_FIELDS_LABEL.name}<br>         error={getFieldErrorMessage(OFFER_CREATE_FORM_FIELDS.name)}<br>         placeholder={OFFER_CREATE_FORM_FIELDS_PLACEHOLDER.name}<br>         required<br>         {...form.register(OFFER_CREATE_FORM_FIELDS.name)}<br>       /&gt;<br><br>       {/* Offer short name */}<br>       &lt;TextInput<br>         label={OFFER_CREATE_FORM_FIELDS_LABEL.short_name}<br>         error={getFieldErrorMessage(OFFER_CREATE_FORM_FIELDS.short_name)}<br>         placeholder={OFFER_CREATE_FORM_FIELDS_PLACEHOLDER.short_name}<br>         required<br>         {...form.register(OFFER_CREATE_FORM_FIELDS.short_name)}<br>       /&gt;<br><br>       {/* Offer advertiser */}<br>       &lt;AdvertiserSelect<br>         label={OFFER_CREATE_FORM_FIELDS_LABEL.advertiser_id}<br>         name={OFFER_CREATE_FORM_FIELDS.advertiser_id}<br>         error={getFieldErrorMessage(OFFER_CREATE_FORM_FIELDS.advertiser_id)}<br>         form={form}<br>         placeholder={OFFER_CREATE_FORM_FIELDS_PLACEHOLDER.advertiser_id}<br>       /&gt;<br><br>       {/* Offer model */}<br>       &lt;ModelSelect<br>         label={OFFER_CREATE_FORM_FIELDS_LABEL.model}<br>         name={OFFER_CREATE_FORM_FIELDS.model}<br>         error={getFieldErrorMessage(OFFER_CREATE_FORM_FIELDS.model)}<br>         form={form}<br>         placeholder={OFFER_CREATE_FORM_FIELDS_PLACEHOLDER.model}<br>       /&gt;<br><br>       {/* Submit button with loading state */}<br>       &lt;Button loading={isPending} type=&quot;submit&quot;&gt;<br>         Submit<br>       &lt;/Button&gt;<br>     &lt;/Stack&gt;<br>   &lt;/form&gt;<br> )<br>}</pre><h3>Overall</h3><p>Thus, thanks to the fact that the OFFER_CREATE_FORM_FIELDS field object and the OFFER_CREATE_FORM_VALIDATION_SCHEMA validation scheme are tied to the OfferPostBody type, we have a form that is quite easy to maintain, due to the fact that:</p><ul><li>uniform field naming is used. It is easy to refactor through IDE tools to access fields;</li><li>a single binding to the OfferPostBody type is used. If this type is changed (scheme regeneration), we will get full illumination of places in the code that do not correspond to the new API scheme;</li><li>strict typing of form field values and data sending function.</li></ul><p>You can find the full code on GitHub here: <a href="https://github.com/dipiash/fully-typed-form">fully-typed-form</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ba1321368b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quadcode-life/fully-typed-forms-based-on-api-schema-with-react-hook-form-openapi-typescript-and-yup-validation-93ba1321368b">Fully typed forms based on API schema with react-hook-form,  openapi-typescript and yup validation</a> was originally published in <a href="https://medium.com/quadcode-life">Quadcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vite, Nginx and environment variables for a static website at runtime]]></title>
            <link>https://medium.com/quadcode-life/vite-nginx-and-environment-variables-for-a-static-website-at-runtime-f3d0b2995fc7?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3d0b2995fc7</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[envsubst]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Fri, 17 May 2024 07:44:31 GMT</pubDate>
            <atom:updated>2024-05-17T07:44:31.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*JIN2irSrv7J4-Zl-rdH0wg.jpeg" /></figure><p>Hello everyone! My name is Dmitry Pashkevich, and I’m a Frontend developer at Quadcode. Today I’ll share a method for passing environment variables to a statically built website using the <a href="https://vitejs.dev/">Vite</a> build tool in conjunction with the Nginx web server.</p><p>A common task in frontend development is passing environment variables to the application depending on the environment in which the application is running. It seems like a simple task, and everything is described in the <a href="https://vitejs.dev/guide/env-and-mode">documentation </a>— just place a <em>.env</em> file next to it and run the build… on each environment.</p><p>It seems like the solution has been found. But this leads to a situation where each environment has a different build process and a different result of this build.</p><p>Practice shows that problems arise with the functionality of the build steps. For example, when making changes, settings, scripts, etc. are forgotten to be updated for one of the environments. As a result, we encounter issues with the application itself, as the artifacts also differ.</p><p>Thus, it seems logical to obtain a single build artifact for all available environments and be able to pass environment variable values. Therefore, it is easier to troubleshoot one issue with variable values than to investigate build steps as well.</p><p>Now, let’s see how to do this using the Vite and Nginx tools as an example.</p><h3>Repository Preparation</h3><p>First, let’s create a project from the template provided by the Vite builder for React + Typescript.</p><pre>npm create vite@latest vite-nginx-dynamic-env-variables-example -- <br>--template react-ts &amp;&amp; cd vite-nginx-dynamic-env-variables-example &amp;&amp; npm <br>instal</pre><h3>Project Configuration Preparation</h3><p>After successfully executing the commands, let’s open the resulting project in our favorite IDE and start creating the target solution.</p><p>Let’s adjust the file src/vite-env.d.ts. We will add a description of the type of available environment variables to enable <a href="https://vitejs.dev/guide/env-and-mode.html#intellisense-for-typescript">IDE hinting</a>.</p><pre>/// &lt;reference types=&quot;vite/client&quot; /&gt;<br><br>interface ImportMetaEnv {<br>    readonly VITE_VERSION: string<br>}<br><br>interface ImportMeta {<br>    readonly env: ImportMetaEnv<br>}</pre><p>Now the IDE will provide hints about the available environment variables.</p><p>Next, let’s create a file with environment variable templates: <em>src/shared/projectEnvVariables.ts</em> and add the following content to it.</p><pre>type ProjectEnvVariablesType = Pick&lt;ImportMetaEnv, &#39;VITE_VERSION&#39;&gt;<br><br><br>// Environment Variable Template to Be Replaced at Runtime<br>const projectEnvVariables: ProjectEnvVariablesType = {<br>   VITE_VERSION: &#39;${VITE_VERSION}&#39;,<br>}<br><br><br>// Returning the variable value from runtime or obtained as a result of the build <br>export const getProjectEnvVariables = (): {<br>   envVariables: ProjectEnvVariablesType<br>} =&gt; {<br>   return {<br>       envVariables: {<br>           VITE_VERSION: !projectEnvVariables.VITE_VERSION.includes(&#39;VITE_&#39;) ? projectEnvVariables.VITE_VERSION : import.meta.env.VITE_VERSION,<br>       }<br>   }<br>}</pre><p>Next, it is necessary to make a change to the build configuration in <em>vite.config.ts</em> so that the file created above has a predictable name after the build stage. To do this, add a section with the configuration for rollup to the config.</p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>   plugins: [react()],<br>   build: {<br>       rollupOptions: {<br>           output: {<br>               format: &#39;es&#39;,<br>               globals: {<br>                   react: &#39;React&#39;,<br>                   &#39;react-dom&#39;: &#39;ReactDOM&#39;,<br>               },<br>               manualChunks(id) {<br>                   if (/projectEnvVariables.ts/.test(id)) {<br>                       return &#39;projectEnvVariables&#39;<br>                   }<br>               },<br>           },<br>       }<br>   }<br>}</pre><p>In the <a href="https://rollupjs.org/configuration-options/#output-manualchunks">manualChunks</a> section, we create a custom chunk and save part of its name so that after the build, we can find this file for substituting environment variables.</p><p>Let’s make changes to the <em>src/App.tsx</em> file to see the values of environment variables.</p><pre>import { getProjectEnvVariables } from &quot;./shared/projectEnvVariables.ts&quot;;<br><br>const { envVariables } = getProjectEnvVariables()<br><br>function App() {<br> return (<br>     &lt;&gt;<br>         &lt;h1&gt;VITE_VERSION&lt;/h1&gt;<br>         &lt;div&gt;{envVariables.VITE_VERSION}&lt;/div&gt;<br><br>         &lt;hr /&gt;<br><br>         &lt;h2&gt;import.meta.env.VITE_VERSION&lt;/h2&gt;<br>         &lt;div&gt;{import.meta.env.VITE_VERSION}&lt;/div&gt;<br>     &lt;/&gt;<br> )<br>}<br><br>export default App</pre><p>Next, let’s run the build to make sure that we obtain the necessary chunk for substituting variables after the build stage.</p><pre>npm run build</pre><p>After the build is complete, navigate to the <em>dist/assets</em> directory. You will see that a chunk named <em>projectEnvVariables*</em>, which we specified in the configuration above, exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*ktJM-uxP1B_MHsUh" /></figure><p>Next, let’s conduct a series of experiments.</p><p>For ease of understanding that the desired build result is obtained, each build will be performed with a specified environment variable. This will visually verify the condition for returning the value of the environment variable in the <em>getProjectEnvVariables</em> function.</p><p>For the first experiment, create a<em> .env</em> file in the project root with the following contents.</p><pre>VITE_VERSION=dev</pre><p>Let’s start the project build and the mode to view the build results.</p><pre>npm run build &amp;&amp; npm run preview</pre><p>Upon navigating to <a href="http://localhost:4173/">http://localhost:4173/</a>, you will see two identical values of the variable read from the config and directly from the environment variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*v54K2xxJ6lxc8gNS" /></figure><p>For the second experiment, let’s replace the variable in the <em>dist/assets/projectEnvVariables-wa84hTgi.js</em> file, which was generated after building the application. Replace the line with the value ${VITE_VERSION} with <em>dev_from_env</em> in this file. After refreshing the page in the browser, you will get the updated version of the variable on the screen, read from the config <em>getProjectEnvVariables</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*i78JsfhPexEVriyi" /></figure><p>Everything works as expected! It’s time to automate variable substitution.</p><h3>Preparing Docker + Nginx Configuration</h3><p>We’ll demonstrate the automation of variable substitution using a Docker container containing the Nginx web server, which executes i<a href="https://www.nginx.com/resources/wiki/start/topics/examples/initscripts/">nitialization scripts</a> before startup, and substitutes environment variables using <a href="https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html">envsubst</a>.</p><p>Let’s create a .docker directory in the project root with the configuration contents for the Nginx web server that will serve the application. A complete example of the Nginx configuration can be found in the <a href="https://github.com/dipiash/vite-nginx-dynamic-env-variables-example">repository</a>, and below is the bash code of the <em>.docker/app/nginx/init-scripts/100-init-project-env-variables.sh</em> file, which replaces the environment variables.</p><pre>#!/usr/bin/env sh<br><br>set -ex<br><br><br># Find the file where environment variables need to be replaced.<br>projectEnvVariables=$(ls -t /usr/share/nginx/html/assets/projectEnvVariables*.js | head -n1)<br><br># Replace environment variables<br>envsubst &lt; &quot;$projectEnvVariables&quot; &gt; ./projectEnvVariables_temp<br>cp ./projectEnvVariables_temp &quot;$projectEnvVariables&quot;<br>rm ./projectEnvVariables_temp</pre><p>Next, in the project root, create a Dockerfile with the following content, which describes the application build and runs the Nginx web server to serve the static files.</p><pre>FROM node:20-alpine as builder<br><br>WORKDIR /app<br><br>COPY package.json package-lock.json ./<br><br>RUN npm ci<br><br>COPY . .<br><br>ARG NODE_ENV=production<br>ENV NODE_ENV=${NODE_ENV}<br><br>RUN npm run build<br><br>FROM nginx:alpine<br><br>ARG VITE_VERSION=dev<br>ENV VITE_VERSION=${VITE_VERSION}<br><br>ARG PORT=80<br>ENV NGINX_PORT=${PORT}<br>ENV NGINX_HOST=localhost<br><br>EXPOSE ${PORT}<br><br>COPY .docker/app/nginx/nginx.conf /etc/nginx/nginx.conf<br>COPY .docker/app/nginx/conf.d/ /etc/nginx/conf.d/<br>COPY .docker/app/entrypoint.sh /entrypoint.sh<br>COPY .docker/app/nginx/init-scripts/ /docker-entrypoint.d/<br><br>WORKDIR /usr/share/nginx/html<br><br>COPY --from=builder /app/dist ./</pre><p>Next, let’s build the container.</p><pre>docker build -t <br>vite-nginx-dynamic-env-variables-example .</pre><p>Next, let’s run the created container with a new value for the environment variable available in the application.</p><pre>docker run -p 81:80 -e VITE_VERSION=FROM_NGINX <br>vite-nginx-dynamic-env-variables-example</pre><p>Upon navigating to <a href="http://127.0.0.1:81/">http://127.0.0.1:81</a> , we see that the environment variable is initialized with the current value, while the directly read environment variable remains with the old value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*ukJd94zCo_IfhduJ" /></figure><h3>Conclusion</h3><p>This way, environment variables can be substituted into a statically built application at runtime, allowing for a unified build across all environments.</p><p>The code can be found in <a href="https://github.com/dipiash/vite-nginx-dynamic-env-variables-example">the repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3d0b2995fc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quadcode-life/vite-nginx-and-environment-variables-for-a-static-website-at-runtime-f3d0b2995fc7">Vite, Nginx and environment variables for a static website at runtime</a> was originally published in <a href="https://medium.com/quadcode-life">Quadcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving development productivity: the magic of a unified ESLint configuration]]></title>
            <link>https://medium.com/quadcode-life/improving-development-productivity-the-magic-of-a-unified-eslint-configuration-e32aa71b063b?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e32aa71b063b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[eslint-config]]></category>
            <category><![CDATA[js-tutorial]]></category>
            <category><![CDATA[eslint]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 16:57:17 GMT</pubDate>
            <atom:updated>2023-09-22T16:57:17.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cJlW1Fld56PPVrj_" /></figure><p>Hello everyone! My name is Dmitry Pashkevich, and I’m a Frontend developer at Quadcode. This article isn’t just a tutorial on creating a unified ESLint configuration that can be reused between projects. It’s a story about solving the pain of discussions about code formatting from project to project during reviews.</p><p>The article will be useful for developers who want to standardize their approach to code formatting across different projects; looking for a proven solution for codebase standardization.</p><p>[SPOILER ALERT] You can review the code in our<a href="https://github.com/dipiash/eslint-plugin-nimbus-clean"> repository on GitHub</a> repository as well as find the package in <a href="https://www.npmjs.com/package/eslint-plugin-nimbus-clean">NPM</a>.</p><h3>Why do we need a unified ESLint plugin/configuration?</h3><p>Uniform code formatting in a team reduces the mental load during code reviews, reading/writing code, or starting a new project. It allows one to focus on how the code works rather than being distracted by how semicolons are placed.</p><p>Imagine you have 5 projects, and each has its own formatting rules. You start the 6th and copy configs from previous projects, adding new rules. And so on in a loop. We end up with inconsistent ESLint configs in all projects and, as follows, inconsistently formatted code between projects. As a result, simple things are discussed over and over during code reviews.</p><p>In this article, I will explain how to write a plugin/configuration for ESLint and publish it as a package. This will allow you to correct, add, and change the necessary rules in one place and connect them as a single module in other projects.</p><p>In our Quadcode team, we use publication to a private registry, but in this article, you’ll see publication to NPM (in the source code).</p><h3>Repository Preparation</h3><p>So, the first thing we’ll start with is creating a template for the ESLint plugin project.</p><p>To do this, go to the <a href="https://eslint.org/docs/latest/extend/plugins#create-a-plugin">ESLint documentation</a>, the “Create Plugin” section, and follow the recommendation for creating a new project. Navigate to the<a href="https://www.npmjs.com/package/generator-eslint"> installation section</a> and perform the required actions.</p><p>Open the command line.</p><h3>Installing Node.js</h3><p>If you haven’t installed the <a href="https://nodejs.org/en">Node.js</a> platform yet, you need to do so.</p><h3>Installing Yeoman</h3><p>Next, install <a href="https://yeoman.io/">Yeoman</a> — a tool for generating template projects, if you haven’t installed it yet.</p><pre>npm i -g yo</pre><h3>Installing the ESLint Plugin Generator</h3><p>Next, we’ll install a utility to generate an ESLint plugin.</p><pre>npm i -g generator-eslint</pre><p>Great! All preliminary work is done, now it’s time to create the base project for our plugin.</p><h3>Creating the Project Directory</h3><p>Let’s create a directory for our project.</p><pre>mkdir eslint-plugin-nimbus-clean</pre><p>And navigate into it.</p><pre>cd ./eslint-plugin-nimbus-clean</pre><p>Next, we’ll set up the project structure.</p><pre>yo eslint:plugin</pre><p>This command will start the wizard for creating an ESLint plugin project.</p><h3>Answering the Setup Wizard’s Questions</h3><p>Let’s go through a short survey.</p><pre>? What is your name? dipiash<br>? What is the plugin ID? nimbus-clean<br>? Type a short description of this plugin: A comprehensive linting solution that sweeps your code clean<br>? Does this plugin contain custom ESLint rules? No<br>? Does this plugin contain one or more processors? No</pre><p>The last two questions were answered with “No” because at this stage, we won’t be using any custom rules or custom processors. Instead, we will use a certain combination of other plugins.</p><p>Wait for the generator to create the starting project and open the resulting project in your IDE.</p><h3>Setting Up .gitignore File</h3><p>Next, we will create a “.gitignore” file to exclude unnecessary files from being committed to the repository.</p><pre>touch .gitignore</pre><p>To avoid drafting this file’s content from scratch, I always use the service: <a href="https://www.toptal.com/developers/gitignore">https://www.toptal.com/developers/gitignore</a>. You can also find plugins for your IDE that allow you to generate this file directly there.</p><p>We’re interested in “.gitignore” for Node.js — take the content from <a href="https://www.toptal.com/developers/gitignore/api/node">the link</a> and add it to the “.gitignore” file we created earlier.</p><h3>Initializing git</h3><p>Initialize the git repository.</p><pre>git init</pre><h3>Project Preparation</h3><p>Let’s make changes to the created project.</p><p>In the future, we might need to write custom rules. Let’s immediately add a <a href="https://www.npmjs.com/package/eslint-plugin-eslint-plugin">plugin</a> for linting ESLint rules and connect it as indicated in the documentation.</p><pre>npm install eslint-plugin-eslint-plugin - save-dev</pre><p>In the package.json file, in the “scripts” section, add two commands: “build” and “pack”.</p><p>The “build” command will compile our project.</p><pre>rm -rf ./dist &amp;&amp; mkdir ./dist &amp;&amp; cp -r ./lib/* ./dist</pre><p>The “pack” command will be needed to locally check the plugin’s operation.</p><pre>npm pack - pack-destination=./dist</pre><p>We should also adjust the sections: “main”, “exports”, and “files”, as the content for npm publication will be located in the “dist” directory.</p><pre>&quot;main&quot;: &quot;./dist/index.js&quot;,<br>&quot;exports&quot;: &quot;./dist/index.js&quot;,<br>&quot;files&quot;: [<br>  &quot;/dist&quot;,<br>  &quot;README.md&quot;,<br>  &quot;package.json&quot;<br>]</pre><p>Additionally, let’s edit the “lib/index.js” file. We won’t need the <strong>require index</strong> package, so remove that part of the code.</p><h3>ESLint Plugin vs. ESLint Config</h3><p>When setting up ESLint, one can often encounter packages with names starting with: “eslint-plugin-*” and “eslint-config-*”. So, what’s the difference?</p><p>Plugins must be named as “eslint-plugin-*”. When adding a plugin to your project, the rules won’t be enabled automatically, and therefore you will need to enable each rule individually.</p><p>Configs must be named as “eslint-config-*”. When adding a config to your project, all rules will be enabled automatically, and you won’t need to enable each rule individually.</p><p>In practice, plugins are needed if you are creating your own code linting rules and want the plugin users to be able to turn them on or off by themselves. In all other cases, you can use a config since it will most likely simply reuse a set of configurations from other plugins.</p><p>However, a plugin can also be used as a config with general rules enabled by default. In this article, we will consider such a plugin version that includes a default configuration (recommended). Often in the documentation for plugins, one can see that such plugins are connected to the “extends” section as “plugin:your-plugin-name/recommended” — more details can be found in the <a href="https://eslint.org/docs/latest/extend/plugins#configs-in-plugins">ESLint documentation</a>.</p><h3>Set of Configs / Plugins</h3><p>Next, let’s determine the main plugins that we will use in our projects.</p><h3>ESLint</h3><p>This is directly the <a href="https://www.npmjs.com/package/eslint">eslint</a> itself, from which we will take the <a href="https://eslint.org/docs/latest/use/getting-started#configuration">recommended config</a>.</p><h3>Prettier</h3><p>So as not to use a separate configuration for <a href="https://prettier.io/">Prettier</a>, we’ll add to our ESLint plugin/config the rules from the packages:</p><ul><li><a href="https://www.npmjs.com/package/eslint-config-prettier">eslint-config-prettier</a> — disables all rules that are unnecessary or might conflict with Prettier.</li><li><a href="https://www.npmjs.com/package/eslint-plugin-prettier">eslint-plugin-prettier</a> — allows us to set up Prettier as ESLint rules and will display information about problems as ESLint issues.</li></ul><h3>Imports</h3><p>Let’s set up rules for working with import/export in our code.</p><ul><li><a href="https://www.npmjs.com/package/eslint-plugin-import">eslint-plugin-import</a> — will allow us to avoid various issues when importing/exporting modules in the code.</li><li><a href="https://www.npmjs.com/package/eslint-import-resolver-typescript">eslint-import-resolver-typescript</a> — will add TypeScript support for the previous plugin.</li><li><a href="https://www.npmjs.com/package/eslint-plugin-simple-import-sort">eslint-plugin-simple-import-sort</a> — will allow us to configure module sorting in the desired order according to certain rules.</li></ul><h3>React</h3><p>Since all our projects are written using React, we will naturally add linting support for code written with React.</p><ul><li><a href="https://www.npmjs.com/package/eslint-plugin-react">eslint-plugin-react</a> — rules for linting React code.</li><li><a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">eslint-plugin-react-hooks</a> — will help us adhere to the rules for writing React Hooks.</li><li><a href="https://www.npmjs.com/package/eslint-plugin-testing-library">eslint-plugin-testing-library</a> — will check the code of our tests for the Testing Library.</li><li><a href="https://www.npmjs.com/package/eslint-plugin-jsx-a11y">eslint-plugin-jsx-a11y</a> — will check if we have added accessibility rules to our JSX elements or not.</li></ul><h3>Typescript</h3><p>Since the entire codebase is written in TypeScript, we will add rules for linting TypeScript code — <a href="https://www.npmjs.com/package/@typescript-eslint/eslint-plugin">@typescript-eslint/eslint-plugin</a>.</p><h3>Promises</h3><p>We will add a plugin for linting code that works with Promises — <a href="https://www.npmjs.com/package/eslint-plugin-promise">eslint-plugin-promise</a>.</p><h3>Code quality</h3><p>And we will add two final plugins for linting code quality.</p><ul><li><a href="https://www.npmjs.com/package/eslint-plugin-sonarjs">eslint-plugin-sonarjs</a> — will help identify potential bugs and the use of suspicious patterns in the code.</li><li><a href="https://www.npmjs.com/package/eslint-plugin-unicorn">eslint-plugin-unicorn</a> — more than 100 useful rules for ESLint.</li></ul><p>We will install all the packages listed above and add them as peerDependencies in package.json.</p><pre>npm i -D eslint-import-resolver-typescript @typescript-eslint/eslint-plugin <br>eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-<br>plugin-prettier eslint-plugin-promise eslint-plugin-react eslint-plugin-react-<br>hooks eslint-plugin-simple-import-sort eslint-plugin-sonarjs eslint-<br>plugin-testing-library eslint-plugin-unicorn</pre><p>Also, to ensure the user sees the entire list of missing projects when installing our package, we will use the directive in package.json <a href="https://docs.npmjs.com/cli/v9/configuring-npm/package-json#peerdependenciesmeta">peerDependenciesMeta</a> and mark each dependency as `optional: false`.</p><h3>Rules for ESLint</h3><p>In this section, I will describe the inclusion of rules for each section from the previous one — I will describe in the same order.</p><p>Let’s create a `rules` directory in `lib` — where files for each part of the config will be located.</p><pre>mkdir ./rules/lib</pre><h3>ESLint</h3><p>Let’s create a file to describe the ESLint configuration.</p><pre>touch lib/rules/common.js</pre><p>And add the rules there.</p><pre>/** eslint */<br>module.exports = {<br>    // https://eslint.org/docs/latest/rules/curly<br>    &quot;curly&quot;: [&quot;error&quot;, &quot;all&quot;],<br>    // https://eslint.org/docs/latest/rules/padding-line-between-statements<br>    &quot;padding-line-between-statements&quot;: [<br>        &quot;error&quot;,<br>        { &quot;blankLine&quot;: &quot;always&quot;, &quot;prev&quot;: [&quot;const&quot;, &quot;let&quot;, &quot;var&quot;], &quot;next&quot;: &quot;*&quot; },<br>        { &quot;blankLine&quot;: &quot;any&quot;, &quot;prev&quot;: [&quot;const&quot;, &quot;let&quot;, &quot;var&quot;], &quot;next&quot;: [&quot;const&quot;, &quot;let&quot;, &quot;var&quot;] },<br>        { &quot;blankLine&quot;: &quot;always&quot;, &quot;prev&quot;: &quot;*&quot;, &quot;next&quot;: &quot;return&quot; }<br>    ],<br>    // https://eslint.org/docs/latest/rules/no-multiple-empty-lines<br>    &quot;no-multiple-empty-lines&quot;: [&quot;error&quot;],<br>    // https://eslint.org/docs/latest/rules/arrow-body-style<br>    &quot;arrow-body-style&quot;: [&quot;error&quot;, &quot;as-needed&quot;],<br>    // https://eslint.org/docs/latest/rules/prefer-arrow-callback<br>    &quot;prefer-arrow-callback&quot;: &quot;off&quot;,<br>    // https://eslint.org/docs/latest/rules/no-console<br>    &quot;no-console&quot;: [&quot;error&quot;, { &quot;allow&quot;: [&quot;warn&quot;, &quot;info&quot;, &quot;error&quot;] }],<br>    // https://eslint.org/docs/latest/rules/no-underscore-dangle<br>    &quot;no-underscore-dangle&quot;: [<br>        &quot;error&quot;,<br>        {<br>            &quot;allow&quot;: [&quot;_id&quot;, &quot;__typename&quot;, &quot;__schema&quot;, &quot;__dirname&quot;, &quot;_global&quot;],<br>            &quot;allowAfterThis&quot;: true<br>        }<br>    ],<br>}</pre><h3>Prettier</h3><p>Let’s create a file to describe the Prettier configuration.</p><pre>touch lib/rules/prettier.js</pre><p>Add the rules.</p><pre>/** eslint-plugin-prettier */<br>module.exports = {<br>    &quot;prettier/prettier&quot;: &quot;error&quot;,<br>}</pre><h3>Imports</h3><p>Let’s create a file to describe the configuration for “eslint-plugin-import” and “eslint-plugin-simple-import-sort”.</p><pre>touch lib/rules/import.js</pre><pre>touch lib/rules/simple-import-sort.js</pre><p>Add the rules.</p><pre>/** eslint-plugin-import */<br>module.exports = {<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/first.md<br>    &quot;import/first&quot;: &quot;error&quot;,<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/newline-after-import.md<br>    &quot;import/newline-after-import&quot;: &quot;error&quot;,<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-duplicates.md<br>    &quot;import/no-duplicates&quot;: &quot;error&quot;,<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/prefer-default-export.md<br>    &quot;import/prefer-default-export&quot;: &quot;off&quot;,<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-anonymous-default-export.md<br>    &quot;import/no-anonymous-default-export&quot;: [<br>        &quot;error&quot;,<br>        {<br>            &quot;allowArray&quot;: false,<br>            &quot;allowArrowFunction&quot;: false,<br>            &quot;allowAnonymousClass&quot;: false,<br>            &quot;allowAnonymousFunction&quot;: false,<br>            &quot;allowCallExpression&quot;: true,<br>            &quot;allowLiteral&quot;: false,<br>            &quot;allowObject&quot;: true<br>        }<br>    ],<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-unassigned-import.md<br>    &quot;import/no-unassigned-import&quot;: &quot;off&quot;,<br>    // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-unused-modules.md<br>    &quot;import/no-unused-modules&quot;: &quot;error&quot;<br>}</pre><h3>React</h3><p>Let’s create a configuration file for React.</p><pre>touch lib/rules/react.js</pre><p>Add the rules.</p><pre>/** eslint-plugin-react-* */<br>module.exports = {<br>    // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prop-types.md<br>    &quot;react/prop-types&quot;: &quot;off&quot;,<br>    // https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md<br>    &quot;react-hooks/exhaustive-deps&quot;: [2],<br>}</pre><h3>TypeScript</h3><p>Let’s create a configuration file for TypeScript.</p><pre>touch lib/rules/typescript.js</pre><p>Add the rules.</p><pre>/** @typescript-eslint-* */<br>module.exports = {<br>    // https://typescript-eslint.io/rules/no-use-before-define/<br>    &quot;@typescript-eslint/no-use-before-define&quot;: [&quot;error&quot;],<br>    // https://typescript-eslint.io/rules/no-unused-vars/<br>    &quot;@typescript-eslint/no-unused-vars&quot;: [<br>        &quot;error&quot;<br>    ],<br>    // https://typescript-eslint.io/rules/no-explicit-any/<br>    &quot;@typescript-eslint/no-explicit-any&quot;: &quot;error&quot;,<br>    // https://typescript-eslint.io/rules/naming-convention/<br>    &quot;@typescript-eslint/naming-convention&quot;: [<br>        &quot;error&quot;,<br>        {<br>            &quot;selector&quot;: &quot;interface&quot;,<br>            &quot;format&quot;: [&quot;PascalCase&quot;],<br>            &quot;custom&quot;: {<br>                &quot;regex&quot;: &quot;[A-Za-z]Interface$&quot;,<br>                &quot;match&quot;: true<br>            }<br>        },<br>        {<br>            &quot;selector&quot;: &quot;typeAlias&quot;,<br>            &quot;format&quot;: [&quot;PascalCase&quot;],<br>            &quot;custom&quot;: {<br>                &quot;regex&quot;: &quot;[A-Za-z]Type$&quot;,<br>                &quot;match&quot;: true<br>            }<br>        }<br>    ],<br>    // https://typescript-eslint.io/rules/ban-types/<br>    &quot;@typescript-eslint/ban-types&quot;: [<br>        &quot;error&quot;,<br>        {<br>            &quot;types&quot;: {<br>                // un-ban a type that&#39;s banned by default<br>                &quot;{}&quot;: false<br>            },<br>            &quot;extendDefaults&quot;: true<br>        }<br>    ]<br>}</pre><h3>Promises</h3><p>Let’s create a configuration file for Promises.</p><pre>touch lib/rules/promise.js</pre><p>Add the rules.</p><pre>/** eslint-plugin-promise */<br>module.exports = {<br>    // https://github.com/eslint-community/eslint-plugin-promise/blob/main/docs/rules/prefer-await-to-then.md<br>    &quot;promise/prefer-await-to-then&quot;: &quot;off&quot;,<br>    // https://github.com/eslint-community/eslint-plugin-promise/blob/main/docs/rules/always-return.md<br>    &quot;promise/always-return&quot;: &quot;off&quot;,<br>    // https://github.com/eslint-community/eslint-plugin-promise/blob/main/docs/rules/catch-or-return.md<br>    &quot;promise/catch-or-return&quot;: [2, { &quot;allowThen&quot;: true, &quot;allowFinally&quot;: true }],<br>}</pre><h3>Code Quality</h3><p>Let’s create a configuration file for ESLint.</p><pre>touch lib/rules/sonarjs.js</pre><pre>touch lib/rules/unicorn.js</pre><p>Add the rules.</p><pre>/** eslint-plugin-sonarjs */<br>module.exports = {<br>    // https://github.com/SonarSource/eslint-plugin-sonarjs/blob/master/docs/rules/no-identical-functions.md<br>    &quot;sonarjs/no-identical-functions&quot;: [&quot;error&quot;, 5],<br>}</pre><pre>/** eslint-plugin-unicorn */<br>module.exports = {<br>    // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-array-reduce.md<br>    &quot;unicorn/no-array-reduce&quot;: &quot;off&quot;,<br>    // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-module.md<br>    &quot;unicorn/prefer-module&quot;: &quot;off&quot;,<br>    // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-null.md<br>    &quot;unicorn/no-null&quot;: &quot;off&quot;,<br>    // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-useless-undefined.md<br>    &quot;unicorn/no-useless-undefined&quot;: &quot;off&quot;,<br>    // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/filename-case.md<br>    &quot;unicorn/filename-case&quot;: [<br>        &quot;error&quot;,<br>        {<br>            &quot;cases&quot;: {<br>                &quot;pascalCase&quot;: true,<br>                &quot;camelCase&quot;: true<br>            },<br>            &quot;ignore&quot;: [<br>                &quot;next-env.d.ts&quot;,<br>                &quot;vite(st)?.config.ts&quot;,<br>                &quot;vite-environment.d.ts&quot;,<br>                &quot;\\.spec.ts(x)?&quot;,<br>                &quot;\\.types.ts(x)?&quot;,<br>                &quot;\\.stories.ts(x)?&quot;,<br>                &quot;\\.styled.ts(x)?&quot;,<br>                &quot;\\.styles.ts(x)?&quot;,<br>            ]<br>        }<br>    ],<br>    // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prevent-abbreviations.md<br>    &quot;unicorn/prevent-abbreviations&quot;: [<br>        &quot;error&quot;,<br>        {<br>            &quot;checkFilenames&quot;: false<br>        }<br>    ],<br>}</pre><h3>Publishing an NPM package</h3><p>To publish the package, we will use the following utilities:</p><ul><li><a href="https://github.com/release-it/release-it">release-it </a>+ <a href="https://github.com/release-it/bumper">@release-it/bumper</a> + <a href="https://github.com/release-it/conventional-changelog">@release-it/conventional-changelog</a></li><li><a href="https://www.npmjs.com/package/@commitlint/cli">@commitlint/cli</a> + <a href="https://www.npmjs.com/package/@commitlint/config-conventional">@commitlint/config-conventional</a></li><li><a href="https://www.npmjs.com/package/commitizen">commitizen</a> + <a href="https://www.npmjs.com/package/cz-git">cz-git </a>+ <a href="https://www.npmjs.com/package/cz-conventional-changelog">cz-conventional-changelog</a></li></ul><p>These utilities will allow us to version our ESLint plugin according to SemVer and describe commits in such a way that it occurs automatically and a <a href="https://github.com/dipiash/eslint-plugin-nimbus-clean/blob/main/CHANGELOG.md">CHANGELOG</a> is generated. You can see the entire setup in the <a href="https://github.com/dipiash/eslint-plugin-nimbus-clean">repository</a>.</p><h3>Integration into a Project</h3><p>After publishing to NPM, you can install and integrate the <a href="https://www.npmjs.com/package/eslint-plugin-nimbus-clean">package</a> into any of your projects.</p><pre>npm i eslint-plugin-nimbus-clean</pre><p>Setting up the ESLint configuration.</p><pre>{<br>    &quot;extends&quot;: [<br>      &quot;plugin:nimbus-clean/recommended&quot;<br>    ]<br>}</pre><p>Detailed instructions are described in the project’s <a href="https://github.com/dipiash/eslint-plugin-nimbus-clean/blob/main/README.md">README</a>.</p><h3>Conclusion</h3><p>This is my experience in creating custom configurations and plugins for ESLint and publishing them to NPM.</p><p>Using this approach, you can create the desired configuration for your projects once and then reuse it. If you need to make some changes to the ESLint config, it only needs to be done in one place, and in the projects, you just need to update the version if necessary.</p><p>What else would you recommend adding to this plugin?</p><p>You can see all the code in the <a href="https://github.com/dipiash/eslint-plugin-nimbus-clean">Github repository</a>, and the package can be found on <a href="https://www.npmjs.com/package/eslint-plugin-nimbus-clean">NPM</a>. I will be glad if you can star the repository:) Feel free to ask me any questions in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e32aa71b063b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quadcode-life/improving-development-productivity-the-magic-of-a-unified-eslint-configuration-e32aa71b063b">Improving development productivity: the magic of a unified ESLint configuration</a> was originally published in <a href="https://medium.com/quadcode-life">Quadcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How design systems are created: sharing our own example. Part 2]]></title>
            <link>https://medium.com/quadcode-life/how-design-systems-are-created-sharing-our-own-example-part-2-df42f786ec1a?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/df42f786ec1a</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 16:45:41 GMT</pubDate>
            <atom:updated>2023-07-28T16:48:10.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, everyone! This is Dmitry Pashkevich, and I am a frontend developer at Quadcode, specializing in the creation and development of design systems. This is the second part of a comprehensive article, “How Design Systems Are Created.” Last time,<a href="https://medium.com/quadcode-life/how-design-systems-are-created-sharing-our-own-example-part-1-82f58c6f3719"> <strong>we discussed the basics of design systems</strong></a><strong> </strong>— problems that prompt a company to create design systems, phases of forming design systems, and general design system development. Today, I’m going to delve into our own experience, explain how to define product (and design system) requirements and much more. Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_fADNxwcrDq5rz4A" /></figure><h3>Defining Product Requirements and, as a result, Design System Requirements</h3><p>The process of defining product requirements began with the frontend (FE) team choosing suitable tools to implement the entire project, not just the design system, based on minimal requirements:</p><ul><li>React:</li></ul><p>a) Server-Side Rendering (SSR) for the main page,</p><p>b) Client-Side Rendering (CSR) for the user dashboard.</p><ul><li>TypeScript.</li><li>Work with REST/GraphQL/WebSockets.</li><li>SSR support.</li><li>React components should be covered by tests.</li><li>Usage of modern transpilation tooling — Babel/Esbuild, etc.</li><li>Enforced linting and code style (code analyzer).</li><li>Defined project folder structure and agreement on code organization.</li><li>Optional: use a UI kit and reuse it for components.</li><li>Optional: ability to view the project’s UI kit and provide it to designers.</li></ul><p>As a result of this selection, the following technologies and tools were chosen:</p><ol><li>React + TypeScript</li><li><a href="https://gist.github.com/dipiash/a5e78b20af18849fdff888c5820c44f7">Eslint</a> with a set of preferred rules</li><li>GraphQL — Apollo</li><li>TanStack Query</li><li>Schema-first approach for API development, generating TypeScript types from Swagger schemas</li><li>Styled-components</li><li>Vite as the project bundler</li><li>Storybook for component display</li><li>npm as the package manager (Yarn/pnpm/npm were considered)</li><li>Monorepo using NX</li><li>Feature-Sliced Design for code architecture and structure</li><li>Testing: unit tests, Jest (later transitioned to Vitest), RTL/snapshot testing</li><li>Monitoring with Sentry</li></ol><p>At this stage, we also considered the UI kit and how we would build it:</p><ul><li>Possible use of react-hook-form for working with forms</li><li>Using styled-system.com for building the UI, building from scratch, or exploring alternative options</li></ul><p>The question of building the UI kit sparked heated discussions and extensive research. I had no desire to start from scratch and go through the process of creating a new set of components again (which I had already experienced and took a long time), while also encountering the same pitfalls. Additionally, it was clear at that time that building the UI kit would not take up much time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*swv4NSj1AGLiRngV" /></figure><p>After some more time spent on research and intense discussions, a solution emerged. We chose Mantine, although we considered other options such as Ant Design, Chakra UI, and Semantic UI. Mantine won our hearts with its project documentation and more. In the next section, I will provide more details on why we were so impressed with this tool. This choice became the starting point for working on the design system, and we already had a sense that it would be an entirely new experience.</p><h3>Results of Working with Requirements or Why Mantine?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UP_v5_I-WMDUTtBh" /></figure><p>The result of the research was a rough draft of the application skeleton. You can check out an example on Github. The final solution differs from what is presented in the repository, but the concept is reflected. After creating the skeleton, we started working on the design system.</p><p>The development of the design system began by identifying the following basic elements:</p><p>- Color palettes</p><p>- Typography</p><p>- Margins/Padding</p><p>- Icons/Images</p><p>- Borders</p><p>- Radii (rounded corners)</p><p>- Patterns/UX/UI flows</p><p>- Animations</p><p>Based on this, we initially set up a configuration for theming (and now we are gradually building the design tokens system). As mentioned earlier, our design system is built using Mantine. So, what made it so useful? On the one hand, it might seem limiting because we are relying on a specific tool. But on the other hand:</p><h4>Mantine is a clear and flexible tool</h4><p>It provides:</p><ul><li>Documentation;</li><li>Theming capabilities;</li><li>Typing;</li><li>Source code that can be used as supplementary/training/inspirational material;</li><li>A broad set of basic, easily customizable components, most of which have been tested in projects and are supported by the community, indicating that they cover many typical use cases and have resolved enough bugs to be used in production;</li><li>Components are broken down into layers, with almost every layer being customizable and stylizable. Again, if you need to do something specific, you can always take the source code of the basic elements and customize it or create a pull request;</li></ul><p>In essence, for us, Mantine serves as the foundation for building our “home” = the design system.</p><h4>Speed of development</h4><p>Comparing the efforts required to create components from scratch versus using Mantine, it looks like this:</p><p><strong>From scratch (under limited time constraints):</strong></p><p>1. You come up with the logic of how the component will work in different states (default/active/focus/disabled, etc.) and then you program the logic/styles.</p><p>2. You think about how it can be styled externally (usually, people don’t think/suspect this at the start), and then there are slight differences here and there — no one breaks down the component into layers (each layer/element of the layer should be stylized).</p><p>3. There are also different variations of the component, and you have to implement logic and styles for them too.</p><p>a) Due to time constraints, it might end up being not very convenient to use and modify the API.</p><p><strong>If we use Mantine:</strong></p><p>You have a ready-made basic component, organized into layers with predefined states (default/active/focus/disabled, etc.) and behavior logic. Essentially, this is your limitation and safety in component creation.</p><p>You simply style the component according to your theme. Styling variations involve describing different styles for display based on the known classes for the layers.</p><p>If there is a need for some custom logic, it can be easily implemented through the standard component API or by modifying the source code, but within your own project.</p><p>I believe it is essential to note that at the product launch, sometimes it is necessary to simplify the interface and make reasonable assumptions because it is not always possible to achieve everything we want right away. Striking a balance is crucial.</p><blockquote><strong>According to some estimates, creating the final component based on Mantine is approximately 5–10 times faster than building it from scratch</strong>.</blockquote><p>This is achieved because:</p><p>- The component’s parameters and layers are immediately clear.</p><p>- You can interactively view the component in the documentation, which gives you an understanding of its capabilities and limitations, along with easily readable source code.</p><p>- You can start using the component immediately without having to come up with its logic from scratch, by using the offered API, which covers around 80–90% of the logic needs for displaying the component, and in most cases, even 100%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vQSEPGITpVW-9Qu3" /></figure><h4>Layered API:</h4><p>Let’s consider layers using the example of a simple button. On the surface, it may not seem complicated, but here’s how it looks in <a href="https://mantine.dev/core/button/?t=styles-api">layers</a>:</p><p>- Root</p><p>- Inner</p><p>- Icon + Left Icon</p><p>- Label</p><p>- Loader</p><p>- Icon + Right Icon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JJgfFF7dAp5jwcvX" /></figure><p>Or, for a more complex component like Select, it can be broken down into layers with the ability to modify the rendering of the dropdown list, etc.</p><p>You can create your custom components according to the following rules:</p><ul><li><a href="https://mantine.dev/guides/custom-components/#add-styles-api-support">Styles API</a></li><li><a href="https://mantine.dev/guides/custom-components/#add-default-props-support">Default props</a> &amp; <a href="https://mantine.dev/guides/custom-components/#defaultprops-type">types</a>.</li></ul><p>Examples of the code can be viewed <a href="https://gist.github.com/dipiash/a2798b48c621439e023e6f9986aca1d4">here</a>.</p><h4>The impact of Mantine version updates</h4><p>The skeleton of our project and part of the setup were created using Mantine version 4. We went through the update to version 5 relatively smoothly, and soon we will have to update to version 6. It might be a bit more challenging, but the team has provided a detailed <a href="https://mantine.dev/changelog/6-0-0/">CHANGELOG</a> to help with the process.</p><h4>Benefits</h4><blockquote><strong>Mantine is about achieving more results with less effort.</strong></blockquote><p>When starting to work on a design system, a lot of time is always invested in basic components, no matter how much we want to avoid it. However, using auxiliary tools significantly eases the work for both developers and designers.</p><p>Our very intense development and design phase lasted about one quarter. During this time, 96% of the components were ready, the framework of the application was set up with various providers (authorization, translations, etc.), and several sections related to authentication and onboarding were implemented.</p><p>The phase of active synchronization took another quarter. A few new components were introduced (no more than 10), and most of the time was spent on assembling pages.</p><p>Currently, we are in the third quarter of development, and I believe we have reached a plateau — there are no major changes happening. However, soon we will begin moving towards design tokens and scaling the design system to other team projects. I think we will go through all three phases of design system development to some extent again.</p><h3>Summarizing the Definition of a Design System</h3><p>Let me provide a brief summary and definition of what a design system is.</p><p>I’ll start by saying that in my understanding, the ideal start of working on a design system is when passionate individuals from both the front-end development and design sides come together. These individuals are enthusiastic and willing to put in the effort, even staying up late at night to discuss and improve their creation. And there’s a little time to start.</p><p><strong>Developing a design system is about:</strong></p><ul><li>Having a single source of truth for UI/UX and interface text.</li><li>Flexibility, standardization, and simplicity.</li><li>Thoughtfulness, efficiency, and transparency.</li><li>Change safety, consistency, and inheritability.</li><li>Automation (not necessarily at the beginning).</li><li>Accessibility.</li><li>Constant communication.</li></ul><p><strong><em>A design system is a set of rules for styling products that helps maintain the integrity of the user experience and optimize resources expended on development and design. </em></strong>It involves a high degree of autonomy through a unified design, component library, guidelines, and established development approaches. This, in turn, allows businesses to simply articulate the problem and what they want to change, while the design system with all its processes and approaches begins to help solve the identified issues.</p><p>Ultimately, a design system encompasses:</p><ul><li>Communication rules.</li><li>Visual language.</li><li>Documentation.</li><li>Component library.</li></ul><p>I hope this provides an understanding that a UI kit is just a component library, and without all the other elements, it cannot be called a design system.</p><h3>What a Design System has brought and who it benefits</h3><p>A design system is not a simple and cheap tool that can be implemented and used casually. A team or company should reach a certain point where the use of this approach is justified.</p><p>Let’s take a look at what we ultimately achieved after 3 quarters of working on the design system and product.</p><ul><li><strong>Each team member found value in the design system: </strong>costs and feature release speed: By reusing well-designed components, more resources are available for creating new/non-standard features in the product. After laying the foundation, we became faster in designing and assembling application sections.</li><li><strong>Reduction in design time:</strong> Using the design system allows designers to reduce the time spent on design and development. This is possible because a significant portion of design elements and components are already ready and can be reused.</li><li><strong>Unified design and components for development: </strong>We hardly write styles within the project, thanks to the unified design and components. The proportion of styling files is less than 4%, which speeds up development and the release of new pages exponentially (time to market).</li><li><strong>User interface development is like building with blocks:</strong> We spend more time on the application’s logic rather than its layout.</li><li><strong>Single source of truth: </strong>Since the design system is the source of truth, there are no discrepancies in interface-related decisions. Any team member can review the design and implementation to ensure compliance with the layout and rules. This helps maintain the quality of released solutions.</li><li><strong>Convenient testing setup:</strong> We have design reviews followed by task/feature testing. If there are changes, they are implemented both in Figma and Storybook. For example, our QA team often uses Figma and consults Storybook to review component properties and capabilities. When working with content and editors, we know that most of the product’s textual content is reflected in the design. The text is pulled from a specialized service.</li><li><strong>Product quality:</strong> Using the design system allows us to create higher quality products. Strict styling rules, a unified design, and the reuse of elements ensure that the product meets quality standards.</li><li><strong>Developers propose solutions before design:</strong> Developers can propose solutions for certain tasks based on established approaches and coordinate them with designers (if the design is not ready yet).</li><li><strong>Onboarding new employees:</strong> During onboarding, new employees gain a clear understanding of the capabilities of the components used in the project. They can view interactive examples of their work and read the documentation.</li><li><strong>Unified solution across different projects: </strong>There is no need to adapt to a new interface workflow.</li><li><strong>Using a design system helps create a unified design</strong>, which enhances the user’s perception of the product. Strict styling rules and the use of a consistent style throughout the project ensure a uniform user interface and make the project more recognizable.</li><li><strong>Fast adaptation to changes</strong>: This is more relevant for design, as development becomes more laborious when the API of a component is not compatible with the previous version. The design system allows for quick adaptation to project changes. If changes are made to a component, they automatically apply wherever it is used, which accelerates the adaptation process.</li><li><strong>No bloating of the team’s technical stack:</strong> Focus remains on implementing our own UI kit. The product is executed in a unified style, despite consisting of multiple services. There is no need to learn a new framework/version of another library.</li></ul><p>The main benefits we gained as a team have been listed above. However, there are certain aspects worth considering, which are not necessarily drawbacks but rather peculiarities:</p><blockquote>Synchronizing component changes in Figma and code can be challenging.</blockquote><p>Starting a product is more challenging as components need to be developed first before the business begins receiving fully functional application pages incrementally. However, this is true for the first two or three iterations of implementing the UI kit in new projects, as it requires resolving related discrepancies during integration: settings, styling, documentation, versioning, etc. Overall, it is a solvable problem, and with each new project, the startup process accelerates significantly.</p><p>Maintaining components as a library is not always easy: versioning and applying new versions to all projects, testing them, etc., can consume a considerable amount of resources. This is especially true at the beginning when requirements can change frequently.</p><h3>Plans for Design System Development</h3><p>What’s next? We want to:</p><ul><li>Separate components into a separate package:</li><li>Implement versioning in code.</li><li>Implement versioning in design.</li><li>Start implementing the design system in other team projects:</li><li>Address and resolve related issues.</li><li>Develop new components and improve existing ones.</li><li>Upgrade to version 6 of Mantine.</li><li>Implement design tokens for key components.</li><li>Implement color scheme management.</li><li>Describe standards for component creation and their entire lifecycle.</li><li>Start describing contexts and rules for component usage.</li></ul><p>At the time of article publication, some of these tasks will already be completed.</p><h3>Code Examples</h3><ul><li><a href="https://gist.github.com/dipiash/a5e78b20af18849fdff888c5820c44f7">ESLint configuration</a></li><li><a href="https://gist.github.com/dipiash/a2798b48c621439e023e6f9986aca1d4">Styling of the Stats component</a></li><li><a href="https://github.com/dipiash/nx-ts-vite-react-graphql-styled-monorepo-example">Basic project skeleton</a> (the final solution differs from what is presented in the repository, but the concept is reflected).</li></ul><p>This is it! I hope you’ve enjoyed this article. Let me know what you think about it in the comments. I’ll be glad to answer any of your questions. See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df42f786ec1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quadcode-life/how-design-systems-are-created-sharing-our-own-example-part-2-df42f786ec1a">How design systems are created: sharing our own example. Part 2</a> was originally published in <a href="https://medium.com/quadcode-life">Quadcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How design systems are created: sharing our own example. Part 1.]]></title>
            <link>https://medium.com/quadcode-life/how-design-systems-are-created-sharing-our-own-example-part-1-82f58c6f3719?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f58c6f3719</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[mantine]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 17:33:13 GMT</pubDate>
            <atom:updated>2023-08-01T09:19:10.993Z</atom:updated>
            <content:encoded><![CDATA[<h2>How design systems are created: sharing our own example. Part 1</h2><p>Hello everyone. My name is Dmitry Pashkevich, and I am a frontend developer at Quadcode, specializing in the creation and development of design systems. This article is intended for specialists at various levels who are involved in design systems: from consumers and component developers to team/tech leads building design systems from scratch. Here, I will share my experience, and the path I have taken from creating UI-kits to fully building design systems, and show the benefits that a ready-made design system has brought us. If you are looking to deepen your understanding of design systems, then this article is for you. Have a nice reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9H8Fwp3vvEigMDJ0" /></figure><h3>Intro</h3><p>To some extent, this combination of words has become a collective term because experience shows that different companies have different interpretations of it. Understanding depends on the maturity level of the team/project/company/processes, the presence of desire, time, and resources, and most importantly, people with “passionate” eyes who will develop this direction despite all the difficulties.</p><p>I have gone through the path of creating various UI kits, transforming these UI kits into design systems, to fully building design systems from scratch from the perspective of FE development in the following roles:</p><ol><li>Consumer of components.</li><li>Developer of components.</li><li>Lead in building a design system from scratch. Here, 80–90% of the time was spent on component development, while the remaining 10–20% involved applying components in the product code, as well as sharing knowledge and interacting with the FE development team.</li><li>Product developer — when you “build components” and immediately implement them during product development. In this case, the entire team participates in working on the design system.</li></ol><p>In this article, I want to share the experience we have gained and try to structure it using our company as an example. I will demonstrate the phases of formation and development of the design system that we went through, share the technical stack of our product, and provide insights into the benefits the ready-made design system has brought us.</p><p>On one hand, I would like to immediately provide a definition of what a design system is in my understanding, but let’s approach it slightly differently and formulate what comes after the main part.</p><p><em>&lt;</em><strong><em>SPOILER&gt;</em></strong><em> For those who are eager to learn the differences between a design system and a UI kit, you can skip ahead to the second part of my article and scroll straight to the section“What is a design system, in summary.” However, I still recommend reading from beginning to end. &lt;/</em><strong><em>SPOILER&gt;</em></strong></p><h3>The problems that lead to the emergence of design systems</h3><p>Firstly, I will start with what usually initiates the birth of a design system. Most often, the reason lies in accumulated and recognized problems that the whole team or specific parts of it begin to address — the areas where the pain is the greatest.</p><p>So, what can these problems be?</p><ol><li>The old design is lost. It is no longer supported, or it exists only in images (yes, it happens). In this case, developers themselves or with the help of a designer come up with ways to incorporate specific elements. The consequence is that the development of new pages becomes a pain. The product inevitably becomes inconsistent across different pages because the logic of interface construction is lost.</li><li>The old design/interface has become morally outdated, and a redesign is necessary. The question arises: what should be done? Should the current product be modified: modularly, page by page, or should it be built from scratch, etc. — each person chooses their own path. Different paths have nuances that need to be dealt with.</li><li>Communications regarding feature creation/interface changes exceed reasonable limits. In this case, creating a new element or UX approach becomes disconnected from the product. I think this can be considered as an extension of point 2 and the team’s desire to provide users with a more convenient and modern product.</li><li>Creating any new feature (even a similar one) takes a lot of time. Various factors can contribute to this, such as poor architecture inherited from the MVP project, outdated tools, or the inability to simply update.</li><li>The necessity to improve processes. The desire to create a unified point of communication within the team, at least between development and design. A little spoiler: as practice shows, during development, this point, also known as the design system, becomes at least a single source of truth, and discussions constantly arise there.</li><li>The presence of significant routine work when creating new layouts or coding within a single product. Sometimes, there is no opportunity to reuse a UI kit in design or code. This situation often arises across different projects and occasionally within a single project (more relevant to design in a specific tool). It looks something like this: you open a new design layout, see similar elements but with different names. It becomes difficult for a developer to match elements with the code, and there is a need to standardize everything to avoid wasting time on unnecessary clarification when it’s simply a matter of taking, implementing, and using.</li><li>There is a product pool within the company, and at some point, there is a need to standardize the UI/UX. Each product has its own team of designers and developers. Does each team need to develop its own UI kit? It happens sometimes. Then the implementation of a design system can start from the design side, which brings everything to a unified appearance. As a result, multiple UI kits may appear in the code due to resistance in different teams, but after a couple of iterations, a unified component base begins to emerge.</li></ol><p>These described problems are not listed in any specific order or importance; any of them can be a starting point for creating a design system.</p><h3>Phases of forming a design system</h3><p>After realizing some of the above, the process usually begins to create something similar to a UI kit or a large-scale design system. It unfolds as follows:</p><ol><li>Human and time resources are allocated.</li><li>Requirements are formed for a technology stack that will meet modern challenges.</li><li>Based on the requirements, a stack is chosen. The first demo versions of project skeletons appear.</li><li>Initial agreements between development and design teams emerge — the search for a common language, the desire to synchronize.</li><li>The core of the design system is born, or it’s more accurate to say, the UI kit, as the processes are yet to be fully formed.</li><li><strong>The first components are created.</strong></li><li>The components are tested in the first product feature, and adjustments are made to them.</li><li>Organic development of components in design and code occurs, with or without design reviews.</li><li>There is more time for reflection on what has been done and what currently needs adjustment. The development and design teams align their approaches and toolsets to help move forward, including:</li></ol><ul><li>Identifying and resolving issues.</li><li>Introducing new processes (syncs — meetings on how designers create a design, frontend developers work on frontend, QA tests the frontend part of the application, and how everyone interacts with design layouts.</li><li>Implementing new tools.</li></ul><p>10. Gradually, there comes a phase where the design system team or individuals responsible for the design system focus less on creating new components and more on assembling pages and maintaining the components.</p><p>In this stage of my personal experience related to design system development, I consider this an ideal path to follow. However, there are always nuances, and it depends on the situation.</p><h3>Phases of design system development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wsJ69YzkSREGxMIv" /></figure><p>If we delve deeper into this list, the following phases of development can be identified:</p><p><strong>Hot phase</strong>: This is when components undergo the maximum number of changes in design/code during their implementation into the final product. This phase can last from a few months (on average, 6) to several years. The minimum duration I have experienced is 3 months, and the maximum is 1.5 years. It depends on the initial agreements, the experience within the development team and the business that allocates resources, time, and sets priorities.</p><p>The development of components in both code and design occurs simultaneously. There is a connection between development and design, establishing a common language, component naming conventions, and determining the best way to organize the library. Efforts are made to ensure that everything in the design references basic components or that more complex components are built from basic ones.</p><p>Many growth points are identified but may not be addressed due to resource limitations or a lack of critical necessity at this stage. These issues are addressed when time becomes available or when it becomes difficult to move forward without resolving them.</p><p>The improvement of design system workflows for design and frontend development occurs in parallel. They improve their own processes, and gradually, they start to solve their respective issues.</p><p><strong>Sync phase: </strong>Shared sync meetings are introduced, such as weekly or sprint meetings, where design and development discuss problems, questions, and suggestions, and agree on small steps to improve their collaboration.</p><p>Sometimes, the sync phase can reach a deadlock, where the team starts getting stuck in their own perspectives and needs to share their problems with a third party who is not as deeply immersed in the context. This person can help find solutions more quickly.</p><p>Deficiencies in processes related to design review, such as how it is conducted from the design side, what and how they review, are addressed. Critical design changes and priorities are determined. Misalignment between design layouts and compressed release timelines are addressed. Understanding how design processes translate into components in Figma, or vice versa when a design doesn’t know how components are transformed into code, is also resolved.</p><p><strong>Plateau phase:</strong> Creation of new pages/features/adjustments does not require major rework of key design system components or only involves minimal changes. Major changes in component behavior are possible. For example, rethinking UI/UX when something is found to be inconvenient and needs to be redesigned or when new components with different behaviors need to be introduced. New components are occasionally created.</p><p>During the redesign of our product, we went through all these stages of realization and acceptance at a relatively fast pace: we built a working product, not just components, within six months.</p><p>I’ll note that all three phases can repeat from time to time depending on the required changes. For example, when separating components into a separate library, adding theme management, establishing stricter component creation standards, or implementing them in a new project.</p><p>In the<a href="https://medium.com/quadcode-life/how-design-systems-are-created-sharing-our-own-example-part-2-df42f786ec1a"> second part of this monumental article</a>, I tell about how to define product requirements and, as a result, design system requirements and also explain why’ve chosen Mantine as a foundation for our own design system. Subscribe and stay tuned! I would be glad to answer any questions in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f58c6f3719" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quadcode-life/how-design-systems-are-created-sharing-our-own-example-part-1-82f58c6f3719">How design systems are created: sharing our own example. Part 1.</a> was originally published in <a href="https://medium.com/quadcode-life">Quadcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Как мы переводим приложение с 100+ страниц на SSR]]></title>
            <link>https://medium.com/%D0%B1%D0%BB%D0%BE%D0%B3-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%BE%D0%B2-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B0%D0%BD%D0%B8%D0%B8-%D0%B4%D0%B5%D0%BB%D0%BE%D0%B2%D0%B0%D1%8F-%D1%81%D1%80%D0%B5%D0%B4%D0%B0/from-client-side-rendering-to-server-side-rendering-on-nextjs-1b9388ec0f0?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b9388ec0f0</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 06:39:28 GMT</pubDate>
            <atom:updated>2021-01-27T06:39:28.420Z</atom:updated>
            <content:encoded><![CDATA[<p>В данной статье хочу рассказать об опыте перевода существующего проекта на Серверный Рендеринг (SSR). Объясню зачем нам это было необходимо, как внедряли, с какими проблемами столкнулись, что это нам дало. Ну и в целом кратко, что такое SSR, с чем его едят, и главное, как.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGiXQ1Q_VFX2GCPMCMg2wg.png" /><figcaption>Задействованные технологии в проекте</figcaption></figure><p>Я старший Frontend Engineer в команде платформы знаний и сервисов компании <a href="https://career.habr.com/companies/dasreda">“Деловая Среда”</a>.</p><p>Деловая среда — дочерняя компания Сбера, созданная с целью развития малого и среднего бизнеса. У нас есть одноименный проект для которого мои коллеги и я внедряли SSR.</p><p>Платформа представляет собой библиотеку статей, курсов, видео, траекторий и сервисов для успешного старта и развития своего дела с различными образовательными статьями и курсами.</p><p>Перед нами стояли задачи: улучшить индексацию данного приложения поисковыми системами и уменьшить время загрузки страниц до первого взаимодействия пользователя с контентом.</p><p>С момента старта приложения прошло более 3-х лет и портал, на тот момент, использовал только клиентский рендеринг (CSR, Client Side Rendering) для всех страниц. В феврале 2020 года в команде мы начали обсуждать идею о том, что необходимо переводить приложение на серверный рендеринг (SSR, Server Side Rendering).</p><p>Идея оказалась жизнеспособной и интересной, как для разработчиков, так и для бизнеса, который был заинтересован в привлечении трафика из поисковых систем.</p><p>Зачем вообще нужен SSR?</p><p>Не смотря на то, что поисковые системы потихоньку начинают все лучше и лучше работать с JavaScript — эта работа все еще далека от идеала. Поэтому поисковому роботу лучше скармливать уже готовую HTML страницу. Для этого необходимо использовать технологии пререндеринга страниц (этот подход не подошел, далее объясню почему) или переводить приложение на SSR.</p><p>Больше почитать на эту тему, можно по ссылкам ниже.</p><ul><li><a href="https://developers.google.com/search/docs/guides/dynamic-rendering?hl=ru">Настройка динамического отображения</a>;</li><li><a href="https://developers.google.com/search/docs/guides/fix-search-javascript?hl=ru">Устранение неполадок кода JavaScript, связанных с поиском</a>;</li><li><a href="https://pagepro.co/blog/ssrvscsr/">Server-Side Rendering vs Client-Side Rendering</a>;</li><li><a href="https://zeo.org/blog/javascript-seo-what-is-ssr-csr-advantages-and-disadvantages/">Javascript SEO: What is SSR/CSR? Advantages and Disadvantages</a>;</li><li><a href="https://www.deepcrawl.com/blog/webinars/webinar-recap-javascript-bartosz-goralewicz/">The Chaotic Landscape of JavaScript with Bartosz Goralewicz &amp; Jon Myers</a>;</li><li><a href="https://medium.com/@benjburkholder/javascript-seo-server-side-rendering-vs-client-side-rendering-bc06b8ca2383">JavaScript SEO: Server Side Rendering vs. Client Side Rendering</a>;</li><li><a href="https://medium.com/walmartglobaltech/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8">The Benefits of Server Side Rendering Over Client Side Rendering</a>;</li><li><a href="https://www.growth-rocket.com/blog/a-closer-look-at-client-side-server-side-rendering/">A Closer Look at Client-Side &amp; Server-Side Rendering</a>.</li></ul><p>Наше приложение состояло из:</p><ul><li>основного репозитория, где хранится код конечного приложения;</li><li>репозитория хэлперов — утилит и выделенной бизнес логики;</li><li>репозитория UI элементов и компонентов.</li></ul><p>Стек по ключевым технологиям на момент перехода: JavaScript, React, Redux, Node.js, GraphQL, Webpack, Ant Design, Axios, Lodash, LESS, CSS-modules.</p><h3>Провели исследование</h3><p>Перед тем как начать переводить приложение на SSR я проанализировал его и изучил доступные материалы на эту тему, чтобы понять каким способом будет оптимальнее внедрять серверный рендеринг.</p><p>Есть несколько вариантов перехода на SSR в уже существующем проекте:</p><ol><li><a href="https://docs.google.com/document/d/1wQzk0OCTcx3njuXtyasCow2M5j2XPfxH5BQWXlt8clY/edit#bookmark=id.eid5ymieiuzr">Способ 1. Пререндер существующего приложения</a></li><li><a href="https://docs.google.com/document/d/1wQzk0OCTcx3njuXtyasCow2M5j2XPfxH5BQWXlt8clY/edit#bookmark=id.wt0b5ija4kxs">Способ 2. Пишем свой велосипед-сервер</a></li><li><a href="https://docs.google.com/document/d/1wQzk0OCTcx3njuXtyasCow2M5j2XPfxH5BQWXlt8clY/edit#bookmark=id.5av41juvnh40">Способ 3. Выбираем один из специализированных фреймворков для SSR типа Next.js/Razzle/After.js/etc</a>.</li></ol><p>Рассмотрим все три варианта относительно нашего проекта.</p><h3>Способ 1. Пререндерим существующее приложение</h3><p>Нужно добавить прослойку в виде промежуточного сервера, который будет заниматься предварительным рендерингом необходимых страниц.</p><p>Возможные решения:</p><ol><li><a href="http://prerender.io/">prerender.io</a> — сторонний сервис, который можно подключить в проект;</li><li>поднять свое небольшое “облако” состоящее из headless chrome’ов и написать обвязку, которая будет управлять всем этим делом (кеширование/инвалидация кэшей/и пр.);</li><li>использовать что-то похожее на <a href="https://github.com/stereobooster/react-snap">react-snap</a>, который под капотом использует тот же headless chrome для рендеринга SPA.</li></ol><p>Плюсы:</p><ul><li>можно быстро внедрить MVP — хорошо как временное решение.</li></ul><p>Минусы:</p><ul><li>необходима оплата подписки для платных решений (бесплатные сервисы медленные), плюсом нужны инструменты для работы с инвалидацией закэшированных страниц;</li><li>обрастаем специфическими инструментами и бизнес логикой вокруг стороннего инструмента, вместо написания фронтенда;</li><li>свой хостинг headless chrome’ов прожорлив к системным ресурсам;</li><li>при использовании headless chrome’ов при постоянных запросах можно напороться на утечки памяти и нужно будет перезапускать;</li><li>headless chrome может не дождаться окончательной загрузки SPA и выплюнуть обычное CSR приложение, тоже нужно как-то за этим следить;</li><li>плохо подходит для приложения, у которого постоянно увеличивается количество страниц и контента.</li></ul><h3>Способ 2. Пишем свой велосипед-сервер</h3><p>При таком подходе каждый собирает свой конфиг для рендеринга приложения на сервере самостоятельно.</p><p>Как показывает практика и опыт изученных материалов, нет какого-то однозначного подхода как это внедрить. Есть общие концепции, но нюансы у каждого проекта будут свои.</p><p>Сначала рассмотрим, что нужно сделать перед внедрением SSR с помощью данного подхода.</p><p>Для начала необходимо сформировать полностью плоские роуты и вынести их на уровень конфигурации, иначе придется разбирать дерево маршрутов. Это самый худший вариант — разбирать дерево реакт компонентов и вызывать инициализацию данных для внутренних маршрутов. Плоский список роутов позволяет по сути просто пробежаться по нему, сматчить нужный маршрут и вызвать инициализацию данных, затем прокинуть их в приложение, что касается redux или apollo.</p><p>Внедрить разделение кода по маршрутам, чтобы подгружались только необходимые чанки для конкретной страницы. Тоже может оказаться нетривиальной задачей, так как программного кода довольно много и это может вызвать ненужные коллизи в работе приложения.</p><p>При работе с Apollo на клиенте, есть особенность с вложенными запросами в дочерних компонентах: они не будут вызваны на стороне сервера, если компоненты изначально скрыты и их отображение зависит от родительских данных (запроса). С этим тоже нужно что-то делать: например, все манипуляции на запрос данных уносить на верхний уровень необходимой страницы.</p><p>Также, необходимо пробежаться по всему приложению и найти компоненты и библиотеки использующие обращение к window объектам при рендеринге страницы:</p><ul><li>обернуть эти компоненты в динамические импорты без инициализации на сервере;</li><li>или переписать их, чтобы вызов window происходил только на клиенте, но компонент рендерился на сервере.</li></ul><p>Необходимо настроить работу со стилями, чтобы на клиенте загружались только нужные для конкретной страницы стили. Кажется, это не самая легкая задача без CSS-in-JS и нашей кастомизацией стилей для Ant Design компонентов.</p><p>Также стоит провести анализ, есть ли утечки памяти на страницах приложения — это может дать знать о себе при рендеринге на сервере.</p><p>Нужно оптимизировать работу с API, чтобы эндпоинты отдавали данные максимально быстро. Иначе пользователь будет видеть белый экран продолжительное время — больше время ответа от API, больше время ответа клиенту. И SSR будет отъедать больше ресурсов сервера, чем это необходимо. Соответственно, в единицу времени мы сможем обработать меньше запросов — нужно будет увеличивать ресурсы.</p><p>Подводя итог: при внедрении SSR с помощью данного подхода есть высокий шанс в будущем ловить “флэшбеки” в разных частях приложения, связанные с тем, что где-то что-то не работает или работает не так.</p><p>Информация по SSR и проблемам возникающим с таким подходом очень разрозненна. 100% внедрение этого подхода произойдет не по щелчку пальцев.</p><p>Вероятен шанс так до конца и не внедрить полноценный SSR или просто потратить очень много времени на борьбу с багами.</p><p>И скорее всего, я упомянул не все проблемы с которыми придется столкнуться, а только базовые, которые нужно решить в первую очередь.</p><h3>Способ 3. Выбираем один из специализированных фреймворков для SSR типа Next.js/Razzle/After.js/etc</h3><p>Внедрить в текущее решение один из существующих специализированных фреймворков для SSR сложно — это не какой-то npm пакет, который подключил и все работает.</p><p>Данный подход подразумевает, что мы будем поддерживать две версии нашего приложения: старого (CSR), которое нужно поддерживать и написание нового приложения (SSR). На время перехода они будут жить параллельно друг другу.</p><p>При выборе SSR фреймворка не стоит использовать starter-* сборки на основе фреймворков, потому что:</p><ul><li>в наличие присутствует множество ненужных функций без возможности их просто выключить, которые могут не понадобиться для реализации проекта;</li><li>часто в таких сборках можно встретить новые нерешенные проблемы и придется допиливать самостоятельно;</li><li>отсутствует понятная политика выпуска новых версий;</li><li>ограниченное комьюнити, которое возможно не сможет помочь;</li><li>сложно поддается внедрению новых возможностей;</li><li>отсутствует постоянная поддержка;</li><li>часто отсутствует документация как таковая.</li></ul><p>Вместо starter-* лучше использовать специализированный SSR фреймворк и настроить его с чистого листа.</p><p>В чем плюс специализированных фреймворков, если мы сетапим их с нуля и только под наши нужды:</p><ul><li>хорошая поддержка — есть основные мейнтейнеры и их довольно много;</li><li>хорошее и активное комьюнити;</li><li>есть достаточно понятная документация;</li><li>есть roadmap развития проекта;</li><li>хорошие примеры;</li><li>понятный путь кастомизации;</li><li>качество — старый технический долг будет выплачен и произойдет улучшение качества приложения (legacy -&gt; without legacy).</li></ul><p>Из минусов специализированных фреймворков: нужно будет мириться с предлагаемой архитектурой, но зато решение будет работать и скорее всего закроет 99% потребностей.</p><p><a href="https://www.npmtrends.com/razzle-vs-next-vs-nuxt">Сравнительный график</a> использования самых популярных решений для SSR за все время. На текущий момент активное использование Next.js на порядок больше чем Razzle/After.js. Nuxt в расчет не берем — так как приложение мы пишем на React.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3KnIqDjv5Kg4BHK-" /><figcaption>Сравнительный график популярных решений для SSR</figcaption></figure><p>Кратко сравним плюсы и минусы подходов.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v57bEA2_fK85KgC8lq8Jiw.png" /><figcaption>Плюсы и минусы подходов при переходе на SSR</figcaption></figure><h3>Обсудили результат исследования</h3><p>Первый подход по итогам обсуждения был отброшен, потому что хотели заниматься развитием проекта, а не написанием инструментов вокруг существующего приложения.</p><p>От второго подхода тоже решено было отказаться и попробовать использовать третий вариант, но с некоторыми нюансами.</p><p>В качестве эксперимента, чтобы окончательно обосновать бизнесу, что необходима разработка параллельного приложения, я попробовал перенести старые UI компоненты на Next.js.</p><p>По идее — это самый оптимальный подход по таким характеристикам как:</p><ul><li><em>время</em> — большая часть проекта уже написана и перенос проекта не занимает столько же времени, сколько написание полностью с нуля.</li><li><em>результат</em> — с костылями, но в конечном итоге проект будет работать, так как перенос по частям позволяет решать проблемы по мере поступления. При этом ровно столько же времени можно потратить на 2 способ, занимаясь написанием своего велосипеда, только без гарантии результата;</li><li><em>качество</em> — скорее всего станет лучше, частично будет переосмыслена архитектура приложения и при переносе будет сделан упор на аспекты связанные с SSR.</li></ul><p>Минусы:</p><ul><li>останется старый UI, который в случае ребрендинга потащит за собой все старые болячки;</li><li>нет возможности сразу писать в едином стиле, всегда будут появляться новые бизнес фичи, которых не было в старом варианте. Например мы хотим TS (TypeScript) и Styled Components, а старый проект написан на JS и LESS/SASS/CSS modules;</li><li>тащим старый стейт менеджмент, который не всегда оптимален.</li></ul><h3>Собрали демо-стенд</h3><p>У нас давно назревал отказ от UI использующего Ant Design — 3 версия, которая обновлялась со 2-ой, плюс было много оберток над внутренними стилями в т.ч. и полный копипаст из Antd компонентов.</p><p>И тут этот вопрос встал довольно остро.</p><p>В итоге я собрал тестовый стенд с: TypeScript, Styled Components + LESS/SASS/CSS modules (для подключения старых компонент), Next.JS, подключен Apollo Client для работы с нашим GraphQL сервером. Созданы example страницы, содержащие:</p><ul><li>компоненты использующие Styled Components;</li><li>запросы к Apollo Server за данными и отображение этих данных на странице;</li><li>вывод данных из cookies;</li><li><strong>компоненты: Button, Content, Row, Col из старой UI библиотеки с Ant Design.</strong></li></ul><p>Проанализировал итоговый бандл, без старой библиотеки компонентов, и с ней. Получил следующий результат: <strong>+350кб</strong> к каждой странице при использовании старого UI.</p><p>По хорошему нужно было использовать ES модули из Ant Design — в этом случае получаются атомарные компоненты со своими стилями.</p><p>Но в текущей реализации этого не получалось сделать из-за сборки стилей. Совсем хорошо отказаться от использования antd, чтобы использовать только то, что действительно необходимо, не затаскивая лишние зависимости.</p><h3>Пришли к решению</h3><p>Какое-то время общались с бизнесом, обсуждали внутри команды и в конечном итоге остановились на том, что будем полностью писать с нуля приложение на SSR с использованием Next.js, появятся: новый дизайн, компоненты, требования к стандартам и архитектуре.</p><p>Когда новая страница будет реализована, будем переключать ее на балансере (Nginx) на новую SSR версию, а старый код удалять. Таким образом произойдет постепенная миграция приложения на SSR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59V9QTLol2s8YKDEg5DWZg.png" /><figcaption>Коллаборация команд позволила перейти к новым: UI Kit и Web App</figcaption></figure><p>Для взаимодействия с поисковыми роботами есть подход, называемый <a href="https://developers.google.com/search/docs/guides/dynamic-rendering">“Динамический рендеринг”</a> — подход который позволяет отдавать разный контент поисковикам и пользователям.</p><p>Мы решили не использовать динамический рендеринг в прямом его понимании и пошли только от пользователей. Для неавторизованных пользователей отдаем версию отрендеренную на сервере или из кэша. Робот считается неавторизованным пользователем. Для авторизованных пользователей отдаем версию, которая рендерится на клиенте.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4303q08XrQALTuyG7cypeg.png" /><figcaption>Когда рендерить на клиенте, а когда на сервере?</figcaption></figure><p>Первой страницей было решено переделать страницу подписки на доступ к платному контенту — на CSR это был по сути лендинг, который рассказывал о нашем продукте. В новой версии это становится полноценной страницей — витриной материалов с разбиением по категориям, где категории тоже являются отдельными страницами.</p><h3>Решили проблемы</h3><p>Было принято решение писать на TypeScript сразу, до этого не было большого опыта с написанием всего проекта на TS. В первые недели бывало уходило пару-тройку часов на то, чтобы разобраться какой тип нужен и как его правильно описать, особенно с npm зависимостями. Было тяжело не писать any везде, но мы справились, иначе зачем внедрять TS? Да это отняло много времени, но в итоге принесло хорошие плоды.</p><p>Довольно много времени ушло, на коммуникацию с DevOps, для того, чтобы грамотно развернуть приложение на всех контурах.</p><p>Был переосмыслен процесс сборки и выкатки на контуры. До этого у нас был предпрод, для которого собирались контейнеры и они же выкатывались на prod контур. И в старом приложении частенько приходилось писать логику, на основе определения окружения по url или cookies.</p><p>В случае с SSR было принято решение, что для prod контуров будет полностью отдельная сборка, чтобы все, что нам нужно мы могли передать через <em>.env</em> файл. Так как рендер происходит на сервере, то нам не нужно на стороне express сервера по заголовкам понимать с какого контура пришел запрос и прокидывать эти данные внутрь Next.js приложения.</p><p>На старте не было возможности учесть все нюансы реализации:</p><ul><li>возможного поведения и состояния компонентов;</li><li>правки на баги при тестировании QA;</li><li>что в какой-то момент сломается рендеринг на сервере и придется откатываться по истории git и смотреть, что его сломало;</li><li>что уйдет время, на то, чтобы провести нагрузочное тестирование;</li><li>несколько раз пересмотреть часть архитектуры по мере выполнения задач;</li><li>обсудить и принять решение о том, как мы работаем с картинками (svg и обычными);</li><li>детальное ревью членами команды и внесение правок, так как это важная веха в развитие проекта;</li><li>выработать концепцию работы с Apollo — генерация типов, локальное хранилище, работа с запросами на разных уровнях приложения;</li><li>и еще много различных мелких нюансов.</li></ul><p>В целом, перевод первого раздела портала включал в себя не только его разработку, но и принятие множества архитектурных решений, устаканивание всей новой кодовой базы в процессе ревью, написания тестов и т.д.</p><p>По сути на первом этапе мы заложили 90% фундамента, на основе которого будут строиться все остальные страницы.</p><p>Перевод на SSR последующих разделов сайта (например статей), уже обошелся нам без превышения сроков в 3 раза, начали укладываться практически один в один по плану.</p><p>В итоге для организации проекта был создан <strong>monorepo</strong> с использованием <a href="https://github.com/lerna/lerna">lerna</a>.</p><p>Итоговая архитектура приложения, в упрощенном виде, выглядит так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFsIAdmTE2srMGDr3nP-Fg.png" /><figcaption>Архитектура SSR приложения</figcaption></figure><p>Первоначальная оценка для запуска первой SSR фичи была <em>в </em><strong><em>2 недели 5 дней</em></strong> на весь новый раздел. <strong>Реальное время</strong> на выход в production заняло <strong><em>9 недель и 2 дня</em></strong>. Время мы считали по YouTrack.</p><h3>Как мы работаем с рендерингом страниц</h3><p>Мы используем кастомный сервер на основе express, который позволяет нам описывать дополнительную логику работы с кэшированием страниц в Redis.</p><p>Однако, если вы тоже используете Next.js и метод app.renderToHTML, то лучше перестать это делать, так как это приватный метод. Начиная с версии 9.5 мы столкнулись с проблемой выставления заголовков ответа при рендеринге страницы из кэша. Были изменены внутренности этого метода. Теперь необходимо использовать метод app.render, который отрабатывает <a href="https://github.com/vercel/next.js/issues/16725#issuecomment-689268390">корректно</a> и является публичным для использования.</p><p>Страницы, которые доступны всем, мы кладем в кэш Redis на 5–60 минут, в зависимости от приоритета, чтобы снять нагрузку с сервера, так как операция рендеринга данных, является затратной операцией.</p><p>До июня 2020 мы использовали 9 версию Next.js, и для того, чтобы инициализировать данные на стороне сервера в Apollo мы использовали большой HOC, который разбирал все дерево запросов к apollo-server в компонентах — можно назвать его магическим Dependency Injection, который нам не очень нравился в использовании и вызывал определенные проблемы:</p><ul><li>некорректная работа с error состоянием (не важно какие были использованы error policy) в запросах при рендере на стороне сервера. Ошибки, которые происходили на стороне сервера в запросах, рендерились только на сервере, но на клиенте при rehydrate исчезали. Для решения этой проблемы мы перенесли ошибочный ответ в data и проверяли пришедший __typename, чтобы определить ошибку или корректный ответ;</li><li>для того, чтобы сделать редирект или отдать корректный HTTP код на основе полученных данных, приходилось подмешивать серверный контекст, которому совершенно не место в компонентах, но выхода не было;</li><li>иногда ломалась логика работы loading состояния.</li></ul><p>В версии Next.js 9.3 были анонсированы новые вспомогательные <a href="https://nextjs.org/blog/next-9-3#next-gen-static-site-generation-ssg-support">методы</a> getServerSideProps / getStaticProps, которые позволили нам избавиться от этого HOC и запрашивать данные в getServerSideProps функции, в которой мы имеем прямой доступ к Apollo Client, серверному контексту и пр. Можем корректно работать с ошибками в error, дожидаться ответа и инициализировать состояние Apollo или делать необходимые редиректы вне React страниц/компонент и оставить запрос за данными на самом верхнем уровне — мы не используем запросы за данными во внутренних компонентах страницы.</p><h3>Результаты</h3><p>Пожалуй, это все аспекты, которые хотел затронуть в этой статье.</p><p>Работы за последние 8 месяцев с запуска SSR, было проделано колоссальное количество и еще больше предстоит.</p><p>Из положительных эффектов, которые принес нам процесс перевода приложения на SSR можно выделить следующее:</p><ul><li>индексация поисковыми системами страниц отрендеренных на стороне сервера;</li><li>использование на SSR в качестве стейт менеджера Apollo и соответственно отказ от запросов в микросервисы на прямую в отличие от CSR версии портала, в которой был смешан Apollo, работа с REST API, и управление state через redux;</li><li>избавились от рендеринга Markdown разметки в React — перешли на формирование контента с использованием <a href="https://editorjs.io/">editor.js</a>;</li><li>внедрение разметки по Schema.org;</li><li>улучшилось восприятия контента пользователями (результат общения с клиентами);</li><li>потихоньку избавляться от legacy (и идти к новому :)).</li></ul><p>поднялась оценка по PageSpeed Insights.</p><p>Для переведенных на SSR страниц подписки с 15 пунктов:</p><ul><li>до 40 пунктов с учетом подключенных third-party скриптов;</li><li>до 86 пунктов без использования third-party скриптов.</li></ul><p>Для переведенных на SSR страниц статей с 20–28 пунктов:</p><ul><li>до 50–60 пунктов с учетом подключенных third-party скриптов;</li><li>до 86–96 пунктов без использования third-party скриптов.</li></ul><p>В 4 квартале 2020 для страниц подписки и статей:</p><ul><li>вырос органический трафик из поисковых систем на 26%;</li><li>глубина просмотра увеличилась на 70%;</li><li>среднее время на сайте увеличилось на 1 минуту.</li></ul><p>Была оптимизирована метрика Time to Interactive (TTI):</p><ul><li>для мобильных стал ~12.3 секунды (было ~20 секунд)<em> [еще предстоят работы по оптимизации]</em>;</li><li>для ПК стал ~3.8 секунды (был ~4 секунды, фактически ~8.5 секунд — в старой версии приходилось ждать контент еще примерно 3–5 секунд — пользователь мог видеть только меню и футер. Сейчас получает весь контент и может начинать с ним взаимодействие).</li></ul><p>Также была оптимизирована метрика First Contentful Paint (FCP):</p><ul><li>для мобильных стал ~1.6 секунды (был ~8.3 секунды);</li><li>для ПК стало ~0.4 секунды (был ~2 секунды).</li></ul><p>Параллельно с переходом на SSR:</p><ul><li>удалось запустить Gitlab CI, в котором гоняем: линтеры, валидность TS, тесты. Эти же процессы удалось распространить на все репозитории нашей фронтовой команды;</li><li>повысилось качество приложения, безопасность изменений и внедрения новых фич, надежность работы приложения при использовании TS;</li><li>произошел отказ от Ant Design и появилась возможность разрабатывать собственный UI Kit, который мы можем модифицировать и затачивать под наши конкретные нужды.</li></ul><p>P.S.</p><p>Если вам интересно узнать больше об аспектах с которыми мы столкнулись в процессе перевода приложения на SSR, проголосуйте в комментариях за одну из следующих тем:</p><ol><li>Monorepo + TS + Apollo + SSR (Next.js);</li><li>Monorepo + TS + HMR в Next.js (Hot Reload на Client / Server);</li><li>Apollo + Local state management в Next.js;</li><li>Next.js + работа с кэшированием.</li><li>Работа с переходами между SSR / CSR и не только.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b9388ec0f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%D0%B1%D0%BB%D0%BE%D0%B3-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%BE%D0%B2-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B0%D0%BD%D0%B8%D0%B8-%D0%B4%D0%B5%D0%BB%D0%BE%D0%B2%D0%B0%D1%8F-%D1%81%D1%80%D0%B5%D0%B4%D0%B0/from-client-side-rendering-to-server-side-rendering-on-nextjs-1b9388ec0f0">Как мы переводим приложение с 100+ страниц на SSR</a> was originally published in <a href="https://medium.com/%D0%B1%D0%BB%D0%BE%D0%B3-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%BE%D0%B2-%D0%BA%D0%BE%D0%BC%D0%BF%D0%B0%D0%BD%D0%B8%D0%B8-%D0%B4%D0%B5%D0%BB%D0%BE%D0%B2%D0%B0%D1%8F-%D1%81%D1%80%D0%B5%D0%B4%D0%B0">Блог разработчиков компании “Деловая Среда”</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Что можно узнать при разработке аудио плеера для разных браузеров]]></title>
            <link>https://medium.com/@dipiash/%D1%87%D1%82%D0%BE-%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE-%D1%83%D0%B7%D0%BD%D0%B0%D1%82%D1%8C-%D0%BF%D1%80%D0%B8-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B5-%D0%B0%D1%83%D0%B4%D0%B8%D0%BE-%D0%BF%D0%BB%D0%B5%D0%B5%D1%80%D0%B0-%D0%B4%D0%BB%D1%8F-%D1%80%D0%B0%D0%B7%D0%BD%D1%8B%D1%85-%D0%B1%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80%D0%BE%D0%B2-742c02bea183?source=rss-ab2d8c832e5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/742c02bea183</guid>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[исследование]]></category>
            <dc:creator><![CDATA[Dmitrii Pashkevich]]></dc:creator>
            <pubDate>Tue, 05 Feb 2019 11:08:05 GMT</pubDate>
            <atom:updated>2019-02-05T11:08:05.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Эта история началась примерно 1.5 года назад. Связана она с проигрыванием музыки в различных браузерах и платформах, на которых они запускаются. Путь полный “боли и страдания” осознания того, что легкая на первый взгляд задача может оказаться не такой уж и легкой, а “незначительные” детали, которым не придаешь значения в самом начале, могут повлиять на всё.</p><p><strong>Незначительные детали для самых любопытных :)</strong></p><ol><li>Подгрузка данных о каждом следующем треке из сети.</li><li>На каждый элемент аудио: new Audio() или &lt;audio&gt; нужно разрешение пользователя — пользовательское действие на странице.</li></ol><p>Наверное, каждый, кто хоть раз в своей жизни писал аудиоплеер для браузеров, сталкивался с проблемой кроссбраузерности и кроссплатформенности. Вот и я во время работы над новым MVP столкнулся с различными особенностями в отношении проигрывания аудио в браузерах. А началось всё с того, что нужно было сделать плавное сведение (crossfade) двух треков при воспроизведении — это первая особенность. Наша команда хотела сделать смену треков как на радио. И вторая особенность — каждый последующий трек запрашивается из сети.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uN4PzZ5MbgXXuszh.png" /></figure><h3>Изыскания</h3><p>Тогда почти во всех наших проектах использовалась библиотека Sound Manager 2. Практически сразу понимаешь, что воспроизведение одновременно двух аудио файлов на мобильных устройствах не везде одинаково работает!</p><p>В Chrome (~62 версия) для ПК треки воспроизводились как надо. На мобильных устройствах (тоже в Chrome) воспроизведение треков работало, но только при активном экране. Когда экран блокировался, следующий трек за текущим играющим не воспроизводился. Что касается iOS / macOS — воспроизведение работало аналогичным образом. Больше информации можно получить <a href="https://www.ibm.com/developerworks/ru/library/wa-ioshtml5/">тут</a> — раздел “Единичный аудиопоток”.</p><p>Так начались хождения за три моря поиски информации по крупицам об особенностях работы браузеров с аудио.</p><p>Хорошо, пробую решение с Web Audio без использования каких-либо библиотек. Да, эта технология предназначена для иных целей: синтез, обработка звука, для игр и т.д., нежели простое воспроизведение треков. Но ради эксперимента нужно было попробовать, так как она позволяет компоновать звуки из разных источников на один один <a href="https://www.html5rocks.com/en/tutorials/webaudio/intro/#toc-xfade">звуковой выход</a> — колонки/наушники/динамик телефона/и т.п. Есть ребята, которые целенаправленно <a href="https://medium.com/@Rich_Harris/phonograph-js-tolerable-mobile-web-audio-55286bd5e567">занимаются исследованием</a> возможностями воспроизведения звука на мобильных устройствах с использованием Web Audio API.</p><p>После реализации выяснились определенные нюансы. Во-первых, необходимо дожидаться полной загрузки всего трека. При медленном соединении с интернетом будут заметны паузы из-за того, что второй трек может не успеть загрузиться к моменту окончания первого трека. Полной загрузки можно избежать, если использовать связку с HTML5 Audio тегами, которые будут выступать в качестве источников звука для Web Audio, но в этом случае снова становится невозможным воспроизведение двух звуков одновременно. Во-вторых, если загружать трек по сети фрагментами и декодировать их программно, то это увеличивает нагрузку на CPU. Для ПК было приемлемо, а вот для мобильных устройств критично.</p><p>В-третьих, возникли проблемы с декодированием. Если на клиент приходили фрагменты mp3/ogg/wav файлов, то эти кусочки спокойно <a href="https://developer.mozilla.org/ru/docs/Web/API/AudioContext/decodeAudioData">декодировались</a> и воспроизводились. Но если в браузер приходили чанки mp4 файла, который выступал контейнером для HE-AAC, то их тогда декодировать не удалось. Это в некоторой степени касается и браузера Opera, в котором от версии к версии нестабильно работает воспроизведение MP3 файлов — то воспроизводит, то выдает ошибку, что данный формат не поддерживается.</p><p>В-четвертых, не отображалось / не менялось название трека на заблокированном экране на плашке с нативным аудио плеером (на iPad), в т.ч. при переключении между треками. Возможно из-за того, что для тестов использовался iPad с 9 версией iOS — другого на тот момент не было. В итоге, на данном этапе от Web Audio пришлось отказаться. Всё-таки crossfade не для браузеров, стандартные музыкальные композиций в хорошем качестве достаточно много весят. Раз от crossfade отказываемся, то реализуем простой fade in и fade out, в начале и в конце музыкального трека соответственно. Код на позапрошлом шаге был немного доработан и протестирован. В результате тестов всплыли различные нюансы (показаны в таблице). Все это с использованием библиотеки Sound Manager 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ebtcfMMJ9k6Nobxn.png" /></figure><p>Добавляем логирование всех событий, чтобы определить момент перехода между треками и понять в какой момент они перестают воспроизводиться.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rRv_mtHmKgYSmLlM.png" /></figure><p><strong>Активация вкладки</strong></p><p>В браузере Safari 9+ звук при активации вкладки не всегда появляется.</p><p>Из этого можно предположить, что выполнение JS в фоне подвергается throttling’у или поток выполнения полностью останавливается (события и <a href="https://stackoverflow.com/questions/15871942/how-do-browsers-pause-change-javascript-when-tab-or-window-is-not-active">таймеры</a>). Однако, позже станет понятно, что это был отчасти корректный вывод. Ниже будет рассмотрен еще 1 нюанс, связанный с воспроизведением треков и осознанием почему звук не появляется.</p><p><strong>Ремарка</strong></p><p>Для работы с прогрессом (progressbar), например, его отрисовкой для трека, хорошо использовать requestAnimationFrame вместо setInterval/setTimeout. Можно избежать накопительного эффекта при деактивации (background tab) и последующей активации вкладки и временного ее подвисания, связанного с выполнением всех вычислений и перерисовок состояния прогресса.</p><p>В этот же момент возник вопрос: а как же быть с автовоспроизведением треков на ПК и на мобильных устройствах?</p><blockquote><em>Под автовоспроизведением понимается — автоматический старт проигрывания трека без каких-либо действий пользователя при загрузке страницы.</em></blockquote><p>Что касается Safari в отношении <a href="https://mackeeper.com/blog/post/444-safari-11-block-autoplay-videos-and-website-tracking/">автоматического воспроизведения</a> при загрузке страницы, то это невозможно, нужно <a href="https://www.reddit.com/r/webdev/comments/71nkym/safari_11_has_a_major_change_to_web_audio_api/">взаимодействие пользователя</a> со страницей, как и на <a href="https://bitmovin.com/play-not-play-new-autoplay-policies-safari-11-chrome-64/">мобильных устройствах</a>. Это касается как <a href="https://support.apple.com/ru-ru/guide/safari/stop-autoplay-videos-ibrw29c6ecf8/mac">видеоконтента</a>, так и <a href="https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/">аудиоконтента</a>. И так, на тот момент было следующее:</p><ol><li>нельзя (не желательно) воспроизводить два и более звуков одновременно;</li><li>для псевдо “автовоспроизведения” трека необходимо разрешение пользователя — первое взаимодействие, позже это было названо “Продать пальчик устройству”;</li><li>в фоне (background tab / lock screen) JS (все зависит от браузера): либо замирает полностью; либо подвергается throttling’у; либо работает также, как и при активной вкладке;</li><li>можно автоматически стартовать воспроизведение без звука, но непонятно зачем (для аудио контента)?</li><li>где-то далеко начинает маячить мысль, а как сделать так, чтобы JS в фоне продолжал выполняться?</li></ol><p>В дело пошли другие библиотеки реализующие функции плеера с предположением, что возможно там есть решение для этой задачи. Несмотря на то, что было просмотрено множество issues на GitHub с описание проблем при воспроизведении треков в различных браузерах, все же была надежда на то, что вот-вот доберешься до сути: почему не работает и как сделать, чтобы работало. Как оказалось, нет… Несколько примеров кода с видео демонстрацией работы библиотек:</p><ol><li>Sound Manager 2 — <a href="https://dipiash.github.io/audio_examples/2.html">github pages</a>, <a href="https://github.com/dipiash/audio_examples/blob/master/2.html">github репозиторий</a>, видео: <a href="https://dipiash.github.io/audio_examples/videos/macos/2_macos_sm2.mp4">macOS Safari 12</a>;<a href="https://dipiash.github.io/audio_examples/videos/ios/2_not_lock_screen_not_sound.mp4"> iOS Safari 10</a> при разблокированном экране</li><li>Howler<br> Howler v2.0.9 — <a href="https://dipiash.github.io/audio_examples/3.html">github pages</a>, <a href="https://github.com/dipiash/audio_examples/blob/master/3.html">github репозиторий</a>, видео: <a href="https://dipiash.github.io/audio_examples/videos/macos/3_macos_howler-2.0.9.mp4">macOS Safari 12</a>, <a href="https://dipiash.github.io/audio_examples/videos/ios/3_lock_screen.mp4">iOS Safari 10</a><br> Howler v2.0.15 — <a href="https://dipiash.github.io/audio_examples/4.html">github pages</a>, <a href="https://github.com/dipiash/audio_examples/blob/master/4.html">github репозиторий</a>, видео: <a href="https://dipiash.github.io/audio_examples/videos/macos/4_macos_howler-2.0.15.mp4">macOS Safari 12</a><br> Howler v2.1.1 — <a href="https://dipiash.github.io/audio_examples/5.html">github pages</a>, <a href="https://github.com/dipiash/audio_examples/blob/master/5.html">github репозиторий</a>, видео: <a href="https://dipiash.github.io/audio_examples/videos/macos/5_macos_howler-2.1.1.mp4">macOS Safari 12</a>, <a href="https://dipiash.github.io/audio_examples/videos/ios/5_lock_screen.mp4">iOS Safari 10</a></li></ol><blockquote><em>Для macOS запись видео сделана без звука, поэтому нужно смотреть на индикатор громкости — изображение динамика, на вкладке.</em></blockquote><blockquote><em>В репозитории доступно больше видео примеров.</em></blockquote><blockquote><em>В интерактивном примере для Howler v2.1.1 — иногда можно услышать несколько звуков одновременно, это связано с добавлением пула разблокированных пользователем audio элементов (в будущих версиях библиотеки это должны исправить).</em></blockquote><p>В чем причина неработоспособности этих библиотек?</p><p>Выше я писал: <em>“В фоне (background tab) JS либо замирает полностью, либо подвергается throttling’у”</em>. Так вот тут всплывает другой момент: библиотеки в коде используют создание новых аудио объектов через new Audio(). Если они создаются динамически, т.е. не используется уже существующий аудио объект, и при этом пользователь никак не взаимодействует с сайтом, неактивна вкладка или заблокирован экран, то некоторые браузеры могут посчитать, что воспроизводить звук от этого аудио элемента не следует, пока вкладка не будет снова активна или пользователь не совершит какое-либо действие.</p><p>Пример теста на <a href="https://dipiash.github.io/audio_examples/6.html">github pages</a> и в <a href="https://github.com/dipiash/audio_examples/blob/master/6.html">репозитории на github</a> с использованием new Audio(). Видео: <a href="https://dipiash.github.io/audio_examples/videos/macos/6_macos_newAudio.mp4">macOS Safari 12</a>; <a href="https://dipiash.github.io/audio_examples/videos/ios/6_not_lock_screen.mp4">iOS Safari 10</a> с разблокированным экраном.</p><p><strong>Похоже, что какого-то универсального инструмента не существует и нужно искать какое-то другое компромиссное решение.</strong></p><p>Дальше садимся с ребятами из команды обсудить, а что действительно важно в работе аудио плеера? Ибо продолжать эксперименты можно было бы до бесконечности, но нужно двигаться вперед. Сначала были выявлены важные моменты, которые мешали достичь желаемого результата:</p><ol><li>в браузере Safari на macOS не воспроизводятся треки при неактивной вкладке;</li><li>отсутствует возможность слушать музыку в фоне (при заблокированном экране) на смартфонах, работающих на iOS и Android, хотелось бы избежать агрессивного перенаправления пользователей в мобильное приложение (в дальнейшем), так как предыдущий опыт показывает, что довольно большая часть пользователей не желает ставить мобильное приложение;</li><li>плеер некорректно работает с динамическим плейлистом, т.е. когда заранее не известно, какой будет следующий трек.</li></ol><p>Далее это позволило сформулировать цели, которые было необходимо достичь:</p><ol><li>обеспечить работу плеера в фоновом режиме — в различных браузерах и на различных платформах;</li><li>позволить пользователю самому выбирать чем пользоваться: прослушивать музыку на сайте или в мобильном приложении;</li><li>обеспечить возможность использовать плеер (или подход) в различных будущих проектах.</li></ol><p>Начался новый этап поиска решения поставленной задачи. На этом этапе уже не использовались различные библиотеки, все исследования велись с использование HTML5 Audio. Итогом стало то, что был найден вариант с использованием <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Dedicated_workers">dedicated workers</a>. iOS это решение победить опять не позволило — воспроизведение в фоне не работает, зато получилось добиться работоспособности в Android (Chrome, Opera, Safari).</p><p>Пример теста HTML5 Audio + Dedicated Workers <a href="https://dipiash.github.io/audio_examples/worker/index.html">на github pages</a> и в <a href="https://github.com/dipiash/audio_examples/tree/master/worker">репозитории на github</a>.</p><p>При инициализации Worker’а запрашиваются данные о текущем треке. Worker также занимается отправкой сигнала на получением состояния прогресса — сколько времени трек играет — из основного потока и на основе этих данных решает когда запросить данные о следующем треке из сети.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gRqLFXWZdDAgFfkb.png" /></figure><p>Также в то время был протестирован следующий пример (<a href="https://dipiash.github.io/audio_examples/index.html">github pages</a>, <a href="https://github.com/dipiash/audio_examples/blob/master/index.html">репозиторий на github</a>), когда HTML5 audio тег встраивается в DOM (видео: <a href="https://dipiash.github.io/audio_examples/videos/macos/1_macos_html5_audio.mp4">macOS Safari 12</a>, <a href="https://dipiash.github.io/audio_examples/videos/ios/1_html_lock_screen.mp4">iOS Safari 10</a>) и у него просто подменяется SRC при переключении между треками. На сегодняшний день на macOS в 12 Safari этот пример работает. К сожалению, сейчас нет возможности проверить работоспособность этого примера на macOS в Safari 10 и 11 версии, но на тот момент при проведении тестов этот пример не работал (<a href="https://bitmovin.com/play-not-play-new-autoplay-policies-safari-11-chrome-64/">autoplay policies</a>, <a href="https://stackoverflow.com/questions/44629198/safari-11s-new-autoplay-restrictions-on-html5-audio">autoplay restrictions</a>).</p><p>Если подытожить, то для iOS и macOS браузер Safari не считает новый экземпляр аудио элемента активированным пользователем, если он был создан в фоновом режиме внутри какого-либо события, например, ajax, setTimeout, onended.</p><p>Далее, что касается воспроизведения треков в iOS Safari и iOS Chrome, была найдена возможность воспроизводить треки в фоновом режиме (при заблокированном экране) только с использованием <a href="https://developer.apple.com/streaming/">HLS</a>. Для платформ iOS и macOS этот формат является стандартом и вещание поддерживается операционной системой. Для Android Chrome и Edge также доступна нативная реализация. А для ПК в Chrome — можно использовать программные обработчики, например, <a href="https://github.com/video-dev/hls.js/">hls.js</a>, <a href="https://bitmovin.com/video-player/">Bitmovin Player</a> и т.д.</p><p>По <a href="https://github.com/dipiash/hls_audio_player_example">ссылке на github репозиторий</a> доступен пример кода, который охватывает самый простой вариант использования — простое проигрывание генерируемого на сервере потока воспроизведения без возможности перемотки, переключения на следующий трек и т.д. Представлены примеры с использованием: тега audio, тега video, библиотеки hls.js, и плеера от Bitmovin. Для запуска требуется Node.js.</p><h3>Выводы</h3><p>Первый момент, к сожалению, из-за всего многообразия браузеров нет какого-то универсального решения, которое бы позволило везде одинаково хорошо прослушивать музыку в браузерах. Везде есть свои ограничения и как показывает практика с ними можно, вполне, комфортно жить.</p><p>Второй момент, иногда стоит как можно быстрее проверить пограничные случаи, например, нативную реализацию. Найти какой-то минимально приемлемый набор требований и достаточно быстро проверить его работоспособность, а не брать за основу какую-либо библиотеку. Это даст больше понимания, как эти библиотеки устроены внутри и почему работают или не работают те или иные функции. Иначе можно убежать довольно далеко в проекте и после понять, что что-то идет не так. И может оказаться так, что отказаться от библиотеки будет довольно затратно. Потребуется переписать значительную часть кода.</p><p>Третий момент, обязательно обращайте внимание на аудиторию вашего сервиса — с каких браузеров и операционных систем приходят ваши пользователи. Это довольно легко отследить с помощью различных метрик и систем мониторинга ошибок. Такой подход позволит понять какие платформы и браузеры поддерживать важно, а на поддержку каких можно не тратить силы.</p><h4>И напоследок</h4><p>Объявляю небольшой конкурс, связанный с воспроизведением музыки на iOS с использованием технологии HLS.</p><p>Описание можно увидеть по <a href="https://github.com/dipiash/m3u8-playlist-generator">ссылке на github</a>.</p><p><em>Originally published at </em><a href="https://habr.com/ru/post/438952/"><em>habr.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=742c02bea183" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>