snippet(20/0)

Send files safely to anyone in the world

What if you need to send sensitive information to a person on the other side of the planet? What if they need to send something to you? Here we’ll explore a simple options available to you. Email Many email providers, such as Outlook and Gmail, encrypt sent email traffic by default. If both the sender and receiver email providers support TLS (Transport-Level Security), such as when one Outlook account emails another, then your message cannot be read if intercepted in-transit.…

Offer local user comment interaction

I’m wondering if it would be nice for users to take comments on my pages? Or for myself even? Here’s a self-contained example of a simple page that lets the user highlight a bit of text, make a short comment, and append it to the page. I’m not interested in wiring this up to a service or anything, but it’s pretty cool just to have this kind of local interaction with the content.…

Implement an oath2 authorization flow

TODO: finish this article Add disclaimer about my example: may not need private server, etc. Steps GET authorization route from service with redirect to current page open route in new window (snippet, link to article about enabling popups on iOS) gather code from redirected url on same page send code to origin window and close new window. (snippet) send code to my server’s token endpoint server requests token with code.…

Stage hunks in git

Like Pawel I’ve been tethered to source control GUIs because I didn’t know how to stage code hunks in the same file into different commits. But no longer! The answer is so simple I can’t believe I didn’t search for it earlier. git add -p name_of_file.txt How easy is that?

Inject web component dependencies

If you’re transitioning from a framework like Angular to native web components it feel natural to inject services into your components. When you discover it’s not possible via the constructor, you may give up and use a framework after all. Or you might engineer your own dependency injection decorators. But there’s another lightweight option. Let me show you. ℹ️ These instructions are perfect for small, private use-cases. If you're building dozens of services with interlocking dependencies, there's no decent option besides a framework.…

Test your namecheap API

My Let’s Encrypt SSL cert was accidentally expired. It’d been updated, but certbot created a new cert instead of updating the existing one. I don’t know why. Anyways. This led me to explore how I might automate this and viola, trwnh has done it! Before you plug in trwnh’s Python script, however, maybe you just want to check out the API for yourself? Here’s a fish script to do it.…

Conditional and union types are better

Elsewhere I advocate for that developers use http response objects. TypeScript has a couple nifty improvements that can really make these response objects simple: Union and Conditional types. Let’s say you have an Author object returned from your API. Now you want to add response properties. Type Union to the rescue! export interface Response { success: boolean; message?: string; } export interface Author { id: number; name: string; age: number; } // the union is an ampersand type AuthorResponse = Author & Response; // and a typed example const x = <AuthorResponse>{ success: true, name: 'Alex', age: 34 }; That worked great for your /artist GET request, but now you need an /artist PUT.…

Recurse tree nodes

