今日已更新 420 条资讯 | 累计 20392 条内容
关于我们

标签:#webdev

找到 1530 篇相关文章

开发者

Context vs Prop Drilling: I Put the Re-render Blast Radius Side by Side

"Prop drilling is bad, use Context" is repeated everywhere — but the actual cost stays abstract. So I put the two approaches side by side with live render counters. Click one button and the difference is impossible to miss. ▶ Live demo: https://context-vs-props-drilling.vercel.app/ Source (React 19 + TS): https://github.com/dev48v/context-vs-props-drilling Two identical 4-level trees, both React.memo 'd. One threads a value down as a prop through every level; the other provides it once via Context and reads it only at the leaf. Change the value: Prop drilling → 4 components re-render. Every component on the path receives the changed prop, so all of them re-render — and each intermediate is cluttered with a value it does nothing with except pass along. Context → 1 component re-renders. The intermediates take no value prop, so they're skipped (memoized, props unchanged). Only the consumer leaf re-renders. The summary tallies it on every click: 4 vs 1 . Why Context skips the middle This is the part that surprises people: with Context, an intermediate component can be skipped even though a descendant re-renders . < ThemeCtx . Provider value = { val } > < A /> { /* memo, no props → skipped on value change */ } </ ThemeCtx . Provider > const A = memo (() => < B />); // skipped const B = memo (() => < C />); // skipped const C = memo (() => < Leaf />); // skipped const Leaf = () => { const value = useContext ( ThemeCtx ); // ← re-renders on context change return < div > { value } </ div >; }; React re-renders context consumers directly when the provider value changes — it doesn't need to re-render the components in between. With prop drilling there's no such shortcut: the only way the value reaches the leaf is through every parent, so every parent must re-render. The catch — Context isn't a free lunch Context isn't a "no re-renders" button. Every consumer re-renders whenever the provider value changes — there's no built-in selective subscription. One big, chatty context ca

2026-06-29 原文 →
AI 资讯

Can retrieval agents like ChatGPT and Perplexity read your website? Agentis Lux sees what they see.

I created Agentis Lux for the purposes of entering H0 Hackathon (Vercel + AWS Databases). #H0Hackathon See Agentis Lux's Devpost.com entry . It started with a comment at a hackathon. A you.com employee said the thing out loud: the web has a second audience now. When you ask ChatGPT or Perplexity a question, a retrieval agent fetches a page and reads its HTML to answer you. Not the laid-out site with the buttons and the hero image. The markup underneath. These agents arrive by the million, and many of them rely on the raw or minimally rendered HTML rather than running your JavaScript, so they often see far less of your page than a person does. That comment sent me to build. My first answer to it was Hermes Clew , for the GitLab Duo Agent Platform Challenge. Hermes lived inside GitLab Duo Chat, no frontend, no database: a Python engine that scanned the HTML, JSX, and TSX files in a repo, scored them across six categories, and let an LLM reason over the findings. It proved the core idea. It also told developers how to fix things, lived inside one vendor's chat, and only worked on files in a repo. Agentis Lux is what happened when I took that idea to the open web and rebuilt it with a different stance. Any live URL, not just repo files. Its own product on a real cloud architecture, not a chat window. And no fix suggestions, on purpose, where Hermes used to hand them out. Same six-category bones, a new body, a sharper philosophy. It scans your site and shows you what that second audience experiences when it tries to read it. What it does You paste a URL to Agentis Lux . You get a report. The report is written from the agent's point of view. Not "this is broken." More like: "an agent landing on this page can't tell which element starts checkout, because it's a styled div and not a button." It reports findings. It does not suggest fixes, and that is on purpose. I know what the agent sees, not what you should change. That is the whole value: visibility, and you decide what

2026-06-29 原文 →
AI 资讯

How to fix the "Purple Potassium" Chrome Web Store rejection (and catch it before you submit)

