How to use export all and export default in Javascript

Issue #964 In JavaScript, particularly in modules used in frameworks like React, export statements are used to expose code—such as functions, classes, or constants—from one module so that they can be imported and reused in other modules. export * The export * syntax is used to re-export all exportable members from the imported module. It’s a way to aggregate exports from several modules into a single module. For example, let’s say we have a couple of modules, each exporting some components:...

January 25, 2024 · 2 min · 397 words · Khoa

How to escape characters in json and regex with Swift string

Issue #963 In the world of Swift programming, we often come across situations where we need to work with string literals that contain special characters. These characters can include new lines, tabs, backslashes, and quotes — all of which need to be handled appropriately to ensure they don’t inadvertently affect the structure or behavior of our code. Traditionally, we negate their special meaning by escaping them with backslashes. However, Swift provides an even simpler method — raw strings....

January 12, 2024 · 4 min · 812 words · Khoa

How to use nextjs Image

Issue #962 Fill parent div A boolean that causes the image to fill the parent element, which is useful when the width and height are unknown. The parent element must assign position: “relative”, position: “fixed”, or position: “absolute” style. <div className="relative"> <Image src="" alt="" fill objectFit="cover" /> </div>

January 7, 2024 · 1 min · 48 words · Khoa

How to check NSTextField is first responder

Issue #961 NSTextField uses NSFieldEditor under the hood, you can check currentEditor if it is the firstResponder extension NSTextField { var isFirstResponder: Bool { currentEditor() == window?.firstResponder } }

January 7, 2024 · 1 min · 29 words · Khoa

Building an iOS camera calculator with Core ML’s Vision and Tesseract OCR

Issue #960 Also written on Fritz Math might be scary, but it’s an essential part of everyday life. Wouldn’t it be cool if we could build an app, point our phone’s camera at an expression, and let the app compute the result? Whenever I’ve needed to use math, I’ve wished this was possible. Now, with advances in machine learning and vision recognition in iOS, this is doable. In this guide, I’ll provide some of the technical details for working with Vision in iOS, as well as my personal experiences using this technology....

December 31, 2023 · 12 min · 2460 words · Khoa

How to decode dynamic JSON key with JSONDecoder

Issue #959 Decoding JSON in Swift is most of the time very straightforward with help of Codable protocol and JSONDecoder. Sometimes the json contains dynamic key, like { "shipmunk": { "name": "Shipmunk", "link": "https://indiegoodies.com/shipmunk" }, "pastepal": { "name": "PastePal", "link": "https://indiegoodies.com/pastepal" }, "codelime": { "name": "Codelime", "link": "https://indiegoodies.com/codelime" } } Decoding JSON with dynamic keys in Swift can be tricky because the keys in your data can change, and Swift likes to know exactly what it’s working with ahead of time....

December 21, 2023 · 2 min · 378 words · Khoa

How to bundle js for use in JavaScriptCore in Swift

Issue #958 We can use any bundler, like Parcel, Webpack or Vite. Here I use Webpack 5 Install Webpack and Babel npm install @babel/polyfill webpack webpack-cli --save-dev @babel/polyfill is a package provided by Babel, a popular JavaScript compiler. The polyfill is a way to bring modern JavaScript features and APIs to older browsers that don’t support them natively. Before ES6 (ECMAScript 2015), JavaScript lacked many features that are now considered standard....

December 7, 2023 · 2 min · 251 words · Khoa

How to handle log in JSContext with JavascriptCore

Issue #957 Define console object and set log function to point to our Swift function import JavaScriptCore extension JSContext { func injectConsoleLog() { evaluateScript( """ var console = {}; """ ) let consoleLog: @convention(block) (Any) -> Void = { print($0) } objectForKeyedSubscript("console") .setObject(consoleLog, forKeyedSubscript: "log" as NSString) } } Then we can just call let context = JSContext()! context.injectConsoleLog() context.evaluateScript(jsContent)

December 7, 2023 · 1 min · 60 words · Khoa

How to make attributed TextView for macOS and iOS with SwiftUI

Issue #956 macOS import Foundation import SwiftUI import AppKit struct AttributedTextView: NSViewRepresentable { @Binding var attributedText: NSAttributedString var isEditable: Bool = true final class Coordinator: NSObject { let parent: AttributedTextView init( parent: AttributedTextView ) { self.parent = parent super.init() } } func makeCoordinator() -> Coordinator { Coordinator(parent: self) } func makeNSView(context: Context) -> NSScrollView { let view = NSTextView.scrollableTextView() if let textView = view.documentView as? NSTextView { textView.font = NSFont.preferredFont(forTextStyle: ....

December 7, 2023 · 2 min · 257 words · Khoa

Apple Developer Learning resources

Issue #955 Besides WWDC videos & documentation, Apple also has interactive tutorials and books. Below are some of my favorites learning resources Tutorials Introducing SwiftUI: SwiftUI is a modern way to declare user interfaces for any Apple platform. Create beautiful, dynamic apps faster than ever before. Develop apps for iOS: Learn the basics of Xcode, SwiftUI, and UIKit to create compelling iOS apps. Develop in Swift: Develop in Swift Tutorials are a great first step toward a career in app development using Xcode, Swift, and SwiftUI....

