Last active: a year ago
Return a closure fn
/// Find parents of all files
///
/// ## Arguments
///
/// `local_path`: local files path from params
///
/// ## Return
///
/// `Fn`: used for `fold()`'s callback
pub fn fold_parents(local_path: &String) -> impl Fn(Vec<PathBuf>, &PathBuf) -> Vec<PathBuf> {
let local_path = PathBuf::from(local_path);
move |mut prev: Vec<_>, cur: &PathBuf| -> Vec<PathBuf> {
let skip_count = local_path
.parent()
.unwrap_or(&PathBuf::new())
.components()
.count();
let skip_count = if local_path.is_dir() && local_path.components().count() == 1 {
1
Last active: a year ago
Ant design resizable table
import { TableProps } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import dynamic from 'next/dynamic';
import { memo, useMemo, useState } from 'react';
import { ResizeCallbackData } from 'react-resizable';
import styles from 'styles/index.module.scss';
const ResizableTitle = dynamic(
() => import('components/pages/resizable-title'),
);
type ResizableTable<T> = TableProps<T>;
const ResizableTable = <T,>({ columns, ...rest }: ResizableTable<T>) => {
const [colWidth, setColWidth] = useState(
columns.map((d) => ({
key: d.key,
width: d.width,
})),
);
Last active: a year ago
organize imports for tsc server
local function organize_imports()
local params = {
command = "_typescript.organizeImports",
arguments = { vim.api.nvim_buf_get_name(0) },
}
vim.lsp.buf.execute_command(params)
end
lspconfig.tsserver.setup {
on_attach = on_attach,
capabilities = capabilities,
init_options = {
preferences = {
disableSuggestions = true,
},
},
commands = {
OrganizeImports = {
organize_imports,
description = "Organize Imports",
Last active: 10 months ago
Axum custom app error.
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use log::error;
use serde_json::json;
#[derive(thiserror::Error, Debug)]
pub enum AppError {
#[error("server internal error {0}")]
InternalServerError(#[from] anyhow::Error),
}
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status_code, err_message): (StatusCode, _) = match self {
AppError::InternalServerError(err) => {
error!("{}", err);
Last active: 10 months ago
Axum custom app error.
use crate::error::AppError;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use log::error;
use serde_json::json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum RouteError {
#[error("server internal error {0}")]
InternalServerError(#[from] anyhow::Error),
#[error("request validate failed {0}")]
ValidationError(String),
}
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for RouteError {
Last active: a year ago
Detect idle when browser lose focus.
import { useCallback, useEffect, useRef } from 'react';
const MINUTE = 60 * 1000;
/**
* 空闲检测
*
* 当浏览器丢失焦点时,出发定时器;定时结束后执行回调函数。
*
* 回调函数 `callback` 是 `useCallback` 的依赖,需要保持地址唯一。
*
* @param timeout 超时时长 默认 5 分钟
* @param callback 回调
*/
const useIdle = (
timeout = MINUTE * 5,
callback = () => {
console.warn('idled');
}
) => {
const id = useRef<NodeJS.Timeout>();
Last active: a year ago
Webassembly errors
use std::fmt::Display;
use thiserror::Error;
use wasm_bindgen::JsValue;
#[derive(Error, Debug)]
pub enum Error {
#[error("js runtime error")]
JsError(JsValue),
#[error(transparent)]
Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error
}
pub fn into_js_value<E>(err: E) -> String
where
E: Display,
{
err.to_string()
}
Last active: a year ago
Rust fetch file with browser fetch funtion in webassembly
use anyhow::Result;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
/// Fetch file by browser fetch
///
/// Arguments:
///
/// - `url`: target url. support relative path.
#[wasm_bindgen]
pub async fn fetch_file(url: &str) -> Result<String, JsValue> {
let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors);
let request = Request::new_with_str_and_init(url, &opts)?;
let window = web_sys::window().ok_or("cannot access browser window")?;
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
Last active: a year ago
isInViewPort
/**
* 检测指定的 DOM 元素是否在浏览器视口中
* @param el 被检测的元素
* @returns boolean 是否在视口中
*/
export const isInViewPort = (el: HTMLElement) => {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
Last active: a year ago
rust wake tree
use std::{
cell::RefCell,
rc::{Rc, Weak},
};
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
chilren: RefCell<Vec<Rc<Node>>>,
}
fn main() {
let leaf = Rc::new(Node {
value: 1,
parent: RefCell::new(Weak::new()),
chilren: RefCell::new(vec![]),
});
println!(
Last active: a year ago
useImperativeHandle with typescript
import { css } from "@emotion/css";
import { forwardRef, useImperativeHandle, useRef } from "react";
type Props = {
placeholder?: string;
};
export type ImpertiveHandler = {
focus: () => void;
};
const Child = forwardRef<ImpertiveHandler, Props>(({ placeholder }, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current?.focus();
}
}));
return (
Last active: a year ago
useImperativeHandle with typescript
import "./styles.css";
import Child, { ImpertiveHandler } from "./Child";
import { css } from "@emotion/css";
import { useRef } from "react";
export default function App() {
const inputRef = useRef<ImpertiveHandler>(null);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div
className={css`
display: flex;
justify-content: center;
flex-flow: column;
align-items: center;
`}
>