惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
SecWiki News
SecWiki News
N
News | PayPal Newsroom
T
Tor Project blog
W
WeLiveSecurity
A
Arctic Wolf
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
月光博客
月光博客
AWS News Blog
AWS News Blog
D
Docker
C
CERT Recently Published Vulnerability Notes
MyScale Blog
MyScale Blog
Google Online Security Blog
Google Online Security Blog
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
I
InfoQ
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
D
DataBreaches.Net
S
Security Affairs
WordPress大学
WordPress大学
T
Threatpost
Microsoft Security Blog
Microsoft Security Blog
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
B
Blog RSS Feed
Project Zero
Project Zero
P
Proofpoint News Feed

Bryan Robinson's Blog

Does our technology still work for us? Product pricing, dev bad habits, and the role of the pit of success Astro Server Island for latest Bluesky post (heavily cached!) Type-safe environment variables in Astro 5.0 New Website, but really is it? Netlify Durable Cache: Caching for a third-party world Introducing the Hygraph Astro Content Loader Integrating Astro.js Starlight Documentation into a Next.js Project Using Proxies Jamstack is meaningless 😱 Book Release: Eleventy by Example – Learn 11ty with 5 in-depth projects 11ty Second 11ty: Creating Template Filters 11ty Second 11ty: Global Data files (JS and JSON) 11ty second 11ty: The Render Plugin Part 1 Help needed: Netlify Frontend environment variables with Astro.js Creating a dynamic color converter with 11ty Serverless Using 11ty JavaScript Data files to mix Markdown and CMS content into one collection How to show your template code in 11ty blog posts New City, New Job, New Content Using Nunjucks Climbing the 11ty Performance leaderboard with Cloudinary, critical CSS and more Three JAMstack movements to watch in 2020 Create a Codepen promo watermark with no additional HTML, CSS or JS 3 underused CSS features to learn for 2020 Use CSS Subgrid to layout full-width content stripes in an article template Adapt client-side JavaScript for use in 11ty (Eleventy) data files CSS Gap creates a bright future for margins in Flex as well as Grid Create your first CSS Custom Properties (Variables) Use CSS Grid to create a self-centering full-width element Creating an 11ty Plugin - SVG Embed Tool Now offering design and code reviews at PeerReviews.dev Routing contact-form emails to different addresses with Netlify, Zapier and SendGrid Create an Eleventy (11ty) theme based on a free HTML template Client work and the JAMstack Grid vs. Flex: A Tale of a "Simple" Promo Space Using Eleventy The Tech Barrier to Entry What Can We Learn from CERN Let Practical CSS Grid - Launching My First Course Build Trust on the Web incorporating User Worries with your User Stories 2019 The Year of Markup-First Development Refactoring CSS into a Sass mixin Starting a new journey with Code Contemporary Dynamic Static Sites with Netlify and iOS Shortcuts Top 3 uses for the ::before and ::after CSS pseudo elements How To: Use CSS Grid to Mix and Match Design Patterns Use CSS ::before and ::after for simple, spicy image overlays Modern CSS: Four Things Every Developer and Designer Should Know About CSS 3 Strategies for Getting Started with CSS Grid CSS Tip: Use rotate() and skew() together to introduce some clean punk rock to your CSS The 5 Stages of Grid Love How To: A CSS-Only Mobile Off Canvas Navigation How To: Use CSS Grid Layout to Make a Simple, Fluid Card Grid Make a More Flexible Cover Screen with CSS Grid Can CSS Grid open up interesting CMS Layout options? Firefox 52 to Introduce New Box-Alignment Values Falling Forward — Rethinking Progressive Enhancement, Graceful Degradation and Developer Morality Start Exploring the Magic of CSS Grid Layout I Converted My Blog to CSS Grid Layout and Regret Nothing Feature Queries are on the Rise CSS Shapes — Let the Text Flow Around You Flexbox -- Let Memorializing Prince and Print vs. The Web I went to Italy and noticed UX fails How to Get Designers to Contribute in Open Source The True Gift of Your Former Code
Quick experiment with the Slinkity 11ty plugin
2021-10-21 · via Bryan Robinson's Blog