November 29, 2023 · 1 min · 106 words · Khoa

How to show anchor bottom view in SwiftUI

Issue #954 From iOS 15, there’s a handy safeAreaInset that allows us to place additional content extending the safe area. Shows the specified content beside the modified view. safeAreaInset allows us to customize which edge and alignment we can place our views. This works for both ScrollView, List and Form and you can apply it multiple times. The content view is anchored to the specified horizontal edge in the parent view, aligning its vertical axis to the specified alignment guide....

November 22, 2023 · 2 min · 218 words · Khoa

How to debounce text input in React

Issue #953 Use debounce from lodash and useCallback to memoize debounce function import React, { useCallback } from "react" import debounce from "lodash/debounce" const SearchField = (props: Props) => { const callback = useCallback( debounce((value: string) => { props.setFilter({ ...props.filter, searchText: value, }) }), [] ) const handleChange = (value: string) => { callback(value) } return ( <div> <Input value={props.filter.searchText} placeholder="Search" variant="bordered" onValueChange={handleChange} /> </div> ) }

November 19, 2023 · 1 min · 67 words · Khoa

How to remove duplicates in Javascript array while keeping latest occurrence?

Issue #952 Use ES6 Map The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value. type Deal = { name: string, link: string } removeDuplicates = (array: Deal[]) => { const map = new Map() array.forEach((item) => map.set(item.link, item)) return [...map.values()] } We might need to update tsconfig.json...

November 17, 2023 · 1 min · 77 words · Khoa

How to drag multiple files in SwiftUI on Mac

Issue #951 Create a custom NSView that handles mouseDragged to beginDraggingSession struct DraggingSourceViewWrapper: NSViewRepresentable { let fileUrls: [URL] let onEnd: () -> Void func makeNSView(context: Context) -> DraggingSourceView { let view = DraggingSourceView(fileUrls: fileUrls) view.onEnd = onEnd return view } func updateNSView(_ view: DraggingSourceView, context: Context) { view.onEnd = onEnd } } final class DraggingSourceView: NSView { let fileUrls: [URL] var onEnd: (() -> Void)? init(fileUrls: [URL]) { self.fileUrls = fileUrls super....

November 13, 2023 · 2 min · 237 words · Khoa

How to dynamically build tailwind class names

Issue #950 Inspired by shadcn Combine tailwind-merge: Utility function to efficiently merge Tailwind CSS classes in JS without style conflicts. clsx: constructing className strings conditionally. import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }

November 4, 2023 · 1 min · 47 words · Khoa

How to store Codable in AppStorage

Issue #949 AppStorage and SceneStorage accepts RawRepresentable where value is Int or String. Creates a property that can read and write to a string user default, transforming that to RawRepresentable data type. init(wrappedValue:_:store:) init( wrappedValue: Value, _ key: String, store: UserDefaults? = nil ) where Value : RawRepresentable, Value.RawValue == String One clever thing (that does not work) is to use a custom Codable type that conforms to RawRepresentable, like below...

October 3, 2023 · 2 min · 333 words · Khoa

How to update widget for iOS 17

Issue #948 iOS 17 has a new Stand by mode so SwiftUI introduces containerBackground for the system to decide when to draw background. It also automatically applies margin to widget so we may need to disable that To update existing widgets, we can write some useful extension extension View { @ViewBuilder func safeContainerBackground(@ViewBuilder content: () -> some View) -> some View { if #available(iOS 17.0, *) { self.containerBackground(for: .widget, content: content) } else { self....

October 2, 2023 · 1 min · 155 words · Khoa

How to get Supabase user token from server API

Issue #947 Sometimes Row Level Security is not enough and we want to do all logic server side, then we need a way for the server to get hold onto current user token. Send JWT token in Authorization header From client, we can get session from supabase auth, then send that as Bearer in Authorization header const session = await supabase.auth.getSession().data.session const token = session.access_token const response = await fetch(url, { 'GET', headers: { Authorization: `Bearer ${token}` } }) Decode token From the nextjs API Route, we can handle all auth logic in middleware....

August 30, 2023 · 2 min · 309 words · Khoa

How to mirror auth.users on Supabase

Issue #946 For security purposes, the auth schema is not exposed on the auto-generated API. We can make a profiles table in public namespace and mirror data from auth.users when user signs up. I need id, username and raw_user_metadata so I will mirror these columns. For easy, you can leverage Supabase SQL Editor -> Quickstarts -> User Management Starter script I don’t need Row Level Security as I manage database from server....

August 30, 2023 · 2 min · 261 words · Khoa

How to force localized language with SwiftGen

Issue #945 The default SwiftGen generate generated strings L10n file like this extension L10n { private static func tr(_ table: String, _ key: String, _ args: CVarArg..., fallback value: String) -> String { let format = BundleToken.bundle.localizedString(forKey: key, value: value, table: table) return String(format: format, locale: Locale.current, arguments: args) } } // swiftlint:disable convenience_type private final class BundleToken { static let bundle: Bundle = { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: BundleToken....

August 26, 2023 · 1 min · 194 words · Khoa