You submitted your extension, waited days for review, and got back a rejection with a violation called "Purple Potassium." Your extension looks fine to you, so what does it even mean? Here is what it is, why it happens, and how to catch it before you ever hit submit. What "Purple Potassium" actually means "Purple Potassium" is Google's internal tag for excessive or unused permissions . Your manifest requests access to something your code does not actually use, and the reviewer flags it. It is one of the most common reasons a Chrome extension gets rejected, and it is frustrating precisely because the extension works fine in testing. Review is checking something testing never does: whether every permission you ask for is justified by your code. The usual causes 1. API permissions you declared but never call. You added tabs , bookmarks , or cookies to your manifest at some point, but there is no chrome.bookmarks.* call anywhere in your code. 2. Host access that is too broad. You requested <all_urls> when your extension only touches one site: // Flagged "host_permissions" : [ "<all_urls>" ] // Better "host_permissions" : [ "https://*.example.com/*" ] Leftover permissions after removing a feature. You shipped a feature that needed downloads, later removed the feature, and forgot to remove the permission. The tabs misunderstanding. The tabs permission does not grant access to the tabs API. Basic methods like chrome.tabs.create() work without it. It only grants four sensitive Tab properties: url, pendingUrl, title, and favIconUrl. If you declare tabs but never read those, it counts as unused. How to fix it by hand List everything in permissions, optional_permissions, and host_permissions. For each one, search your code for the matching chrome. call. Remove any permission with no usage. Narrow and other broad patterns to the specific hosts you need. In your reviewer notes, write one plain sentence per sensitive permission explaining why you need it. Reviewers often lack con

2026-06-29 原文 →
AI 资讯

How I Built a Real-Time Whale Tracker for Polymarket in a Weekend

Prediction markets just hit $3.6B in volume. I wanted to know what the biggest traders were betting on — in real time. So I built WhaleTrack. Here's how it works under the hood. The Problem Polymarket has a public leaderboard. But it only shows P&L totals — not what whales are currently betting on, not their recent activity, not their win rate. If you want to follow smart money, you're flying blind. I wanted something that answered: what are the top traders doing right now? The Stack Vanilla JS frontend (no framework, keeps it fast) Vercel serverless function as a backend proxy (avoids CORS issues) Polymarket's public data API — no auth required Step 1: Finding the Whales Polymarket exposes a leaderboard endpoint: https://data-api.polymarket.com/v1/leaderboard?limit=20 This returns traders ranked by P&L. I pull the top 10, grab their wallet addresses, and that's my whale list. Step 2: Fetching Live Activity For each whale wallet, I hit: https://data-api.polymarket.com/activity?user={address}&limit=20 This returns their recent trades — market name, size in USDC, timestamp. Refreshes every 60 seconds. Step 3: Calculating Win Rate (the tricky part) The key is the redeemable flag — redeemable: true means they won, currentValue: 0 + redeemable: false means they lost. Took a few wrong attempts with cashPnl (always negative, not useful). Step 4: The Whale Alert Banner Every 60 seconds I check for trades over $5,000 placed in the last 10 minutes. When it fires, a green banner slides down with the whale name, market, and amount. Auto-dismisses after 12 seconds. First time I saw it fire live with a $28K bet — genuinely exciting. Results 129+ users in the first few days Zero ad spend Traffic from Twitter, Reddit, Quora What's Next More whale wallets (suggestions welcome) Click-through to open the same market on Polymarket directly Email/push alerts for big trades Check it out: whaletrack.app All feedback welcome — especially if you spot a whale I'm missing.

2026-06-29 原文 →
AI 资讯

How I Built an AI Exam App in 8 Months to outsource studying

Eight months ago, a CS exam forced me to write pseudocode when I already knew how to code. Instead of studying, I rage-built an app. Today examintelligence.app is live. Here’s exactly how I got here—from vibe-coded POCs to a production hybrid AI pipeline—without the curated startup gloss. The Philosophy Behind the Build I’ve always believed studying for marks ≠ actually learning. When I was first introduced to organic chemistry, I hated it. Then I ran into GNNs in Machine Learning with PyTorch and Scikit-Learn , paired with the MoleculeNet dataset. Suddenly, everything clicked. I wanted to learn everything about it. That’s the core problem: exams optimize for pattern recognition, not curiosity. You’re forced down one prescribed path, and it rm -rf s the fun of learning in most cases. So one week before my first prelims, I decided to build exam intelligence. The plan was simple: introduce brutal efficiency using AI for what it’s actually built for: pattern recognition Parse every past paper, mark scheme, and examiner report. Distill it down to precisely what matters. Free up time for coding and creative work. Vibe-Coding the POC (and Why It Collapsed) I’m generally against vibe-coding. It’s unreliable, hard to maintain, and a security nightmare. But with prelims staring me in the face, I had no choice. I opened Claude and vibe-coded it module by module. The only code review I had time for was checking for suspicious os.system or subprocess calls. That was it. I shipped anyway. Initial stack: Gemini API (no agent frameworks, no LangGraph) Streamlit frontend PostgreSQL It validated my idea but functionally, it barely held together. After prelims, I finally looked at what the AI had actually built: Dashboard showing random stats Asked Gemini for a JSON response with 5 keys, saved only 2 Randomly created DB tables while trying to read subjects The kind of code you end up with when you let an AI cook unsupervised for a week. So I did the only reasonable thing: opened Neov