Ben Holmes (the creator of Slinkity) posted on Smashing Magazine today about [the creation of the Slinkity plugin for 11ty](https://www.smashingmagazine.com/2021/10/building-ssg-11ty-vite-jam-sandwich/). After reading it, I had to give Slinkity a try.

The use case

My almost-6-year old has a little art website that I set up for him. Originally, it was just HTML. Then he made more art, so I converted to 11ty with a Sanity Studio for image management.

Like any adolescent, there's always a desire for more. He wanted a "like" button to know how many people liked his art. Despite explaining to him that I was really only sharing the site with his grandparents and that he wouldn't get too many likes. I promised I'd implement the feature if he consistently drew pictures for it.

He's done a good job, so I needed to write the feature...

Downside: I had no build process. Upside: A chance to see what folks were using for tiny interactions!

I reached out on Twitter to see what folks thought. Even on a weekend, there were opinions.

From "Roll your own in JS" to "web components" to "petite vue" and more. All great suggestions. I started with very simple JS event handlers, but it was pretty messy code. I moved on to a web component, but, as I usually do, I got frustrated by the feel of web components (I really want them to be awesome).

I want to learn more about AstroJS, so I started re-writing the site in Astro (since there wasn't much functionality yet). It went relatively well, but the data pipeline is still pretty rough around the edges. I was able to get my Sanity content pulling in, but not without some annoyances (that the Astro discord helped me get through, I should add!).

Fast forward to Ben's post and my realization that Slinkity had the same ideas as AstroJS about islands of static content and rehydrated content (which I totally think is the future of the web... and maybe it's the past, too...).

The code

Expect a bigger tutorial on Slinkity coming up, but for now, here's a bit of code for how I implemented a very simple "Like" button for my son's images.

After I set up my Sanity connection, I had an image.html template that set up individual pagination for detail pages for each of the images – much like a blog post template. This is where I wanted the like button.

I kept things VERY simple (it's a site for a 6-year old after all!). Basically, a template to show an image with a caption. Quick aside, the imageUrlFor shortcode comes from my alpha Sanity Image plugin.

---
layout: "base.html"
pagination: 
    data: images
    size: 1
    alias: image
permalink: "{{ image.slug }}/index.html"
---

<div class="container">

    <figure class="stack">
        <img src="{% imageUrlFor image.image, 750 %}">
        <figcaption>{{ image.caption }}</figcaption>
    </figure>

</div>

Next, I needed to install the Slinkity package and change the way I was building and serving my site. What Slinkity does is creates a build process that runs your 11ty instance and then runs a Vite server on the _site directory (or whatever your config file says is your output directory).

npm i --save-dev slinkity
{
  // package.json
  "scripts": {
    // Start changes to slinkity --serve instead of eleventy --serve
    "start": "slinkity --serve",
    // Build changes to slinkity instead of eleventy
    "build": "slinkity"
  },
}

Once that was installed, I was ready to create a React component and insert it into my template.

The component and the react shortcode

To add the component, I needed to create a components directory inside my _includes directory. In that directory, I added a LikeCounter.js file.

This code could probably be refined more, but at its essence it's a component that takes a current like count and an image ID (the Sanity document ID). It uses the count for initial HTML display (statically built during the build). It then fetches an updated count from a serverless function. The serverless function queries Sanity based on the document ID and gets the current count. I also have a serverless function for incrementing the count when a user clicks.

import React, { useEffect, useState } from 'react'

function LikeCounter({likeCount, id}) {
  const [count, setCount] = useState(likeCount)
  useEffect(() => {
    fetch('/.netlify/functions/getLikes', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
            },
            body: JSON.stringify({image: id})
            })
            .then(res => res.json())
            .then(res => {
                setCount(res.count)
            })
                

  }, [])
  async function handleClick() {
    setCount(count + 1)

    fetch('/.netlify/functions/setLikes', {
          method: 'POST',
          body: JSON.stringify({
              image: id
              })
            })
            .then(res => res.json())
            .then(res => {
                console.log(res)
                setCount(res.count)
            })
}

  return (
    <div>
      <p>This photo has {count} likes ❤️ 
        <button onClick={handleClick}>Add a like</button>
      </p>   
    </div>
  )
}

export default LikeCounter

Once the component is created, I added the component to my template.

---
layout: "base.html"
pagination: 
    data: images
    size: 1
    alias: image
permalink: "{{ image.slug }}/index.html"
---

<div class="container">

    {% react 'components/LikeCounter' 'likeCount' image.count 'id' image._id %}

    <figure class="stack">
        <img src="{% imageUrlFor image.image, 750 %}">
        <figcaption>{{ image.caption }}</figcaption>
    </figure>

</div>

The react shortcode accepts a number of arguments that will be ingested as props. In this case, I pass the likeCount and id.

Slinkity handles the rest.

In about an hour, I had a working React component and a new build pipeline. I got to keep all the things I love about 11ty.

Node Version and deployment

One thing to keep an eye out for is that Slinkity has some dependencies that need Node version 14.x. By default my Netlify site was on v12.x. To get around this, set an environment variable of NODE_VERSION with a 14+ version number. You can also set this in your netlify.toml.

Why not Astro?

I'd originally planned on using this as a way to test and play with AstroJS. I really enjoyed playing with it in this use case, but the data pipeline was a bit rough to deal with for ingesting data from Sanity. I know the Astro team is currently working on the data pipeline, so I'm confident that for use cases like this it'll be a great solution soon.

More than anything Astro felt like a good bridge between the world of 11ty and the world of frameworks like Next. It felt kind of like I was writing Next code next to 11ty code, which was nice.

I think both these advancements are 100% the future. Slinkity gets the advantage of the current 11ty ecosystem and tooling.

Next Steps

Right now Slinkity is just compatible with React, but I know the team is working on integrating with other libraries (and even vanilla JS, which I'm excited about!).

For now, I've got some additional ideas for using Slinkity to add more interactive islands with no need for a large build process, which is super exciting to me.