Skip to content

Common Utilities

Common brings together the "Swiss Army Knife" functions within TechUI that cannot be easily categorized but are used with high frequency in business development.

It covers a range of atomic capabilities, from device environment sniffing and data structure transformation to view transition animations.

Import Method

javascript
import { 
  deviceInfo, 
  fullScreen, 
  flatToTree, 
  genUid, 
  viewTransStart,
  colorPicker,
  tConsole,
  tTime
} from "@techui/utils";

Device & Screen

deviceInfo()

Retrieves detailed hardware and environment information of the current device. Commonly used for responsive layout logic or mobile compatibility handling.

  • Returns: Object
  • Source Logic: Calculates breakpoints based on the UserAgent and screen dimensions (document.body.clientWidth).
javascript
const info = deviceInfo();
console.log(info);

/* Output Example:
{
  type: "pc-xl",      // Screen breakpoints: pc-xl, pc-lg, pc-md, pc-sm, pad, mobile
  h: 1920,            // Current width
  v: 1080,            // Current height
  touchable: false,   // Whether touch is supported
  browser: "webkit",  // Browser engine: webkit, Firefox, IE
  orientation: "landscape", // Orientation state
  screenInvert: false       // Whether the screen is inverted
}
*/

fullScreen

A full-screen control object that encapsulates the browser's native requestFullscreen and exitFullscreen APIs.

  • fullScreen.isEnabled(): Determines if the application is currently in full-screen mode.
  • fullScreen.toggle(): Toggles between full-screen and non-full-screen modes.
  • fullScreen.switch(boolean): Forcefully switches the state (true to enter full-screen, false to exit).
javascript
// Button click event
const handleScreen = () => {
  fullScreen.toggle();
};

Data Structure

flatToTree(flatData)

Converts a flattened database result set (containing id, parentId) into a tree structure (containing children).

  • Features: Automatically sorts based on the order field and cleans up empty children arrays.
  • Scenario: Generating sidebar menus, organizational structure trees.
javascript
const list = [
  { id: 1, name: 'Root', parentId: null, order: 1 },
  { id: 2, name: 'Child', parentId: 1, order: 0 }
];

const tree = flatToTree(list);
// Result: [{ id: 1, children: [{ id: 2, ... }] }]

genUid(prefix, len) V0.0.5+

Generates a unique identifier.

  • prefix: The ID prefix string.
  • len: Length of the random suffix.
javascript
genUid('node', 6); // Output: "node_xYz123"

Vision & Animation

viewTransStart(options)

An encapsulation of transition animations based on the native Chrome View Transitions API.

  • Mechanism: During the animation execution, the tui-transitioning class is automatically added to the html root element to facilitate CSS hook control.
  • Fallback: If the browser does not support this API, the callback will be executed directly.
javascript
viewTransStart({
  enable: true, // Whether to enable the transition
  callback: () => {
    // Update the DOM here, e.g., switch routes or change themes
    updateMyDom(); 
  },
  complete: () => {
    console.log('Transition completed');
  }
});

colorPicker(options)

Advanced Color Picker. Typically used for dynamic color scheme generation in ECharts or data visualizations.

  • Dependencies: Internally depends on $c (Chroma.js wrapper) and $tCore.
  • Parameters:
    • palette: An array of base colors.
    • total: The total number of colors to generate.
    • mode: Interpolation mode (lch, hsl, lab, etc.).
    • pickType: Picking strategy (seq sequential, rdm random).
Note: This tool may be deprecated in future versions; use $c.scale instead.
javascript
const colors = colorPicker({
  palette: ['#ff0000', '#0000ff'], // Red to Blue
  total: 10,                       // Generate 10 gradient colors
  mode: 'lch'
});

Debugging & Formatting

tConsole

Throttled Console. Used to prevent the same error or warning message from flooding the console.

  • tConsole.s(type, name, msg, thro): Sends a message.
    • type: 'log' | 'warn' | 'error' | 'info'
    • name: Unique identification Key; messages with the same Key will be throttled.
    • thro: Whether to enable throttling (defaults to true).
  • tConsole.g(name): Retrieves cached information.
javascript
// Called within a loop, this will only print once
for(let i=0; i<100; i++){
  tConsole.s('warn', 'myKey', 'This is a warning', true);
}

tTime

A simple regex-based time formatting tool.

  • formatTime(str, fmt): Formats HH:mm.
  • formatWeek(str, fmt): Formats YYYY-WW.
javascript
tTime.formatTime('14:05', 'HHh MMm'); // -> "14h 05m"
tTime.formatWeek('2023-W01', 'YYYY Week WW'); // -> "2023 Week 01"

Released under the MIT License.