2026-06-28 原文 →
AI 资讯

AgentJr — The AI Junior Developer That Manages Your Entire Freelance Business While You Sleep

AgentJr — The AI Junior Developer That Manages Your Entire Freelance Business While You Sleep Most "AI developer tools" do one thing: write code. AgentJr does everything a real junior developer does. Code. Clients. Communication. Deployment. Testing. Invoices. Social media. All of it. Automatically. While you sleep. The Real Problem With AI Coding Tools Today Claude Code writes code. Devin writes code. Copilot writes code. But writing code is maybe 40% of what a freelance developer actually does. The other 60%? Talking to clients. Understanding what they actually want. Managing git properly. Branches, commits, PRs. Running tests. Catching bugs before the client sees them. Deploying to the right environment. Not accidentally pushing dev code to production. Sending updates. "Hey, your feature is live." Tracking costs. How much did this project actually cost me in API calls? Following up. Drafting invoices. Scheduling calls. Posting on LinkedIn about the work you just shipped. No AI tool today handles all of that together. They give you a coding assistant and leave the rest to you. AgentJr is different. AgentJr is not a coding assistant. It's a complete AI junior developer that manages your entire workflow — from the moment a client messages you, to the moment the project is deployed, tested, and the invoice is sent. You Are the CEO. AgentJr Is the Manager. Here's the architecture that makes AgentJr unique: You — give direction. Set priorities. Approve plans. That's it. AgentJr (Manager) — understands requirements, asks smart questions, builds plans, manages git, monitors work, handles client communication, runs tests, manages deployments, tracks costs, drafts invoices, posts social media updates. Claude Code / Codex / Gemini CLI (Worker) — writes the actual code. Spawned by AgentJr on your terminal. Per project. You choose which one. AgentJr never writes code itself. It orchestrates the worker that does. This separation is intentional — and it's what makes the whole s

2026-06-28 原文 →
AI 资讯

How I Built GitPulse: A Cinematic Developer Storyteller (and why standard GitHub profiles are boring)

Let's be honest — standard GitHub profiles are a bit... static. As a Full Stack Developer & AI/ML Specialist, I wanted a way to showcase my contributions that actually felt alive. I didn't just want a grid of green squares; I wanted a universe. So, I built GitPulse. What is GitPulse? GitPulse is a cinematic, interactive web application that transforms standard GitHub profiles and repository logs into glowing, animated contribution universes. Instead of just seeing numbers, you experience your code history visually. The Tech Stack I wanted this to feel premium, fast, and visually stunning without relying on heavy frontend frameworks if I didn't need to. Canvas API & GSAP: For buttery-smooth micro-animations and physics. Glassmorphism UI: Using CSS backdrop-filters to create a modern, deep aesthetic. Vanilla JavaScript: Keeping the core logic incredibly fast and lightweight. The "Stellar Duel" Feature One of the coolest features I added was the Stellar Duel mode. I thought: What if you could compare your GitHub activity with a friend, but instead of a boring chart, it looked like a sci-fi dashboard? Stellar Duel Using the GitHub API, GitPulse fetches the data and renders a live, side-by-side visual duel of your commit history, stars, and PRs. It’s highly interactive and honestly, just really fun to look at. The Biggest Challenge: Performance Rendering thousands of data points (commits) visually on a canvas can crash a browser if you aren't careful. To solve this, I had to heavily optimize the animation loop. Instead of manipulating the DOM for every star/commit node, I used HTML5 Canvas to batch render the visual elements. I also implemented requestAnimationFrame properly to ensure the animations pause when the user switches tabs, saving CPU cycles. See it in Action I've integrated GitPulse directly into my main portfolio. You can try it live here: GitPulse Live Demo And if you want to see more of the projects I build (especially in the AI/ML and Computer Vision space

