AI 资讯
How Particle Effects Improve Game Feel in HTML5 Games
A game can be mechanically correct and still feel flat. The button works. The enemy loses health. The coin counter increases. The level completes. Everything technically functions, but the player's actions do not seem to have much weight. Particle effects are one of the cheapest ways to fix that. Not because every screen needs fireworks, but because particles give actions a visible consequence. Feedback Should Happen Immediately Imagine tapping an enemy in a mobile game. Version A: tap enemy HP decreases Version B: tap small flash impact particles enemy reacts HP decreases The underlying mechanic is almost identical. The second version communicates the result more clearly. The player sees exactly where the hit happened. That matters on mobile screens where fingers frequently cover part of the action. Particles Can Explain the Game VFX is not only decoration. It can communicate state. Damage Particles show where an impact happened. Healing A slow upward effect can visually separate healing from damage. Selection A subtle glow or ring can show which object is active. Currency Particles moving toward a counter connect the collected object with the UI value that changed. Cooldowns A burst or dissolve can show that an ability has become available. Danger Smoke, sparks, or unstable energy can communicate that an object is close to breaking. Good VFX helps the player understand the game without another label or tutorial popup. Timing Matters More Than Particle Count A common mistake is assuming better effects need more particles. They usually need better timing. Consider a button press. You could emit 100 particles over two seconds. Or you could emit 12 particles exactly when the interaction occurs. The second effect will often feel better because it reinforces the player's action. For responsive games, the sequence might look like this: 0 ms input 0 ms visual response begins 20 ms burst expands 80 ms largest particles appear 200 ms effect begins disappearing 350 ms effect
AI 资讯
The Evolution of Web Forms — Part 1
The Evolution of Web Forms Part-1 — From Plain HTML to AJAX Modern React forms can feel unnecessarily complicated when you first encounter tools such as React Hook Form, Zod, resolvers, controlled inputs, refs, formState , and server-error handling. Why do we need all of that? Why not simply read the value from an input and send it to the server? To understand why modern form libraries exist, we need to understand the problems developers faced before those libraries were created. In this series, we will evolve the same idea step by step: Plain HTML ↓ Native HTML validation ↓ JavaScript validation ↓ AJAX submission ↓ React controlled forms ↓ Form libraries ↓ React Hook Form ↓ React Hook Form + Zod ↓ Production form architecture This first part covers the first four stages: Plain HTML forms Native HTML validation Vanilla JavaScript validation AJAX form submission By the end, you will understand how forms worked before React and why each new approach became necessary. Stage 1: Plain HTML Forms Before React, AJAX, or even large amounts of client-side JavaScript, browsers already knew how to submit forms. HTML forms are not just visual containers. They are a built-in browser mechanism for collecting data and sending an HTTP request. A basic registration form <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" /> <meta name= "viewport" content= "width=device-width, initial-scale=1.0" /> <title> Registration Form </title> </head> <body> <h1> Create an account </h1> <form action= "/register" method= "POST" > <div> <label for= "username" > Username </label> <input id= "username" name= "username" type= "text" /> </div> <div> <label for= "email" > Email </label> <input id= "email" name= "email" type= "email" /> </div> <div> <label for= "password" > Password </label> <input id= "password" name= "password" type= "password" /> </div> <button type= "submit" > Register </button> </form> </body> </html> There is no JavaScript in this example. The browser handles the ent
AI 资讯
🚀 From FlipaClip to SitePoint: The Full Story of Kehinde Owolabi
🚀 From FlipaClip to SitePoint: The Full Story of Kehinde Owolabi How a Nigerian teenager built a professional game engine with borrowed laptops, offline W3Schools, and pure determination. 🎮 Play the Game Try Limn Engine Live — Space Shooter Demo See what 4 years of determination built. This space shooter runs at 60 FPS on a Tecno Pop 4 with 1GB RAM. 📖 Introduction Every developer has an origin story. Some start with a fancy computer and a computer science degree. Others start with a flipbook app and a sister who trusted them with her phone. My name is Kehinde Owolabi . I'm 18 years old (born December 4, 2007), and I live in Lagos, Nigeria. I'm currently in PC103 at BYU Pathway, and I'm a member of The Church of Jesus Christ of Latter-day Saints. I built a 94/100 professional game engine called Limn Engine. It runs at 60 FPS on a Toshiba with 4GB RAM. It was published on SitePoint and ranked #3 among 2D JavaScript game engines. Nobody knew it was developed on a Chromebook, a borrowed Thinkpad (behind my sister's back), and a Toshiba that "hung like hell." That was the secret I kept for months. But that's only one part of this story. This is the full story of how I went from a button phone to a 94/100 game engine, from FlipaClip to SitePoint, from a boy who failed physics to a developer who built something that runs on a Tecno Pop 4. The one-line summary: "I'm Kehinde Owolabi, an 18-year-old developer from Lagos, Nigeria who went from FlipaClip to building a 94/100 game engine on borrowed laptops — and got published on SitePoint." 🎮🚀 🎨 The Beginning: FlipaClip and the Spark of Creativity Before I was a developer, I was an animator. I used FlipaClip — a simple animation app on mobile — to create flipbook-style animations. I loved bringing characters to life, frame by frame. I would spend hours drawing, tweaking, and watching my creations move. That creative spark stayed with me. I wanted to create interactive experiences. I wanted to build games. But I didn't know how.
开发者
How to Extract Colors From an Image Using JavaScript and Canvas?
How to Extract Colors From an Image Using JavaScript and Canvas Have you ever looked at an image and wanted to know the exact HEX color of a particular pixel? Designers often need to extract colors from photographs, screenshots, logos, UI designs, and illustrations. You can do this directly in the browser without uploading the image to a server. The browser Canvas API gives us everything we need. Reading pixels with Canvas The basic process is: Load an image. Draw it onto a canvas. Read the pixel data. Convert the RGBA values into a color format such as HEX or RGB. The important API is getImageData() . javascript const imageData = ctx.getImageData(x, y, 1, 1); const pixel = imageData.data; const r = pixel[0]; const g = pixel[1]; const b = pixel[2]; const a = pixel[3];
AI 资讯
Enforcing a style rule with a linter that actually fails the build
Background I run a fleet of static sites that publish new content every day, mostly unattended. One of the house style rules is simple: no emoji anywhere in our own copy. That rule is impossible to hold by hand. A single site builds a few hundred HTML files, and emoji can slip into nav icons, button labels, <title> , the RSS feed, or JSON-LD (the JSON-formatted metadata embedded in a page to describe its structure to search engines). Nobody is going to review all of that before every deploy. So I wrote emoji-lint , a check that exits 1 the moment it finds a single emoji . It sits in the pre-deploy gate, which means a failure stops that day's publish. This post is not about the regex. It's about what happens when you put a failing check into real operation: you immediately discover the places where the rule must not apply. How it works The core is unremarkable. A regex holds the emoji code point ranges, the scanner walks each file line by line, and matching lines are reported as JSON. const EMOJI_RE = / [\u {1F000}- \u {1FAFF} \u {2600}- \u {27BF} \u {2B00}- \u {2BFF} \u {1F1E6}- \u {1F1FF} \u {FE0F} \u {200D} \u {2049} \u {203C} \u {2122} \u {2139} ] /u ; \u{FE0F} (variation selector) and \u{200D} (ZWJ) are in there because emoji are not always a single code point. Arrows and similar symbols used in ordinary technical writing are deliberately left out. Catch everything and the check drowns in false positives, at which point people stop reading it. The interesting part came later. Three categories of content look exactly like a violation but must not be treated as one: Verbatim quotes from other people Real proper nouns whose official spelling contains a symbol Passages where the emoji itself is the subject being explained Delete the emoji in any of those and you break something more important than the style rule. One term up front: "masking" here means replacing a range with spaces so the scanner cannot see it. Nothing is deleted from the file. Implementation Scope
AI 资讯
App-like UX in Next.js 16.3
Building App-like Experiences with Next.js 16.3 A hands-on look at how Next.js 16.3 helps apps feel fast and smooth, more like a single-page app, without losing the benefits of server rendering. Using four demo apps, it shows how features like Instant Navigations, Cache Components, Partial Prefetching, optimistic updates, Suspense streaming, offline retry, and View Transitions work together in real apps ⚡️ Sponsor: Arcjet AI compliance controls Protect your AI applications from prompt injection, PII leaks, and unauthorized tool calls. 📙 Articles / Tutorials / News Next.js team AMA The Next.js team opened the floor to community questions and covered a lot of ground. The AMA focused on Next.js 16.3, performance, caching, App Router, React Server Components, and upgrading apps, along with some insight into how the team works on the framework Coordinating Optimistic Updates in Next.js This guide shows how useActionState and useOptimistic can work together to keep the UI updated right away, save changes in the right order, and roll back cleanly if something fails Using next/root-params in Next.js 16.3 The new next/root-params API lets Server Components read top-level params like [locale] from deep in the tree, which makes next-intl much easier to use Docs for React's new browser() API The docs for React's new browser() API are now available in Canary. You can pass it to use() , where it suspends to the nearest Suspense boundary on the server, then renders normally in the browser 📦 Projects / Packages / Tools Better Auth 1.7 A big release for Better Auth, especially around OAuth, OpenID Connect, SCIM, SSO, MCP, and device login flows. The main theme here is stronger auth, better enterprise identity support, and more standards-based ways for apps and devices to sign in and get access Next 16 Calendar "Flow" A calendar and booking demo exploring Async React, Cache Components, Partial Prefetching, and View Transitions with Next.js 16.3, React 19, Tailwind CSS v4, and Prisma.
AI 资讯
Knowing When to Use If/Else vs. Switch in JavaScript
If/else statements - We all know and love them. While they are incredibly powerful, there comes a point where a long chain of conditions only makes your code look messy. Choosing between if/else and switch depends on readability, but there's a hidden pro tip that makes switch much more powerful than many people think at first. Traditional Approach: If/Else Normally, we use if/else when our logic depends on complex ranges and multiple variables: // Hard to scan, bulky, and prone to typos let weatherAdvice = "" ; if ( temperature < 15 && isRaining ) { weatherAdvice = " Grab a heavy coat and an umbrella! 🌧️🧥 " ; } else if ( temperature < 15 && ! isRaining ) { weatherAdvice = " It's cold but dry. Just a jacket is fine! 🧥 " ; } else if ( temperature >= 15 && isRaining && isNightTime ) { weatherAdvice = " Warm, rainy night. Stay indoors if you can! 🌧️🌃 " ; } else if ( temperature >= 15 && isRaining && ! isNightTime ) { weatherAdvice = " Warm rain during the day. Don't forget your umbrella! 🌧️🌦️ " ; } else if ( temperature >= 30 && ! isRaining ) { weatherAdvice = " It's scorching hot! Stay hydrated! ☀️🥤 " ; } else { weatherAdvice = " Weather seems pleasant today! 😎 " ; } Pro Tip: Using switch(true) Many developers think you can only use switch when you're checking a single variable against fixed values. However, you can use a switch statement for complex ranges by passing the boolean value true into the switch condition. Here is a cleaner switch statement version of the above code block: // Much easier on the eyes let weatherAdvice = "" ; switch ( true ) { case ( temperature < 15 && isRaining ): weatherAdvice = " Grab a heavy coat and an umbrella! 🌧️🧥 " ; break ; case ( temperature < 15 && ! isRaining ): weatherAdvice = " It's cold but dry. Just a jacket is fine! 🧥 " ; break ; case ( temperature >= 15 && isRaining && isNightTime ): weatherAdvice = " Warm, rainy night. Stay indoors if you can! 🌧️🌃 " ; break ; case ( temperature >= 15 && isRaining && ! isNightTime ): weather
AI 资讯
I turned browser cookie counts into game currency - meet Crumbongo
Crumbongo started from a pretty stupid little question: What if the number of accessible cookies on the website you're visiting could become game currency? So I built it. Crumbongo is a tiny local Chrome game where you choose a website, let the extension count the accessible cookie records for that site, and turn only that number into game rewards. No cookie names or values are used for gameplay. From a tiny experiment to an actual little game The first version was basically: choose a website; check its accessible cookie count; harvest that number into a Cookie Jar; spend the cookies on Bongo. Then I kept building on top of it. Crumbongo now has: a level and progression system; pixel-art cosmetics; multiple habitats; companions; local statistics; Monkey Climb; Cookie Stack. The whole thing still lives inside a Chrome extension popup. The technical side Crumbongo is deliberately small. There is no React, TypeScript, Vite, game engine, backend or framework involved. It's built with: vanilla JavaScript; HTML; CSS; Chrome Extension APIs; requestAnimationFrame for the minigames; chrome.storage.local for persistent game progress. The minigames are built with regular DOM elements and CSS rather than Canvas. That constraint became part of the fun: figuring out how far I could push a tiny extension popup without turning the project into something much larger. Local by design Because the core mechanic involves browser cookies, I wanted the privacy model to be extremely clear. Crumbongo requests access one site at a time. For gameplay it only uses the number of accessible cookie records returned for that site. It does not: store or transmit cookie names; store or transmit cookie values; modify or delete browser cookies; use an account system; use analytics or tracking; send gameplay data to a backend. Game progress stays locally in the browser. The game-design part became more interesting than I expected Once I added progression, I realized the cookie mechanic could support mu
开源项目
🔥 team-codebug / babua-dsa-patterns-course
GitHub热门项目 | | Stars: 864 | 9 stars today | 语言: JavaScript
开源项目
🔥 reisxd / TizenTube - A TizenBrew module to remove ads and add support for Sponsor
GitHub热门项目 | A TizenBrew module to remove ads and add support for SponsorBlock for your Tizen TV. | Stars: 2,002 | 10 stars today | 语言: JavaScript
AI 资讯
Making webpack's Docs Update Themselves | GSoC 2026, wrapped
Contributor: Nikhil Kumar Rajak ( @ryzrr ) Organization: webpack · Project: webpack-doc-kit Mentors: Aviv Keller ( @avivkeller ), Claudio Wunder ( @ovflowd ), Sebastian Beltran ( @bjohansebas ) Teammates: Mohamed Shams El-Deen ( @moshams272 ), Tushar Thakur ( @TusharThakur04 ) Period: 25 May to 17 August 2026 The problem webpack's docs lived at webpack.js.org and every API change meant somebody updating them by hand. Pages go stale and nobody notices until a reader does. webpack-doc-kit fixes that. It takes webpack's TypeScript declarations, runs them through TypeDoc, hands the output to nodejs/doc-kit for linking and UI, and produces a site that regenerates itself. We split the work three ways. Shams took AST parsing and content, Tushar took routing and navigation and UI, and I took the operational side: how docs get generated on a release, versioned & deployed. My six deliverables were PR-based doc sync, release-aware doc generation, versioned output folders, a deployment pipeline, CI validation before merge, and README fetch automation. All six shipped. Merged PRs in webpack-doc-kit 31 Lines added / removed +1,959 / −1,419 Distinct files touched 89 First / last merge 28 May ( #110 ) / 14 Aug ( #241 ) Merged PRs in other repos 2 Upstream issue filed and fixed 1 Everything below is merged into main . Nothing is open or pending. The release pipeline webpack releases happen in webpack/webpack . The docs live in webpack/webpack-doc-kit . A release in one needs to produce updated docs in the other with nobody doing anything. #110 set up versions.json as the single source of truth everything downstream reads, plus the script that maintains it and the workflow that runs it. My mentor proposed an object schema with latest , label , major , exactVersion , commit and frozen per entry. Review cut it to a flat array of tag strings, because everything else is derivable from the semver string and position [0] with unshift() already tells you which is latest. Right call, and I d
AI 资讯
Why Fixed-Window Rate Limiters Fail (And How to Fix Them with Math)
If you’ve ever built an Express API, you’ve probably reached for standard rate-limiting middleware to protect your login or payment endpoints from DDoS and brute-force attacks. Under the hood, most simple limiters use a Fixed-Window Counter . It’s easy to write: count incoming requests, and once the minute rolls over, reset the counter to zero. However, from a security and algorithmic standpoint, Fixed-Window counters have a massive blind spot. The Boundary Vulnerability (The 2-Second Spike) Imagine your endpoint allows a maximum of 100 requests per minute , resetting every full minute on the clock ( :00 ). Here is how an attacker bypasses that limit without breaking your rules: At 12:00:59 , the attacker fires 100 requests. (Allowed: 100/100 used). At 12:01:00 , the clock resets your counter back to 0. At 12:01:01 , the attacker fires another 100 requests. (Allowed: 100/100 used). To your server code, everything looks fine. But in reality, 200 requests slammed your backend within a 2-second window. In FinTech or authentication systems, that burst is more than enough to overwhelm payment gateways or run a successful credential-stuffing attack. The Algorithmic Fix: Sliding Window Counter To stop boundary spikes, we need a continuously sliding window rather than a rigid clock reset. Attempt 1: The Sliding Window Log (High Memory) You store a timestamps array (a Deque) for every user request and drop timestamps older than 60 seconds. While accurate, storing every single request timestamp takes $O(N)$ space. If your API receives millions of requests, your server memory dies instantly. Attempt 2: Sliding Window Counter (Optimal O(1) Math) Instead of keeping thousands of timestamps, we track only two integers : the request count of the previous window and the count of the current window . When a request arrives, we calculate an estimated request count by weighting the previous window based on how much time has passed in the current window: Estimated Requests = Current Cou
AI 资讯
Next step to client-side storage
Next step to client-side storage In my past one blog, I wrote about how I improve the performance of the application using the local storage. And the problem local storage solves. But now I face another problem about the client storage. My project is simply about order management software for the rental clothing industry. In the rental clothing industry, Showrooms or small shops have a big problem. The problem starts when one order has a single or multiple items that are booked in a particular time range. Now, a second order wants the same item in between that particular time range. If, by mistake, the second order books that item, then the problem starts. The item is booked two times in that particular time range. That is called double booking of the item. This mistake is created by the use of traditional register booking. Now, when I need to store the items data, that is a small amount of data, so I simply use the local storage. But now I need another and a big storage for storing order details. I build two features: first one is for showing all the orders and second one is for showing the full order. To implement those features and to maintain the user experience, I decide to store a small amount of data about the order on the client side. First, I decide to store data in local storage. But to store data in the local storage is not a good option because the local storage is used for storing small details about the application, and storing order details in the local storage compromises the performance of the application. Now I want a new storage option for storing order details. And again I find out, and that is the IndexedDB. To integrate IndexedDB in my application, I want to learn about that storage. I search multiple videos about IndexedDB, but no one is teaching me properly. After finding hundreds of tutorials, I finally found one tutorial that is teaching properly how to integrate IndexedDB in the application. Now I want to share that learning with you. To i
AI 资讯
I built a JSON toolkit that never sends your data anywhere
Most "paste your JSON here" tools online send that JSON to a server to process it. For internal API responses, config files, or anything with real data in it, that's not something I wanted to do — so I built JSONLinter , a JSON toolkit where literally everything happens client-side. What it does It started as a validator/formatter, then grew into 42 tools across six categories: Validate & Format — validation with precise error locations, pretty print, minify, JSON repair (fixes trailing commas, single quotes, unquoted keys, truncated JSON, etc.) View & Query — tree view, JSONPath queries, structural diff (key order doesn't matter), full-text search Data Converters — CSV, Excel, YAML, XML, SQL, Markdown, both directions Code Generators — infers a type model from a JSON sample and generates TypeScript, Python, Java, C#, Go, Kotlin, Swift, Rust, or PHP Schema Tools — JSON Schema validation + generation Encoding Tools — Base64, escape/unescape, JWT decode There's also an optional AI assistant on the validator page — it's bring-your-own-key (OpenAI or Anthropic), and since there's no backend at all, the key and your JSON go straight from your browser to the provider. I never see either. How it's built Stack is React 19 + TypeScript + Vite, Tailwind v4 for styling, CodeMirror 6 for the editor. A few things I had to solve that were more interesting than expected: Prerendering without SSR. I didn't want to take on a Next.js-style server just to get real HTML for crawlers. Instead, the build runs a headless Chromium pass (Playwright) over every route after vite build and saves the fully-rendered output to dist/<route>/index.html . Crawlers get real content and correct per-page meta tags on first paint; once JS loads, React takes over exactly like a normal SPA. No server, no hydration mismatches to worry about. Structural JSON diff. A text diff on two JSON documents is mostly useless because key order doesn't matter semantically. The diff tool parses both sides and compares t
开发者
Cómo solucionar el error \"Text content does not match server-rendered HTML\" en Next.js App Router
Cómo solucionar el error "Text content does not match server-rendered HTML" en Next.js App Router Este error ocurre cuando el HTML generado en el servidor (SSR/SSG) no coincide con el árbol de React que se construye durante la primera renderización en el navegador (hydration). Es un problema crítico de consistencia de estado que rompe la experiencia de usuario y puede causar comportamientos impredecibles. 🔍 Causa raíz (diagnóstico técnico) En tu caso, el error está relacionado con contenido dinámico que varía entre renderizado del servidor y renderizado del cliente , probablemente causado por: Uso de Date() , Math.random() , localStorage , window , o APIs del navegador directamente en el render . Uso de typeof window !== 'undefined' como condición de renderizado (no es idempotente entre SSR y CSR). Metaetiquetas de detección automática de iOS ( format-detection ) que inyectan nodos <a> en tiempo de ejecución. Extensiones del navegador (especialmente en desarrollo) que modifican el DOM. Librerías CSS-in-JS mal configuradas que inyectan clases o estilos dinámicos en CSR. ⚠️ Nota crítica : Next.js App Router no permite el uso de useEffect para evitar el mismatch en el primer render — el mismatch debe prevenirse , no suprimirse . ✅ Solución definitiva (pasos verificados) Paso 1: Elimina toda lógica no determinista del render NUNCA uses lo siguiente directamente en el cuerpo del componente: // ❌ Evitar const now = new Date (); // ❌ const isClient = typeof window !== ' undefined ' ; // ❌ const randomId = Math . random (); // ❌ const theme = localStorage . getItem ( ' theme ' ); // ❌ ✅ Reemplaza con: // ✅ Usar `useEffect` para *actualizar* el estado, no para *determinar* el render inicial import { useState , useEffect } from ' react ' ; export default function Component () { const [ time , setTime ] = useState < string > ( '' ); // Inicializa con valor seguro (ej. string vacío o placeholder) useEffect (() => { setTime ( new Date (). toISOString ()); }, []); return < time d
AI 资讯
Building a Live, User-Controlled Canvas Background System That Doesn't Kill Low-End Phones
The idea Most apps give you a static background. I wanted Pairly to feel alive instead, so I built "Atmosphere": a real-time animated Canvas layer that sits behind every chat, fully tunable by the user, speed, density, opacity, brightness, saturation, all live. There are currently over 40 atmospheres in the system, from calm ones like Snow and Fireflies to more elaborate ones like a black hole accretion disk called Abyss. The interesting part wasn't drawing pretty particles. It was making that work smoothly on a five-year-old Android phone without draining the battery in ten minutes. Two rendering paths, not one Atmosphere isn't a single renderer, it's a small internal package ( @pairly/atmospheres ) with two shared engines that every individual atmosphere builds on: ParticleCanvas , a generic particle system for anything made of many independent objects: snow, fireflies, sakura petals. useCanvasLoop , a raw draw-loop hook for continuous scenes that aren't particle-based, like Abyss's swirling accretion disk. Both engines centralize every "don't destroy the device" concern in one place, so individual atmospheres never have to think about it. Here's useCanvasLoop 's frame loop: const frameInterval = 1000 / perf . fps ; let raf = 0 ; let last = performance . now (); let acc = 0 ; const loop = ( now : number ) => { if ( ! running ) return ; raf = requestAnimationFrame ( loop ); const elapsed = now - last ; last = now ; acc += elapsed ; if ( acc < frameInterval ) return ; const dt = acc / 1000 ; acc = 0 ; draw ( ctx , width , height , elapsedTime , perf ); }; requestAnimationFrame fires at the display's native rate (often 90-120Hz on phones now), but that doesn't mean you should draw every single time it fires. This accumulator pattern throttles actual drawing down to the target FPS from the device's performance profile, instead of trusting rAF's raw rate. Profiling the device before drawing anything Before any atmosphere renders a single frame, it checks the device: ex
AI 资讯
I wrote the privacy rule, enforced it, commented it, and shipped the leak anyway
This is a submission for DEV's Summer Bug Smash : Smash Stories. TL;DR. I wrote a scrubbing policy before writing any instrumentation code. I enforced it in a beforeSend hook. I unit tested it. I wrote a comment above the one obviously sensitive line saying exactly what it must never do. Then I intercepted the actual bytes leaving the browser and found a stranger's shoulder injury in them. Every guarantee I had written was about data my code hands to the SDK. None of them were about data the SDK collects on its own. The setup WhyRep is a workout tracker built local-first. Training data is created and read on the device, the tracker works offline with no account, and that is not a marketing line, it is the architecture. It is also the thing people decide to trust or not trust in about four seconds on the landing page. So when I added Sentry, the scrubbing policy came before the code. Written down, in the repo, as a list of things that may never appear in an event: exercise names, weights, reps, RIR, session notes, chat content. Never. On Android I enforced it twice. A beforeSend hook that strips the forbidden fields, and a unit test that constructs an event carrying each one and asserts it comes out stripped. @Test fun `beforeSend strips every field the policy forbids` () { val event = SentryEvent (). apply { setExtra ( "exerciseName" , "Incline Barbell Bench" ) setExtra ( "weightKg" , 82.5 ) setExtra ( "notes" , "left shoulder clicks past parallel" ) } val scrubbed = ScrubbingPolicy . scrub ( event , Hint ()) assertNull ( scrubbed ?. getExtra ( "exerciseName" )) assertNull ( scrubbed ?. getExtra ( "weightKg" )) assertNull ( scrubbed ?. getExtra ( "notes" )) } Green. Good. Then I wired up the landing site's share-link page. It decodes whyrep.com/t#<payload> , where the payload is somebody's entire workout template, base64 in the URL fragment. I was careful there too. On a decode failure it reports a coarse reason tag and never the payload: // NEVER send the payload i
AI 资讯
Someone forked my React component instead of opening an issue
I maintain a small comic and manga viewer component for React called react-comic-viewer . The other day I was poking around npm and noticed something odd — there were three other packages with basically my package's name, published by other people. All three were forks of mine. Same description, same repository URL pointing back at my repo. None of the three authors had ever opened an issue or a pull request on my side. What the fork changed The oldest fork was made about three months after I first published, and it kept going for almost a year. Its version number ran ahead of mine at the time — I was on 0.3.5 while the fork was on 0.6.3. So I read the diff. Honestly, it was more useful than any issue would have been. The commit messages alone told the whole story: remove sass fix: support className props use Hotkeys and a new example file called controlled.tsx The sass one I'd already fixed. The className one I'd fixed too, about a year later. The controlled.tsx one I had never fixed. Not in four years. The part I never fixed Here's what their example looked like: < ComicViewer currentPage = { currentPage } isExpansion = { false } onTryMoveNextPage = { ( nextPage ) => { /* ... */ } } onChangedCurrentPage = { ( page ) => setCurrentPage ( page ) } pages = { pages } /> And here's what my component actually accepted: < ComicViewer initialCurrentPage = { 0 } initialIsExpansion = { false } onChangeCurrentPage = { ( page ) => { /* ... */ } } pages = { pages } /> The initial prefix is the whole problem. My component would take a starting page from you, and then never let you touch it again. It owned that state for the rest of its life. That's fine for a demo. It's pretty bad for anything real. You can't jump to a page from a table of contents. Syncing the current page with the URL doesn't work either. And if a chapter needs to be purchased first, there's no way to step in and stop the move. Every one of those needs the parent to be in charge, and the parent never was. Maki
开发者
Forms in React : From Inputs to Controlled Components
You have probably written HTML forms before, and so the structure below resonates with you. Perhaps you even smile because, this one, you understand. <form> <input type= "text" /> <button> Submit </button> </form> If you have done this, you know what happens when you click the button. The whole form reloads, the changes or inputs are cleared. This is the default behavior of forms in HTML. In React, we handle every step and every stage so that we have control over the data and the behavior of the form and data. The above signature represents what we call UNCONTROLLED INPUT . This means that there isn't a single source of truth to the value of this field, hence it can change to anything, and any value In addition to the above attributes, we will add value and onChange props to the input element as below: <input type= "text" value= {} onChange= {}/ > value represents the content of the input field e.g. the name text that the user enters in a Name field. onChange is the function that will be triggered everytime the input changes. Whenever a key is pressed within this field, this function will be invoked. Controlled inputs have their values set and manipulated by states, as we saw in Part 1 of the series. Uncontrolled inputs on the other hand do not have a manager that will dictate what goes into the field and when. Now let's write our first React Input, we'll keep it simple. import { useState } from " react " function Form (){ const [ name , setName ] = useState ( "" ) return ( < input type = " text " value = { name } onChange = {( event ) => setName ( event . target . value )} / > ) Let's look at what happens in the above. We have declared a state [name,setName] . name is the state variable setName is a function used to update the variable We then initialized an input element with properties value and onChange Note that, when the value of an input is set, that will always be the value even if you type something into the box. That is the essence of controlled input. The
开发者
Hello Everyone
Hello everyone, I am new to coding just begun to learn the ins and outs of coding and what it can do. I am in the process of getting my Full Stack Developer certificates. I have always wanted to do something that has to do with computers because I needed something to pass the time when I hurt myself playing football. I am looking forward to chatting with all of you about the struggles you had and what you found that you liked within the development realm.