LoveFuture Technical Documentation

website·Indexed 30 days ago

https://www.lovefuture.top/

A collection of technical guides and practical tutorials covering a wide range of development topics, including Rust (syntax, WASM, and Neon), Next.js, Electron, Go (Gin framework), NestJS, Midway, and Vue. It also includes resources on TypeScript, Node.js, TensorFlow.js, and general tools like Nginx, Git, and Vim.

Tokens
57.5K
Snippets
295
Records
327
Agent score
50%

What's inside LoveFuture

  1. Overview of Web Components standards

    Web Components are a set of technologies that allow the creation of reusable custom elements with encapsulated functionality. The standard consists of three main technologies:

    1. Custom Elements: JavaScript APIs to define custom elements and their behavior.
    2. Shadow DOM: JavaScript APIs to encapsulate styles and markup within a component, preventing interference with the external DOM.
    3. HTML Templates: The <template> and <slot> elements allow defining markup templates that are not rendered immediately but can be reused as the structure for custom elements.
  2. Design a database schema for third-party and local authentication

    To support both local (username/password/phone) and third-party (OAuth) logins while maintaining a clean architecture, use a decoupled table structure. This approach separates the core business user identity from the specific authentication mechanisms used to verify that identity.

    Table Responsibilities:

    • users: The core business user table. Used for internal business logic and as the primary identity for OAuth 2.0 providers within the system.
    • user_local_auth: Stores credentials for local authentication, such as usernames, passwords, and phone numbers.
    • user_third_auth: Stores data and identifiers provided by third-party authentication providers.
    • user_auth_rel: A relationship/mapping table that links a single core user in the users table to one or more authentication methods in user_local_auth or user_third_auth.
  3. Use `if let` for concise pattern matching

    Use if let when you only care about one specific pattern and want to ignore all other cases, avoiding the need for an exhaustive match expression.
    fn main() {
      let v = Some(0u8);
      if let Some(3) = v {
        println!("three")
      } else {
        println!("others")
      }
    }
  4. Understand Wujie micro-frontend architecture

    Wujie is a micro-frontend solution developed by Tencent. It utilizes a combination of Web Components and iframes to provide a runtime environment. Web Components are used to isolate styles between elements, while the iframe provides a native isolated environment with its own window, document, history, and location, ensuring better decoupling from the host application.
  5. Use basic data types in Go

    Go supports several fundamental data types:

    • Strings: Defined using double quotes. Use the + operator for concatenation and \n for newlines.
    • Integers: Includes signed (int8, int16, int32, int64) and unsigned (uint8, uint16, uint32, uint64) types. Signed integers can represent both positive and negative numbers, while unsigned integers only represent positive numbers.
    package main
    import "fmt"
    
    func main() {
        // String concatenation and newline
        text := "First line"
        text += "\nSecond line"
        fmt.Println(text)
    
        // Integer declaration
        var age int = 18
        fmt.Println(age)
    }
  6. Retrieve Page Data and Frontmatter using useData() in VitePress

    The useData() runtime API in VitePress allows developers to access metadata about the current page. The page object returned by useData() contains properties such as the page title, description, relative path, file path, and the frontmatter object containing all custom YAML variables defined at the top of the markdown file.
    // Example Page Data structure
    {
      "title": "Runtime API Examples",
      "description": "",
      "frontmatter": {
        "outline": "deep"
      },
      "headers": [],
      "relativePath": "api-examples.md",
      "filePath": "api-examples.md",
      "lastUpdated": 1788104079000
    }
    
    // Example Page Frontmatter structure
    {
      "outline": "deep"
    }
  7. Understand qiankun and Vite compatibility challenges

    Integrating qiankun with Vite presents three primary technical challenges:

    1. ESM Loading: Vite uses ESM, but qiankun does not support parsing ESM code within non-module script tags, preventing sub-apps from loading correctly.
    2. React Refresh: The __vite_plugin_react_preamble_installed global variable is placed in window.proxy due to qiankun's JS sandbox, causing errors when accessed.
    3. Public Path: Vite does not support runtime publicPath configuration, which qiankun requires to dynamically load sub-app resources.
  8. Define a Convolutional Neural Network (CNN) for CAPTCHA recognition

    The model uses a sequential architecture consisting of two convolutional layers for feature extraction, a max-pooling layer for downsampling, dropout layers to prevent overfitting, and dense (fully connected) layers for classification. The final layer uses a softmax activation to output probabilities for each possible label.
    const createModel = (): tf.Sequential => {
      const mModel = tf.sequential()
      // Conv Layer 1
      mModel.add(tf.layers.conv2d({
        inputShape: [96, 96, 4],
        filters: 32,
        kernelSize: [3, 3],
        activation: "relu",
      }))
      // Conv Layer 2
      mModel.add(tf.layers.conv2d({
        filters: 32,
        kernelSize: [3, 3],
        activation: "relu",
      }))
      mModel.add(tf.layers.maxPooling2d({ poolSize: [2, 2] }))
      mModel.add(tf.layers.dropout({ rate: 0.3 }))
      mModel.add(tf.layers.flatten())
      // Dense Layer 1
      mModel.add(tf.layers.dense({ units: 256, activation: "relu" }))
      mModel.add(tf.layers.dropout({ rate: 0.3 }))
      // Dense Layer 2 (Output)
      mModel.add(tf.layers.dense({ units: labelMapArr.length, activation: "softmax" }))
    
      mModel.compile({
        optimizer: tf.train.adam(0.0001),
        loss: "categoricalCrossentropy",
        metrics: ["accuracy"],
      })
      return mModel
    }
  9. Understand React 15 vs React 16 architecture and performance

    React 15 used a synchronous recursive update process (Stack Reconciler). If the component tree was large, the JS main thread would be blocked until the entire tree was processed, causing UI lag (stuttering) because the browser could not perform layout or paint tasks within the 16.6ms window (60Hz).

    React 16 introduced Fiber to solve this by allowing the reconciliation process to be interrupted and resumed. It leverages concepts similar to requestIdleCallback to perform work during the browser's idle time, ensuring high-priority tasks (like animations and user input) are handled first.

  10. Understand React Fiber architecture and task scheduling

    React Fiber is a reimplementation of the React core algorithm designed to enable incremental rendering. Before React 16, VirtualDOM reconciliation used recursive loops that could not be interrupted, leading to UI lag in large component trees. Fiber solves this by:

    1. Breaking the reconciliation process into small units of work (Fiber nodes).
    2. Replacing recursion with a loop that can be paused and resumed.
    3. Utilizing browser idle time to execute these units.

    The process is split into two phases: the Fiber construction phase (which is interruptible) and the Commit phase (which is non-interruptible and applies changes to the DOM).

  11. Define methods with pointer receivers in Go

    To modify the actual data of a struct within a method, use a pointer receiver. A pointer receiver is defined by using a pointer to the type (e.g., *Type) as the receiver. This allows the method to mutate the original instance rather than a copy.
    package main
    
    import "fmt"
    
    type Person struct {
    	Name string
    	Age  int
    }
    
    // Pointer receiver: allows modifying the original struct
    func (p *Person) GrowUp() {
    	p.Age++
    }
    
    func (p Person) Introduce() {
    	fmt.Printf("My name is %s, I am %d years old\n", p.Name, p.Age)
    }
  12. Implement computed properties in Vue 3

    Computed properties in Vue 3 are implemented using a combination of a getter, a setter, and a ComputedRefImpl class that manages caching and dependency tracking.

    Core Mechanism:

    • Dirty Checking: A _dirty flag tracks whether the cached value is stale. If _dirty is true, the getter is re-executed to update the value.
    • Reactive Effect: The computed property creates a ReactiveEffect. When dependencies of the getter change, the effect's scheduler marks the computed property as dirty (_dirty = true) and triggers updates to any components relying on this computed value.
    • Caching: If _dirty is false, the value getter returns the cached _value immediately without re-running the getter function.
    • Read-only vs Writable: If only a getter is provided, the computed property is marked as read-only.
    class ComputedRefImpl<T> {
      private _value!: T
      private _dirty = true
      public readonly effect: ReactiveEffect<T>
    
      constructor(getter: ComputedGetter<T>, private readonly _setter: ComputedSetter<T>, isReadonly: boolean) {
        this.effect = new ReactiveEffect(getter, () => {
          if (!this._dirty) {
            this._dirty = true
            triggerRefValue(this)
          }
        })
        this[ReactiveFlags.IS_READONLY] = isReadonly
      }
    
      get value() {
        const self = toRaw(this)
        trackRefValue(self)
        if (self._dirty) {
          self._dirty = false
          self._value = self.effect.run()!
        }
        return self._value
      }
    
      set value(newValue: T) {
        this._setter(newValue)
      }
    }