2026-06-28 原文 →
开发者

I built a free UAE calculator platform that runs on live government data

Living in the UAE means constantly Googling numbers: what is the visa fee now, how much zakat do I owe, what is today's fuel price, how is my gratuity calculated. The answers online are usually outdated. So I built Adad , a free set of 15 calculators that pull from official UAE government sources and refresh every 24 hours. No sign-up, works in 8 languages. A few that people use most: Visa fees: real GDRFA and ICA rates Zakat: gold, silver, savings DEWA bills: estimate before the bill lands Gratuity: UAE labour-law end-of-service It is at adad.ae if it is useful to you. Happy to answer how the data pipeline stays current.

2026-06-28 原文 →
AI 资讯

Your console.log Is Lying to You

Open your browser DevTools and run this: const user = { name : " Bob " } console . log ( user ) user . name = " Alice " You would expect the log to show { name: "Bob" } , the value at the time of the console.log call. The collapsed line is what you expect: ▶ Object { name: "Bob" } But expand it, and you will see: name: "Alice" Oops. So what's going on? console.log() is the most-used debugging tool in JavaScript, but it can be subtly unreliable. Not because it is broken, but because it optimizes for speed and interactivity rather than for accuracy . It was built for fast exploration in a live, interactive environment, and those priorities come with tradeoffs that can genuinely mislead you during debugging. Over the next sections, we'll look at a few ways the console can mislead you - and, more importantly, why each one exists. Objects Aren't Snapshots When you pass an object to console.log() in browser DevTools, the browser does not immediately serialize it into a string. Instead, it stores a live reference to that object and defers the actual rendering until you expand the entry. This is called lazy evaluation, and it is what caused the surprise. The collapsed ▶ Object you see is essentially a placeholder: the properties shown inside it are evaluated at the moment you click the arrow, not at the moment you called console.log() . By then, your code has already continued running. That means what you're seeing is not a frozen record of the object at the time of logging, but a live view into whatever the object happens to look like when DevTools renders it. In the example: You log { name: "Bob" } DevTools stores a reference to the user object The code continues executing user.name is mutated to "Alice" You expand the logged object later and see the current state This behavior can feel unintuitive at first, because most developers mentally model console.log() as "print this value right now", but in browser DevTools, it is closer to "show me this object as it exists when

2026-06-28 原文 →
AI 资讯

From Regex Hell to AI: How I Finally Tamed Messy PDF Invoices

Last month, I spent three days wrestling with 500 PDF invoices. Each one had the same data—vendor name, invoice number, total amount—but the layouts were all over the place. Different fonts, missing headers, tables that somehow broke across pages. I tried regex. I tried OCR with layout analysis. I even tried building a rule-based parser that looked for keywords like "Total:" . Nothing worked reliably. Every time I fixed one pattern, another invoice broke. I was one commit away from throwing my laptop out the window. Then I took a step back. I realized I didn't need to understand every layout variation. I just needed to understand the data . And that's where AI came in. What didn’t work Let me be clear: I tried the usual suspects first. Regex. Classic. I wrote patterns like r"Total\s*:\s*\$?(\d+\.\d{2})" . Worked on 60% of invoices. The rest had "Total Due" or "Amount Total" or the dollar sign in a different place. Regex is great when you control the input. I didn't. OCR with layout parsing. I used Tesseract with --psm 6 and tried to extract lines by bounding boxes. It helped a bit, but tables with merged cells or rotated text threw it off. Plus, I had to write code to guess which box was a field name and which was a value. Rule-based parser. I built a dictionary of known vendors and their layouts. That worked … until I got an invoice from a new vendor. Maintenance became a nightmare. I was solving the wrong problem. Instead of fighting formatting, I needed to focus on meaning . The AI approach that saved me I remembered that large language models are surprisingly good at understanding context. If I could give the model the raw text from a PDF and a description of what I wanted, maybe it could extract the fields directly. Here’s the core idea: treat extraction as a structured generation task. Provide a prompt with a few examples (few-shot) or just describe the schema, and let the model output JSON. I found an API that did exactly this with a simple HTTP call. (Full d

2026-06-28 原文 →
开发者