Reasons to build recursive functions happen infrequently enough that I often forget how to do it. Here’s an example I wrote recently to retrieve a flat array of nodes in a tree which meet a certain requirement. Essentially it’s a recursive filter. It’s been made generic so that any object which implements the Node interface can use it. export interface Node { public parent?: Node; public children?: Node[]; } export function getNodesBy<T>(propFunc: (Node) => boolean, tree: Node[]): T[] { const getNodes = (items: Node[]) => { const matches = items.…

Embed web components into static HTML

I’ve successfully published hundreds of articles using only a static site generator. Sometimes though, I itch to create reactive elements like I build at work with Angular. What is a developer to do? My needs are tiny, so here is a tiny way to get started. ℹ️ My intended goal is to supply a small number of custom web components for most pages on my website that I can inject via Hugo shortcodes.…

Get published today feed

This JavaScript snippet reads multiple RSS/XML feeds on my site and adds a list of the items published on this day to the bottom of my page. I may use this in future to add a “Published On This Day” feed to my site, kind of like how OneDrive will pop up a picture from last year. const parser = new DOMParser(); const today = new Date(); const lastYear = new Date(today.…

Hide nodes by sum of attribute

My tags list has 195 tags with a single entry. One of the primary purposes for tags is to compare writing with the same tag to discover similarities, so these entries achieve little. A simple button to the tags list with the following JavaScript will hide all tags with a plant and stone sum of less than two. document.querySelectorAll("div.terms-page__terms>div").forEach((el) => { var txt = el.childNodes[0].childNodes[1].innerText; var txtSum = txt.slice(1,-1).split('/').reduce((p,c) => Number(p) + Number(c)); if (txtSum < 2) { el.…

Verify your RSS feed

If you have an RSS feed, you can use this snippet as a starting place to review the output. I’m printing the titles of each RSS item to the console, but go as deep as necessary to ensure the right information ends up in your feed. fetch('https://my-url-here.com') .then(res => res.text()) .then(text => { const domParser = new DOMParser(); const doc = domParser.parseFromString(text, 'text/html'); var feedURL = doc.querySelector('link[type="application/rss+xml"]'); return fetch(feedURL.href); }) .…

Save unfinished notes in local storage

When I publish content to my site I sometimes get nervous that the work I’ve written into the publish form will be lost. Jan-Lukas has written a straightforward Javascript snippet to store my work locally so it will not be lost. Thanks! Simply cache form fields in localStorage

Display backlink preview on hover

The combination of microformat2 h-entry and backlinks is potent. Each note page that’s marked up with a e-content microformat2 property can be retrieved via fetch() and displayed as a preview elsewhere on the site. No database required; the website is the API. With these two snippets you can implement dynamic backlink functionality on pretty much any webpage. With a little standardization (mostly complete by the microformat2 standard), one could support backlinks across websites.…

Add snippets to your text input

If you have a textarea where you enter content on a regular basis and want to implement snippets to help with certain constructs, this JavaScript example might be just your style. I may use it in my publishing service so I can easily enter Hugo shortcodes I’ve developed for my site. document.querySelector('textarea.content').addEventListener('keyup', (event) => { var txt = event.target.value; if (txt.length < 7) { return; } var lastWord = txt.split(' ')?…

Custom container queries with resize observer

Until CSS container queries are baked into every browser, ResizeObserver fills the gap. Here’s an example of an observer that switches the CSS Flex from row to column based on the container’s width. This is used on my Plants and Stones pages. ℹ️ I use a Store object to share observable state across my application. This vastly simplifies communication between components; in this case, with my filter component. When my filter results change, I want to re-calculate the possible list width.…

One subscription per resource

Here’s my subscription progression for the qrm-category-container root component. Let me know if this is headed in the right direction. Stage One - Current Code The root container creates a subscription in onInit() that fires whenever fedId or QRM periodId changes, like so: combineLatest([this.sessionQuery.federalReserveId$, this.sessionQuery.qualitativePeriodId$]) .subscribe(([fedId, qualitativePeriodId]) => { this.qualitativePeriodId = qualitativePeriodId; this.refreshViewModel(fedId, qualitativePeriodId, this.viewCustomerData, this.categoryId); }); That’s not too bad, right? Consider what happens in refreshViewModel()… refreshViewModel(federalReserveId: number, periodId: number, viewCustomerData: boolean, categoryId): void { this.…

Smart components observe state over input

In component design there are two buckets, smart and dumb components. Smart components are keepers of data models and reactive to changes. Dumb components render explicit data models to views. Dumb components benefit from the explicit interface created by a clear set of inputs. Smart components, however, can get into a lot of trouble if they depend on mutable inputs for their data models. While it seems easy to add an onChanges() function to child smart components to re-render based on changes to their inputs, this dependency can have unexpected consequences.…

Use HTTP response objects

As Victoria mentions in her post, the type of code you’re writing affects how you’ll handle errors. Her example matches code that integrates with other systems on the same machine (and probably other cases). The code I’m writing these days, when it’s not JavaScript, is for back-end services. I’ve discovered that services delivered over HTTP/S are best implemented to capture exceptions in the service and return response objects. I’ll usually do something like this:…

Store secret text in the cloud

I was updating my resume the other day when something creepy happened. Dropbox, where my resume sits, showed me an advertisement for resume assistance. If it’s not clear why this creeped me out, consider: to know the file was a resume, Dropbox needs to scan the entire document. It wasn’t called ‘resume’. the scan is sophisticated enough to accurately determine the contents of what I’ve written. at least some of this data is shared with the owner of the advertisement.…