สามภาษา — หนึ่งเดียว | โคลงสี่สุภาพแห่ง HTML, CSS, JavaScript

— โคลงสี่สุภาพ ว่าด้วยสามภาษาแห่งการสร้างเว็บ — HTML — โครงสร้าง <html> เปิดทางฟ้า ประกาศ <head> ซ่อนนัยน์นาถ นามนี้ <body> ร่างกายปราศ ซึ่งชีวิต ทุกแท็กเปิดปิดที่ หล่อหล่อมความจริง CSS — ความงาม สีสันลอยลิบฟ้า แต่งแต้ม ตัวอักษรเรียงแถม ถ้วนถี่ ขอบเขตเว้นระยะแย้ม เผยโฉม ทุกพิกเซลที่ปรี่ ปรุงแต่งให้งาม JavaScript — ชีวิต เมื่อคลิกนิ้วหนึ่งครั้ง โลดแล่น ฟังก์ชันทำงานแย้ม ยามใช้ if else ตรรกะแจ่ม จักรกล ทุกบรรทัดที่ให้ ชีวิตแก่หน้าเว็บ สามภาษา — หนึ่งเดียว html คือร่างให้ โครงครัน css แต่งแต้มฝัน สวยหรู javascript พลิกผัน ให้เคลื่อนไหว สามภาษาคู่ฟู ฟื้นฟูโลกา — Nokka | มิถุนายน 2569 เชิงอรรถ: โคลงสี่สุภาพบทนี้ใช้ฉันทลักษณ์มาตรฐาน — บทละ 4 บาท บาทละ 2 วรรค วรรคหน้า 5 พยางค์ วรรคหลัง 2 พยางค์ สัมผัสบังคับระหว่างวรรคท้ายของบาทที่ 1, 2, 3 กับวรรคแรกของบาทถัดไป เนื้อหากล่าวถึงสามเทคโนโลยีหลักของการพัฒนาเว็บไซต์ในฐานะ "กาย — ใจ — วิญญาณ" ของทุกหน้าเว็บ

2026-06-28 原文 →
AI 资讯

"Building an HSK Speaking Test AI: Real-time Tone Grading with Gemini

Building an HSK Speaking Test AI: Real-time Tone Grading with Gemini I built a free Mandarin speaking assessment tool that grades tone + grammar in real time. Here's the engineering behind it. The Problem HSK (Chinese proficiency test) has a speaking component (HSKK), but most learners can't self-assess their level. Online tutors are expensive. Generic AI conversation tools don't grade tones. So I built ToneTutor: a 3-minute spoken-HSK test that estimates your speaking level and identifies weak points. The Tech Stack Frontend: Web Audio API (record user voice → PCM → LINEAR16) React + TypeScript (real-time transcript display) Backend: FastAPI (Python) on Google Cloud Run Gemini 2.5 Flash (real-time conversation + transcript grading) Firestore (user sessions + results) The Challenge: Web Audio API records as WebM. Gemini expects LINEAR16 (WAV). iOS Safari doesn't support WebM. So: Transcode WebM → PCM in browser (Web Audio context) Send raw PCM bytes to backend Backend wraps PCM in WAV header → sends to Gemini Speech-to-Text Gemini analyzes transcript + provides HSK level estimate The Grading Loop python async def grade_session(transcript: str): prompt = """ Rate this Mandarin response on HSK 1-6 scale. Assess: tone accuracy, grammar, vocabulary range. Provide: level estimate + weak points. """ response = await gemini.generate_content(prompt, stream=True) return parse_hsk_level(response) Results - 3-min test - Real-time feedback - Shareable HSK score card - Free (limited sessions) Open source coming soon. Built because I'm a native speaker + voice actor frustrated with generic tools. Try it: tonetutor.tefusiang.com (free for 3 sessions) Curious about the speech-to-text pipeline or tone grading logic? Ask below.

2026-06-28 原文 →
AI 资讯

I built a free planting calendar with 365 daily pages using AI

Ever planted seeds at the wrong time and watched them die? Me too. That's why I built PlantingCalendar.net - a free tool that tells you exactly what to plant every single day based on your climate zone. Built with AI coding tools in about 4 hours. 365 pages, each with unique planting instructions. Static site on Cloudflare Pages, zero server cost. Free, no sign-up.

2026-06-28 原文 →
AI 资讯

Stop trusting environment variables in your TypeScript apps

Environment variables look simple until one of them is missing, empty, malformed, or interpreted in a way your application did not expect. In TypeScript projects, this can be easy to overlook. The code may be typed, the build may pass, and the app may still ship with broken configuration. This is especially common in frontend builds, server-side rendering, backend services, CLI tools, Docker images, and CI/CD pipelines, where configuration is injected from outside the codebase. That is the problem valitype is designed to address: strict, type-safe validation of environment variables with zero dependencies. The problem with environment variables Environment variables are always external input. They can come from: .env files CI/CD variables Docker or container platforms hosting providers build scripts deployment environments TypeScript can describe what your code expects, but it cannot guarantee that the environment actually contains valid values. This looks harmless: const apiUrl = import . meta . env . VITE_API_URL const debug = Boolean ( import . meta . env . VITE_DEBUG ) const port = Number ( process . env . PORT ) But simple casting can hide invalid configuration: Boolean ( ' false ' ) // true Boolean ( ' 0 ' ) // true Number ( ' 0xff ' ) // 255 Number ( ' 1e5 ' ) // 100000 Number ( '' ) // 0 For application configuration, “parseable” is not the same as “valid”. Invalid configuration should be caught before deployment, either during build, CI, server startup, or a dedicated validation step. The problem in React and frontend builds React applications usually do not read environment variables directly at runtime in the browser. Instead, tools like Vite and frameworks like Next.js inject selected values during build time. That makes validation important. Once the frontend bundle is built and deployed, changing a bad environment variable usually means rebuilding and redeploying the application. For frontend apps, validation should answer a few basic questions before

2026-06-28 原文 →
开发者

How to Send iMessages Programmatically (REST API, Python & Node.js)

If you've ever tried to send an iMessage programmatically , you've probably hit the same wall everyone does: Apple has no public iMessage API. There's no POST /imessage in the developer docs, no SDK, no OAuth scope. Yet "blue bubble" delivery has 3–4× the open rates of SMS, so the demand to send iMessages from code — for CRMs, bots, notifications, and outbound — keeps growing. This guide covers the realistic options, then walks through actually sending and receiving iMessages over a REST API with working Python , Node.js , and curl examples you can paste and run today. Why there's no official iMessage API iMessage is a closed, end-to-end-encrypted protocol tied to Apple IDs and Apple hardware. Apple has never shipped a public API to send iMessages, and "Messages for Business" is a support-inbox product gated behind an approval process — not a way to send outbound messages from a script. So historically, developers reached for hacks: Approach Works from a server? Reliability Receiving messages Notes AppleScript / osascript No — needs a logged-in Mac with Messages open Brittle Polling the local SQLite chat.db Mac-only, breaks on macOS updates Shortcuts automation No Brittle No Manual, not built for scale "Just use SMS" (Twilio etc.) Yes High Yes Green bubbles, no typing indicators/tapbacks/HD media Hosted iMessage REST API Yes High Yes (webhooks) What this guide uses The AppleScript route is fine for a one-off script on your own Mac. The moment you want to send from a server, send at scale, or receive replies reliably, you need a hosted API that manages the Apple side for you and exposes a normal HTTP interface. The setup For the examples below I'm using Blooio , an iMessage REST API. Any provider with a similar HTTP surface will follow the same patterns — the concepts (Bearer auth, a send endpoint, webhooks for inbound) are what matter. You'll need: An API key (Blooio gives you one in the dashboard — no credit card, no A2P/10DLC registration, no DUNS number) A phone

2026-06-28 原文 →
开发者

【互動藝術 DIY】用 p5.js 做一塊會呼吸的粒子背景(無程式背景可)

【互動藝術 DIY】用 p5.js 做一塊會呼吸的粒子背景 先問自己:阿哲會想動手嗎? 看完這個效果,阿哲可能會想: 「那如果我把粒子排成自己的名字,滑鼠靠近時會散開嗎?」 這就是正確的方向—— 讓讀者想自己動手改參數 ,而不是背程式碼。 這個方法厲害在哪? p5.js 官網有很多炫技的粒子效果,但大部分只是給你看「很厲害」。 這次不一樣——我要教你 用最少程式碼,做出最有呼吸感的互動 。 秘密是:用「距離」控制行為,用「lerp」讓移動變溫柔。 教學順序 先建立粒子:讓一群點組成畫面 教動畫:用 sin() 做出呼吸節奏 教距離感:用 dist() 偵測滑鼠 教溫柔散開:用 lerp() 柔和移動,不是瞬移 最後加美感:透明度、殘影、暖色 第一步:讓粒子回家 class Particle { constructor ( x , y ) { this . homeX = x ; // 記住家的位置 this . homeY = y ; this . x = x ; this . y = y ; } // 讓粒子回家的力量 returnHome () { this . x = lerp ( this . x , this . homeX , 0.05 ); // 每次移動5%的距離 this . y = lerp ( this . y , this . homeY , 0.05 ); } show () { noStroke (); fill ( 255 , 180 , 120 , 200 ); // 暖橙色 ellipse ( this . x , this . y , 4 ); } } 第二步:偵測滑鼠距離 function draw () { for ( let p of particles ) { let d = dist ( mouseX , mouseY , p . x , p . y ); if ( d < 100 ) { // 滑鼠靠近時,輕輕推開 let force = 0.05 * ( 100 - d ) / 100 ; p . x += ( p . x - mouseX ) / d * force ; p . y += ( p . y - mouseY ) / d * force ; } p . returnHome (); p . show (); } } 第三步:加呼吸節奏 let breathPhase = 0 ; function draw () { breathPhase += 0.02 ; let breath = sin ( breathPhase ); // -1 ~ +1 來回循環 background ( 10 , 8 , 5 ); // 暖暗色背景 for ( let p of particles ) { let d = dist ( mouseX , mouseY , p . x , p . y ); if ( d < 100 ) { let force = 0.05 * ( 100 - d ) / 100 ; p . x += ( p . x - mouseX ) / d * force ; p . y += ( p . y - mouseY ) / d * force ; } p . returnHome (); p . show ( breath ); // 把呼吸相位傳進去 } } function show ( breath ) { noStroke (); // 呼吸時變亮,吐氣時變暗 let alpha = map ( breath , - 1 , 1 , 150 , 255 ); fill ( 255 , 180 , 120 , alpha ); ellipse ( this . x , this . y , 4 ); } 第四步:殘影效果 function draw () { // 不要每幀清掉背景,而是蓋一層半透明黑色 fill ( 10 , 8 , 5 , 30 ); rect ( 0 , 0 , width , height ); // ... 其餘粒子邏輯 } 這樣粒子移動時會留下淡淡的光跡——很有沉浸式裝置的 feel。 阿哲可以怎麼玩? 參數 預設值 改成... 效果 感知半徑 100px 50px 只有非常靠近才有反應 回家速度 0.05 0.02 超級慢,像在水裡 回家速度 0.05 0.2 快一點回覆 粒子數量 200 50 稀疏的星塵感 粒子颜色 暖橙 淡粉 更柔和的感覺 延伸練習 把粒子排成自己的名字 :讓粒子組成「阿哲」或英文字母輪廓,滑鼠靠近時文字散開,離開後慢慢聚回來。 滑鼠不是破壞者,是一陣風 :不只是排斥,而是讓粒子沿著滑鼠移動方向飄

2026-06-28 原文 →
AI 资讯

I switched 23 sites from JPEG to WebP/AVIF last month — here's what I learned

I spent last month migrating 23 client sites from JPEG/PNG to WebP and AVIF. Here's what I wish someone told me before I started. AVIF vs WebP: the real numbers AVIF is about 30% smaller than WebP at the same quality level. But Safari support is still patchy — if your traffic is 40%+ iOS, you need <picture> tags with WebP fallback. No way around it. The biggest win wasn't the format The single biggest reduction came from capping max image width at 1200px and setting quality to 80. One site went from 9.4MB to 318KB per page — a 97% reduction — just from those two settings plus lazy loading. The format switch was the cherry on top, not the cake. Tools I used daily SmartImgKit — quick batch conversions in the browser. No uploads, no signup, drag and drop. Handles the 80% case where you don't need a CLI pipeline. Supports JPG, PNG, WebP, AVIF, GIF, BMP, TIFF. ImageMagick — server-side batch jobs for when you need automation. Squoosh — one-off fine-tuning with visual comparison. Sharp (Node.js) — build pipeline integration. The HEIC surprise Every iPhone user's photos are HEIC. Most web tools crash on them. You need a converter that handles them before the pipeline — SmartImgKit's HEIC converter works locally in-browser, no uploads. The 80/20 rule Format + max width + lazy loading = 80% of the gain. Everything else is diminishing returns. Don't over-engineer it.

2026-06-28 原文 →
开发者

I Built a Unit Converter in Pure Vanilla JS — 7 Categories, 70+ Units, 165 Tests, Zero Dependencies

Unit converters are everywhere online, but they all seem to either require an account, run ads that cover half the screen, or send your input to a server for no reason. I built one that runs entirely in your browser, with no dependencies, no tracking, and no round-trips. 👉 https://unit-converter-dev.pages.dev What It Does Seven conversion categories, 70+ units, real-time bidirectional conversion: Category Example units Length mm, cm, m, km, in, ft, yd, mi, nmi, light-year Weight mg, g, kg, t, oz, lb, st, short ton Temperature °C, °F, K, °R Volume ml, l, m³, fl oz, cup, pint, quart, gallon, tbsp, tsp Area mm², cm², m², km², ha, acre, ft², in², mi², yd² Speed m/s, km/h, mph, ft/s, knot, Mach Data bit, byte, KB/KiB, MB/MiB, GB/GiB, TB — both SI and binary Features: Bidirectional — type in either field, the other updates instantly Swap button — flip from/to with one click All-units panel — see your input converted to every unit in the category simultaneously Formula display — shows the conversion factor (e.g. "1 Mile = 1.609344 Kilometer") Zero dependencies — single HTML file, no build step, no npm Implementation Notes Linear vs. non-linear conversions Most unit conversions are linear: multiply by a factor to get to the base unit, divide by another factor to get to the target. The approach: function convert ( catKey , fromUnit , toUnit , value ) { const base = toBase ( catKey , fromUnit , value ); // → base unit return fromBase ( catKey , toUnit , base ); // base unit → target } function toBase ( catKey , unit , value ) { const u = CATEGORIES [ catKey ]. units [ unit ]; if ( u . toBase ) return u . toBase ( value ); // non-linear (temperature) return value * u . factor ; } Temperature is the classic non-linear case. You can't just multiply to convert between Celsius, Fahrenheit, and Kelvin — you need offset arithmetic: temperature : { units : { C : { toBase : v => v + 273.15 , // °C → K fromBase : v => v - 273.15 , // K → °C }, F : { toBase : v => ( v - 32 ) * 5 / 9 + 2

2026-06-28 原文 →
AI 资讯

Perl PAGI Middleware

Middleware in PAGI A port of the sample app from What Is Middleware? — which builds the same three-layer stack in Plack/PSGI (Perl) and Starlette/ASGI (Python) — to PAGI , an async, ASGI-style application interface for Perl. The app is deliberately tiny but exercises the three things middleware exists to do: Logger — wrap the request, time it, log method/path in and status/duration out. Authenticator — inspect a header, inject context for downstream layers on success, or short-circuit with a 401 on failure. ProfileRouter — answer one specific route from inside the stack, reading the context the Authenticator injected. All code below was run under perl-5.40.0 with PAGI::Test::Client ; the log lines and responses shown in Running it are the actual captured output, not hand-written. The PAGI middleware contract A PAGI application is, in the spec's words, "a single coderef returning a Future": an async sub over the ($scope, $receive, $send) triple — the same shape as ASGI. $scope is the per-connection metadata hash ( type , method , path , headers , …), $receive pulls inbound events, $send pushes outbound ones ( http.response.start , then http.response.body ), and the Future it returns resolving is what tells the server the response is complete. Middleware is just as plain: a subroutine that takes an application and returns a new application, wrapping the inner one. That is the whole spec-level contract — app in, app out: sub middleware { my ( $app ) = @_ ; return async sub ($scope, $receive, $send) { # ... before ... await $app -> ( $scope , $receive , $send ); # call the inner app # ... after ... }; } A middleware propagates the inner app's Future — its completion and any exception flow straight through — and never reads its return value, which the spec defines as inert; to observe or rewrite the response it wraps $send instead, and to add per-request context it clones $scope (top-level edits stay visible downward only). PAGI::Middleware , from PAGI-Tools rather than

2026-06-28 原文 →