repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
vue3-blog
github_2023
Peerless-man
typescript
delAliveRoutes
function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) { delAliveRouteList.forEach(route => { usePermissionStoreHook().cacheOperate({ mode: "delete", name: route?.name }); }); }
/** 批量删除缓存路由(keepalive) */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L97-L104
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
getParentPaths
function getParentPaths(path: string, routes: RouteRecordRaw[]) { // 深度遍历查找 function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) { for (let i = 0; i < routes.length; i++) { const item = routes[i]; // 找到path则返回父级path if (item.path === path) return parents; // children不存在或为空则不递归 if (!item.children || !item.children.length) continue; // 往下查找时将当前path入栈 parents.push(item.path); if (dfs(item.children, path, parents).length) return parents; // 深度遍历查找未找到时当前path 出栈 parents.pop(); } // 未找到时返回空数组 return []; } return dfs(routes, path, []); }
/** 通过path获取父级路径 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L107-L128
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
dfs
function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) { for (let i = 0; i < routes.length; i++) { const item = routes[i]; // 找到path则返回父级path if (item.path === path) return parents; // children不存在或为空则不递归 if (!item.children || !item.children.length) continue; // 往下查找时将当前path入栈 parents.push(item.path); if (dfs(item.children, path, parents).length) return parents; // 深度遍历查找未找到时当前path 出栈 parents.pop(); } // 未找到时返回空数组 return []; }
// 深度遍历查找
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L109-L125
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
findRouteByPath
function findRouteByPath(path: string, routes: RouteRecordRaw[]) { let res = routes.find((item: { path: string }) => item.path == path); if (res) { return isProxy(res) ? toRaw(res) : res; } else { for (let i = 0; i < routes.length; i++) { if ( routes[i].children instanceof Array && routes[i].children.length > 0 ) { res = findRouteByPath(path, routes[i].children); if (res) { return isProxy(res) ? toRaw(res) : res; } } } return null; } }
/** 查找对应path的路由信息 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L131-L149
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
initRouter
function initRouter() { return new Promise(resolve => { // 初始化路由 usePermissionStoreHook().handleWholeMenus([]); resolve(router); }); // if (getConfig()?.CachingAsyncRoutes) { // // 开启动态路由缓存本地sessionStorage // const key = "async-routes"; // const asyncRouteList = storageSession().getItem(key) as any; // if (asyncRouteList && asyncRouteList?.length > 0) { // return new Promise(resolve => { // handleAsyncRoutes(asyncRouteList); // resolve(router); // }); // } else { // return new Promise(resolve => { // getAsyncRoutes().then(({ data }) => { // handleAsyncRoutes(cloneDeep(data)); // storageSession().setItem(key, data); // resolve(router); // }); // }); // } // } else { // return new Promise(resolve => { // getAsyncRoutes().then(({ data }) => { // handleAsyncRoutes(cloneDeep(data)); // resolve(router); // }); // }); // } }
// function addPathMatch() {
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L194-L226
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
formatFlatteningRoutes
function formatFlatteningRoutes(routesList: RouteRecordRaw[]) { if (routesList.length === 0) return routesList; let hierarchyList = buildHierarchyTree(routesList); for (let i = 0; i < hierarchyList.length; i++) { if (hierarchyList[i].children) { hierarchyList = hierarchyList .slice(0, i + 1) .concat(hierarchyList[i].children, hierarchyList.slice(i + 1)); } } return hierarchyList; }
/** * 将多级嵌套路由处理成一维数组 * @param routesList 传入路由 * @returns 返回处理后的一维路由 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L233-L244
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
formatTwoStageRoutes
function formatTwoStageRoutes(routesList: RouteRecordRaw[]) { if (routesList.length === 0) return routesList; const newRoutesList: RouteRecordRaw[] = []; routesList.forEach((v: RouteRecordRaw) => { if (v.path === "/") { newRoutesList.push({ component: v.component, name: v.name, path: v.path, redirect: v.redirect, meta: v.meta, children: [] }); } else { newRoutesList[0]?.children.push({ ...v }); } }); return newRoutesList; }
/** * 一维数组处理成多级嵌套数组(三级及以上的路由全部拍成二级,keep-alive 只支持到二级缓存) * https://github.com/pure-admin/vue-pure-admin/issues/67 * @param routesList 处理后的一维路由菜单数组 * @returns 返回将一维数组重新处理成规定路由的格式 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L252-L270
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
handleAliveRoute
function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) { switch (mode) { case "add": matched.forEach(v => { usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name }); }); break; case "delete": usePermissionStoreHook().cacheOperate({ mode: "delete", name: matched[matched.length - 1].name }); break; default: usePermissionStoreHook().cacheOperate({ mode: "delete", name: matched[matched.length - 1].name }); useTimeoutFn(() => { matched.forEach(v => { usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name }); }); }, 100); } }
/** 处理缓存路由(添加、删除、刷新) */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L273-L297
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
addAsyncRoutes
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) { if (!arrRoutes || !arrRoutes.length) return; const modulesRoutesKeys = Object.keys(modulesRoutes); arrRoutes.forEach((v: RouteRecordRaw) => { // 将backstage属性加入meta,标识此路由为后端返回路由 v.meta.backstage = true; // 父级的redirect属性取值:如果子级存在且父级的redirect属性不存在,默认取第一个子级的path;如果子级存在且父级的redirect属性存在,取存在的redirect属性,会覆盖默认值 if (v?.children && v.children.length && !v.redirect) v.redirect = v.children[0].path; // 父级的name属性取值:如果子级存在且父级的name属性不存在,默认取第一个子级的name;如果子级存在且父级的name属性存在,取存在的name属性,会覆盖默认值(注意:测试中发现父级的name不能和子级name重复,如果重复会造成重定向无效(跳转404),所以这里给父级的name起名的时候后面会自动加上`Parent`,避免重复) if (v?.children && v.children.length && !v.name) v.name = (v.children[0].name as string) + "Parent"; if (v.meta?.frameSrc) { v.component = IFrame; } else { // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会跟path保持一致) const index = v?.component ? modulesRoutesKeys.findIndex(ev => ev.includes(v.component as any)) : modulesRoutesKeys.findIndex(ev => ev.includes(v.path)); v.component = modulesRoutes[modulesRoutesKeys[index]]; } if (v?.children && v.children.length) { addAsyncRoutes(v.children); } }); return arrRoutes; }
/** 过滤后端传来的动态路由 重新生成规范路由 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L300-L326
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
getHistoryMode
function getHistoryMode(): RouterHistory { const routerHistory = import.meta.env.VITE_ROUTER_HISTORY; // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1 const historyMode = routerHistory.split(","); const leftMode = historyMode[0]; const rightMode = historyMode[1]; // no param if (historyMode.length === 1) { if (leftMode === "hash") { return createWebHashHistory("/admin/"); } else if (leftMode === "h5") { return createWebHistory(""); } } //has param else if (historyMode.length === 2) { if (leftMode === "hash") { return createWebHashHistory(rightMode); } else if (leftMode === "h5") { return createWebHistory(rightMode); } } }
/** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L329-L350
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
getAuths
function getAuths(): Array<string> { return router.currentRoute.value.meta.auths as Array<string>; }
/** 获取当前页面按钮级别的权限 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L353-L355
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
hasAuth
function hasAuth(value: string | Array<string>): boolean { if (!value) return false; /** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */ const metaAuths = getAuths(); if (!metaAuths) return false; const isAuths = isString(value) ? metaAuths.includes(value) : isIncludeAllChildren(value, metaAuths); return isAuths ? true : false; }
/** 是否有按钮级别的权限 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/router/utils.ts#L358-L367
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
message
const message = ( message: string | VNode | (() => VNode), params?: MessageParams ): MessageHandler => { if (!params) { return ElMessage({ message, customClass: "pure-message" }); } else { const { icon, type = "info", dangerouslyUseHTMLString = false, customClass = "antd", duration = 2000, showClose = false, center = false, offset = 20, appendTo = document.body, grouping = false, onClose } = params; return ElMessage({ message, type, icon, dangerouslyUseHTMLString, duration, showClose, center, offset, appendTo, grouping, // 全局搜 pure-message 即可知道该类的样式位置 customClass: customClass === "antd" ? "pure-message" : "", onClose: () => (isFunction(onClose) ? onClose() : null) }); } };
/** 用法非常简单,参考 src/views/components/message/index.vue 文件 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/message.ts#L38-L78
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
closeAllMessage
const closeAllMessage = (): void => ElMessage.closeAll();
/** * 关闭所有 `Message` 消息提示函数 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/message.ts#L83-L83
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
PureHttp.retryOriginalRequest
private static retryOriginalRequest(config: PureHttpRequestConfig) { return new Promise(resolve => { PureHttp.requests.push((token: string) => { config.headers["Authorization"] = token; resolve(config); }); }); }
/** 重连原始请求 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/http/index.ts#L49-L56
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
PureHttp.httpInterceptorsRequest
private httpInterceptorsRequest(): void { PureHttp.axiosInstance.interceptors.request.use( async (config: PureHttpRequestConfig) => { // 开启进度条动画 NProgress.start(); // 优先判断post/get等方法是否传入回掉,否则执行初始化设置等回掉 if (typeof config.beforeRequestCallback === "function") { config.beforeRequestCallback(config); return config; } if (PureHttp.initConfig.beforeRequestCallback) { PureHttp.initConfig.beforeRequestCallback(config); return config; } /** 请求白名单,放置一些不需要token的接口(通过设置请求白名单,防止token过期后再请求造成的死循环问题) */ const whiteList = ["/refreshToken", "/login"]; return whiteList.some(v => config.url.indexOf(v) > -1) ? config : new Promise(resolve => { const data = getToken(); if (data) { config.headers["Authorization"] = data.token; resolve(config); } else { resolve(config); } }); }, error => { return Promise.reject(error); } ); }
/** 请求拦截 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/http/index.ts#L59-L91
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
PureHttp.httpInterceptorsResponse
private httpInterceptorsResponse(): void { const instance = PureHttp.axiosInstance; instance.interceptors.response.use( (response: PureHttpResponse) => { const $config = response.config; // 关闭进度条动画 NProgress.done(); // 优先判断post/get等方法是否传入回掉,否则执行初始化设置等回掉 if (typeof $config.beforeResponseCallback === "function") { $config.beforeResponseCallback(response); return response.data; } if (PureHttp.initConfig.beforeResponseCallback) { PureHttp.initConfig.beforeResponseCallback(response); return response.data; } return response.data; }, (error: PureHttpError) => { const $error = error; $error.isCancelRequest = Axios.isCancel($error); // 关闭进度条动画 NProgress.done(); const { data, status } = error.response; // 消息提示 switch (status + "") { case "403": message(data.message, { type: "error" }); break; case "404": router.push("/error/404"); break; case "500": message(data.message, { type: "error" }); break; default: return; } // 所有的响应异常 区分来源为取消请求/非取消请求 return Promise.resolve($error); } ); }
/** 响应拦截 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/http/index.ts#L94-L138
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
PureHttp.request
public request<T>( method: RequestMethods, url: string, param?: AxiosRequestConfig, axiosConfig?: PureHttpRequestConfig ): Promise<T> { const config = { method, url, ...param, ...axiosConfig } as PureHttpRequestConfig; // 单独处理自定义请求/响应回掉 return new Promise((resolve, reject) => { PureHttp.axiosInstance .request(config) .then((response: undefined) => { resolve(response); }) .catch(error => { reject(error); }); }); }
/** 通用请求工具函数 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/http/index.ts#L141-L165
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
PureHttp.post
public post<T, P>( url: string, params?: AxiosRequestConfig<T>, config?: PureHttpRequestConfig ): Promise<P> { return this.request<P>("post", url, params, config); }
/** 单独抽离的post工具函数 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/http/index.ts#L168-L174
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
PureHttp.get
public get<T, P>( url: string, params?: AxiosRequestConfig<T>, config?: PureHttpRequestConfig ): Promise<P> { return this.request<P>("get", url, params, config); }
/** 单独抽离的get工具函数 */
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/utils/http/index.ts#L177-L183
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
publish
async function publish(formEl) { if (!formEl) return; if (!canPublish.value) { message("文章标题重复,换个标题试试", { type: "warning" }); return; } await formEl.validate(valid => { if (valid) { dialogVisible.value = true; } else { message("请按照提示填写信息", { type: "warning" }); } }); }
// 发布文章 打开弹窗
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L118-L131
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
uploadCover
async function uploadCover() { if (!articleForm.coverList[0].id) { const upLoadLoading = ElLoading.service({ fullscreen: true, text: "图片上传中" }); const res = await imgUpload(articleForm.coverList[0]); if (res.code == 0) { const { url } = res.result; articleForm.article_cover = url; } upLoadLoading.close(); } }
// 图片上传
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L133-L146
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
uploadImage
async function uploadImage(files, callback) { const res = await Promise.all( files.map(file => { return new Promise((resolve, reject) => { mdImgUpload(file).then(imgData => { if (imgData.code == 0) { const { url } = imgData.result; resolve(url); } else { reject(imgData.message || "上传失败"); } }); }); }) ); callback(res); }
// 上传md文章图片
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L160-L177
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
arrangeArticle
function arrangeArticle(articleForm) { const { id, category_id, tagIdList, ...restArticle } = articleForm; let newCategory; const newTagList = []; // 当创建新的分类或者是标签时 类型是string而id是number if (typeof category_id == "number") { newCategory = categoryOptionList.value.find( category => (category.id = category_id) ); } else { newCategory = { category_name: category_id }; } tagIdList.forEach(tagId => { if (typeof tagId == "number") { newTagList.push(tagOptionList.value.find(tag => tag.id == tagId)); } else { newTagList.push({ tag_name: tagId }); } }); restArticle.category = newCategory; restArticle.tagList = newTagList; if (id) { restArticle.id = id; } // 谁发布的 if (!id) { restArticle.author_id = userId ? userId : 1; } if (restArticle.type == 1) { restArticle.origin_url = null; } return restArticle; }
// 整理文章的数据返回给后端
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L180-L218
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
submitForm
async function submitForm(formEl, type) { await formEl.validate(async valid => { if (valid) { // 图片上传 await uploadCover(); if (type == 1) { // 1 是保存草稿 2 是直接发布 articleForm.status = 3; } if (articleForm.is_top == 2) { articleForm.order = null; } // 整合数据 const finalArticle = arrangeArticle(articleForm); let res; if (!finalArticle.id) { // 新增 res = await addArticle(finalArticle); } else { // 编辑 res = await editArticle(finalArticle); } if (res.code == 0) { message(res.message, { type: "success" }); resetForm(formEl.value); resetForm(articleFormRef.value); dialogVisible.value = false; setTimeout(() => { router.push("/article/articleList"); }, 300); } } else { message("请按照提示填写信息", { type: "warning" }); } }); }
// 发布
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L221-L258
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
getTagD
async function getTagD() { const res = await getTagDictionary(); if (res.code == 0) { tagOptionList.value = res.result; } }
// 获取标签列表
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L261-L266
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
getCategoryD
async function getCategoryD() { const res = await getCategoryDictionary(); if (res.code == 0) { categoryOptionList.value = res.result; } }
// 获取分类列表
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L268-L273
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
getArticleDetailsById
async function getArticleDetailsById(article_id) { const res = await getArticleById(article_id); if (res.code == 0) { const { article_cover } = res.result; Object.assign(articleForm, res.result); articleForm.coverList = [ { // 获取数组最后一位有很多种方法 article_cover.split('/').reverse()[0] // article_cover.split('/').slice(-1) // article_cover.split('/').at(-1) id: 1, name: article_cover.split("/").pop(), url: article_cover } ]; } }
// 根据id获取文章详情
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/add-edit-article/index.ts#L275-L292
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
tabChange
const tabChange = (val: any) => { param.status = val.index ? Number(val.index) : null; pageGetArticleList(); };
// tabChange
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L146-L149
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
onSearch
function onSearch() { pageGetArticleList(); }
// 搜
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L151-L153
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
resetParam
const resetParam = () => { Object.assign(param, primaryParam); pageGetArticleList(); };
// 重置参数
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L156-L159
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
changeTop
async function changeTop(val) { if (val) { const { id, is_top } = val; const res = await updateArticleTop(id, is_top); if (res.code == 0) { message(`${is_top == 1 ? "置顶" : "取消置顶"} 成功`, { type: "success" }); } } }
// 修改文章置顶信息
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L162-L172
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
revertArticleById
async function revertArticleById(id, article_title) { if (id) { const res = await revertArticle(id); if (res.code == 0) { message(`恢复文章 ${article_title}成功`, { type: "success" }); } pageGetArticleList(); } }
// 恢复文章
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L175-L183
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
changeArticlePublic
async function changeArticlePublic(id, status) { const res = await isArticlePublic(id, status); if (res.code == 0) { message(`${status == 1 ? "隐藏" : "公开"} 文章成功`, { type: "success" }); } pageGetArticleList(); }
// 公开隐藏文章
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L185-L191
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
deleteArticleById
async function deleteArticleById(id, status, article_title) { const res = await deleteArticle(id, status); if (res.code == 0) { if (status == 3) { message(`删除文章 ${article_title}成功`, { type: "success" }); } else { message(`文章 ${article_title}已进入回收站`, { type: "success" }); } pageGetArticleList(); } }
// 通过id删除文章
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L213-L223
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
pageGetArticleList
async function pageGetArticleList() { loading.value = true; const res = await getArticleList(param); if (res.code == 0) { tableData.value = res.result.list; pagination.total = res.result.total; tableImageList.value = []; tableImageList.value = tableData.value.map(v => { return v.article_cover; }); } loading.value = false; }
// 分页获取文章
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/article/article-manage/index.tsx#L226-L239
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
approveBatch
function approveBatch(type = "batch", row?) { if (type == "single") { if (row.id) { ElMessageBox.confirm("确认审核通过?", "提示", { confirmButtonText: "确认", cancelButtonText: "取消" }).then(async () => { const list = [row.id]; const res = await approveLinks({ idList: list }); if (res.code == 0) { message(`审核友链成功`, { type: "success" }); getPageLinksList(); } }); } } else if (type == "batch") { if (selectList.value.length) { ElMessageBox.confirm("确认审核通过?", "提示", { confirmButtonText: "确认", cancelButtonText: "取消" }).then(async () => { const list = selectList.value.map(se => se.id); const res = await approveLinks({ idList: list }); if (res.code == 0) { message(`批量审核友链成功`, { type: "success" }); getPageLinksList(); } }); } else { message("请先选择友链", { type: "warning" }); } } }
// 批量审核友链
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/links/index.ts#L168-L200
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
deleteBatch
function deleteBatch() { if (selectList.value.length) { ElMessageBox.confirm("确认删除?", "提示", { confirmButtonText: "确认", cancelButtonText: "取消" }).then(async () => { const list = selectList.value.map(se => se.id); const res = await deleteLinks({ idList: list }); if (res.code == 0) { message(`批量删除友链成功`, { type: "success" }); getPageLinksList(); } }); } else { message("请先选择友链", { type: "warning" }); } }
// 批量删除友链接
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/links/index.ts#L203-L219
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
deleteBatch
function deleteBatch() { if (selectList.value.length) { ElMessageBox.confirm("确认删除?", "提示", { confirmButtonText: "确认", cancelButtonText: "取消" }).then(async () => { const list = selectList.value.map(se => se.id); const res = await deleteMessage({ idList: list }); console.log(res); if (res.code == 0) { message(`批量删除留言成功`, { type: "success" }); getPageMessageList(); } }); } else { message("请先选择留言", { type: "warning" }); } }
// 批量删除留言接
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/message/index.ts#L109-L127
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
save
async function save(type, formRef) { await formRef.validate(async valid => { if (valid) { switch (type) { case "info": await updateMyInfo(); isEditMyInfo.value = false; break; case "psd": isEditPassword.value = false; updatePassword(); break; default: return; } } }); }
// 控制编辑与保存
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/personal/index.ts#L66-L83
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
initMyInfo
async function initMyInfo() { const res = await getUserInfoById(useUserStoreHook().getUserId); if (res.code == 0) { const { avatar, nick_name } = res.result; if (useUserStoreHook()?.getNickName != nick_name) { useUserStoreHook()?.SET_NICKNAME(nick_name); storageSession().setItem<userInfoType>("blogCurrentUser", { nick_name, avatar }); } if (useUserStoreHook()?.getAvatar != avatar) { useUserStoreHook()?.SET_AVATAR(avatar); storageSession().setItem<userInfoType>("blogCurrentUser", { nick_name, avatar }); } Object.assign(myInfoForm, res.result); if (avatar) { myInfoForm.avatarList = [ { id: 1, name: avatar.split("/").slice(-1), url: avatar } ]; } Object.assign(primaryMyInfoForm, deepClone(myInfoForm)); } }
// 初始化我的信息
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/personal/index.ts#L118-L150
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
updateMyInfo
async function updateMyInfo() { if (myInfoForm.avatarList.length && !myInfoForm.avatarList[0].id) { const upLoadLoading = ElLoading.service({ fullscreen: true, text: "图片上传中" }); const imgRes = await imgUpload(myInfoForm.avatarList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; myInfoForm.avatar = url; } upLoadLoading.close(); } if (!myInfoForm.avatarList.length) { myInfoForm.avatar = ""; } const res = await updateUserInfo(myInfoForm); if (res.code == 0) { message("用户修改成功", { type: "success" }); initMyInfo(); } }
// 修改个人信息
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/personal/index.ts#L152-L174
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
updatePassword
async function updatePassword() { const res = await updateUserPassword(passwordForm); if (res.code == 0) { message("密码修改成功,请重新登录", { type: "success" }); useUserStoreHook()?.logOut(); } }
// 修改密码
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/personal/index.ts#L177-L183
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
initConfig
async function initConfig() { const res = await getConfigDetail(); if (res.code == 0) { if (res.result) { const { blog_avatar, avatar_bg, we_chat_link, qq_link, we_chat_group, qq_group, we_chat_pay, ali_pay } = res.result; Object.assign(siteInfoForm, res.result); if (blog_avatar) { siteInfoForm.avatarList = [ { id: 1, name: blog_avatar.split("/").pop() || "未知名称", url: blog_avatar } ]; } if (avatar_bg) { siteInfoForm.bgList = [ { id: 2, name: avatar_bg.split("/").pop() || "未知名称", url: avatar_bg } ]; } if (we_chat_link) { siteInfoForm.weChatCoverList = [ { id: 3, name: we_chat_link.split("/").pop() || "未知名称", url: we_chat_link } ]; } if (qq_link) { siteInfoForm.qqCoverList = [ { id: 4, name: qq_link.split("/").pop() || "未知名称", url: qq_link } ]; } // if (we_chat_group) { siteInfoForm.weChatGroupList = [ { id: 5, name: we_chat_group.split("/").pop() || "未知名称", url: we_chat_group } ]; } if (qq_group) { siteInfoForm.qqGroupList = [ { id: 6, name: qq_group.split("/").pop() || "未知名称", url: qq_group } ]; } if (we_chat_pay) { siteInfoForm.weChatPayGroupList = [ { id: 7, name: we_chat_pay.split("/").pop() || "未知名称", url: we_chat_pay } ]; } if (ali_pay) { siteInfoForm.aliPayGroupList = [ { id: 8, name: ali_pay.split("/").pop() || "未知名称", url: ali_pay } ]; } Object.assign(primaryForm, deepClone(siteInfoForm)); } } }
// 初始化网站设置
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/site/index.tsx#L93-L184
dab914ac92f37eaf15520b79718d687eab71b7af
vue3-blog
github_2023
Peerless-man
typescript
updateSiteConfig
async function updateSiteConfig() { loading.value = true; const imgUploading = ElLoading.service({ fullscreen: true, text: "图片上传中......" }); // 先上传图片 if (siteInfoForm.bgList.length && !siteInfoForm.bgList[0].id) { const imgRes = await imgUpload(siteInfoForm.bgList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.avatar_bg = url; } } if (siteInfoForm.avatarList.length && !siteInfoForm.avatarList[0].id) { const imgRes = await imgUpload(siteInfoForm.avatarList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.blog_avatar = url; } } if (siteInfoForm.qqCoverList.length && !siteInfoForm.qqCoverList[0].id) { const imgRes = await imgUpload(siteInfoForm.qqCoverList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.qq_link = url; } } else if (siteInfoForm.qqCoverList.length == 0) { siteInfoForm.qq_link = ""; } if ( siteInfoForm.weChatCoverList.length && !siteInfoForm.weChatCoverList[0].id ) { const imgRes = await imgUpload(siteInfoForm.weChatCoverList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.we_chat_link = url; } } else if (siteInfoForm.weChatCoverList.length == 0) { siteInfoForm.we_chat_link = ""; } if ( siteInfoForm.weChatGroupList.length && !siteInfoForm.weChatGroupList[0].id ) { const imgRes = await imgUpload(siteInfoForm.weChatGroupList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.we_chat_group = url; } } else if (siteInfoForm.weChatGroupList.length == 0) { siteInfoForm.we_chat_group = ""; } if (siteInfoForm.qqGroupList.length && !siteInfoForm.qqGroupList[0].id) { const imgRes = await imgUpload(siteInfoForm.qqGroupList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.qq_group = url; } } else if (siteInfoForm.qqGroupList.length == 0) { siteInfoForm.qq_group = ""; } if ( siteInfoForm.weChatPayGroupList.length && !siteInfoForm.weChatPayGroupList[0].id ) { const imgRes = await imgUpload(siteInfoForm.weChatPayGroupList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.we_chat_pay = url; } } else if (siteInfoForm.weChatPayGroupList.length == 0) { siteInfoForm.we_chat_pay = ""; } if ( siteInfoForm.aliPayGroupList.length && !siteInfoForm.aliPayGroupList[0].id ) { const imgRes = await imgUpload(siteInfoForm.aliPayGroupList[0]); if (imgRes.code == 0) { const { url } = imgRes.result; siteInfoForm.ali_pay = url; } } else if (siteInfoForm.aliPayGroupList.length == 0) { siteInfoForm.ali_pay = ""; } imgUploading.close(); const res = await updateConfigDetail(siteInfoForm); if (res.code == 0) { message("网站设置修改成功", { type: "success" }); initConfig(); } loading.value = false; }
// 修改网站设置
https://github.com/Peerless-man/vue3-blog/blob/dab914ac92f37eaf15520b79718d687eab71b7af/blog-v3-admin/src/views/site/index.tsx#L186-L284
dab914ac92f37eaf15520b79718d687eab71b7af
chat-with-page
github_2023
Fuzzy-Search
typescript
EmbeddingIndex.constructor
constructor(initialObjects?: { [key: string]: any }[]) { this.objects = []; this.keys = []; if (initialObjects && initialObjects.length > 0) { initialObjects.forEach((obj) => this.validateAndAdd(obj)); if (initialObjects[0]) { this.keys = Object.keys(initialObjects[0]); } } }
// TODO: add support for options while creating index such as {... indexedDB: true, ...}
https://github.com/Fuzzy-Search/chat-with-page/blob/293a92fb040431eb06d88d12bbbafe5ed74dfc43/chatwithpage-extension/src/cvs/index.ts#L145-L154
293a92fb040431eb06d88d12bbbafe5ed74dfc43
chat-with-page
github_2023
Fuzzy-Search
typescript
EmbeddingIndex.update
update(filter: { [key: string]: any }, vector: { [key: string]: any }) { // Find the index of the vector with the given filter const index = this.objects.findIndex((object) => Object.keys(filter).every((key) => object[key] === filter[key]), ); if (index === -1) { throw new Error('Vector not found'); } // Validate and add the new vector this.validateAndAdd(vector); // Replace the old vector with the new one this.objects[index] = vector; }
// Method to update an existing vector in the index
https://github.com/Fuzzy-Search/chat-with-page/blob/293a92fb040431eb06d88d12bbbafe5ed74dfc43/chatwithpage-extension/src/cvs/index.ts#L177-L189
293a92fb040431eb06d88d12bbbafe5ed74dfc43
chat-with-page
github_2023
Fuzzy-Search
typescript
EmbeddingIndex.remove
remove(filter: { [key: string]: any }) { // Find the index of the vector with the given filter const index = this.objects.findIndex((object) => Object.keys(filter).every((key) => object[key] === filter[key]), ); if (index === -1) { throw new Error('Vector not found'); } // Remove the vector from the index this.objects.splice(index, 1); }
// Method to remove a vector from the index
https://github.com/Fuzzy-Search/chat-with-page/blob/293a92fb040431eb06d88d12bbbafe5ed74dfc43/chatwithpage-extension/src/cvs/index.ts#L192-L202
293a92fb040431eb06d88d12bbbafe5ed74dfc43
chat-with-page
github_2023
Fuzzy-Search
typescript
EmbeddingIndex.removeBatch
removeBatch(filters: { [key: string]: any }[]) { filters.forEach((filter) => { // Find the index of the vector with the given filter const index = this.objects.findIndex((object) => Object.keys(filter).every((key) => object[key] === filter[key]), ); if (index !== -1) { // Remove the vector from the index this.objects.splice(index, 1); } }); }
// Method to remove multiple vectors from the index
https://github.com/Fuzzy-Search/chat-with-page/blob/293a92fb040431eb06d88d12bbbafe5ed74dfc43/chatwithpage-extension/src/cvs/index.ts#L205-L216
293a92fb040431eb06d88d12bbbafe5ed74dfc43
chat-with-page
github_2023
Fuzzy-Search
typescript
EmbeddingIndex.get
get(filter: { [key: string]: any }) { // Find the vector with the given filter const vector = this.objects.find((object) => Object.keys(filter).every((key) => object[key] === filter[key]), ); if (!vector) { return null; } // Return the vector return vector; }
// Method to retrieve a vector from the index
https://github.com/Fuzzy-Search/chat-with-page/blob/293a92fb040431eb06d88d12bbbafe5ed74dfc43/chatwithpage-extension/src/cvs/index.ts#L219-L229
293a92fb040431eb06d88d12bbbafe5ed74dfc43
Employee--management-app
github_2023
chaniBenziman
typescript
AllEmployeesComponent.editEmployee
editEmployee(employee:Employee){ this.router.navigate(["/editEmployee", employee.employeeId]); }
// }
https://github.com/chaniBenziman/Employee--management-app/blob/424e1c42c48829a551d036206c36d650b604c654/EmployeesManagementClient/src/app/employee/all-employees/all-employees.component.ts#L81-L83
424e1c42c48829a551d036206c36d650b604c654
Employee--management-app
github_2023
chaniBenziman
typescript
s2ab
function s2ab(s: any) { const buf = new ArrayBuffer(s.length); const view = new Uint8Array(buf); for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; }
// Function to save the Excel file
https://github.com/chaniBenziman/Employee--management-app/blob/424e1c42c48829a551d036206c36d650b604c654/EmployeesManagementClient/src/app/employee/all-employees/all-employees.component.ts#L114-L119
424e1c42c48829a551d036206c36d650b604c654
cleanslate
github_2023
successible
typescript
calculatePerFood
const calculatePerFood = ( food: Food, amount: number, unit: Unit, perGram: number | null, perTbsp: number | null, countToGram: number | null, perCount: number | null, countToTbsp: number | null, servingPerContainer: number | null ) => { // Purely for error logging purposes const data = { amount, countToGram, countToTbsp, food, perCount, perGram, perTbsp, servingPerContainer, unit, } if (unit === 'GRAM') { if (countToGram && (perCount || perCount === 0)) { return (amount / countToGram) * perCount } else { return amount * (perGram || 0) } } else if (volumeUnits.includes(unit)) { const tbsp = mapOtherVolumeUnitToTbsp(unit, amount) if ((perCount || perCount === 0) && countToTbsp) { return (tbsp / countToTbsp) * perCount } else { return tbsp * (perTbsp as number) } } else if (unit === 'OZ' || unit === 'LBS') { const grams = convertFromWeightToGrams(unit, amount) if (countToGram && (perCount || perCount === 0)) { return (grams / countToGram) * perCount } else { return grams * (perGram || 0) } } else { const countToUse = unit === 'CONTAINER' && servingPerContainer ? amount * servingPerContainer : amount // The unit MUST be COUNT or CONTAINER // The classic: slice of cheese is 30 grams (countToGram) * calories per gram of cheese * amount of slices if ((countToGram || countToGram === 0) && (perGram || perGram === 0)) { return countToUse * countToGram * perGram } { return countToUse * (perCount || 0) } } }
/** This function calculates the calories/protein in a single food, given a log */
https://github.com/successible/cleanslate/blob/d42527839b00d9637edb433863a35de3bd25599b/src/components/macros/helpers/calculateMacros.ts#L32-L88
d42527839b00d9637edb433863a35de3bd25599b
cleanslate
github_2023
successible
typescript
recurse
const recurse = (dummyFoods: DummyFoods, path: string[] = []) => { for (const [key, value] of Object.entries(dummyFoods)) { // Guard: Make sure it is not a category if (Array.isArray(value)) { leaves[value[0]] = path[0] } else { recurse(value, [...path, key]) } } }
// The recursive function
https://github.com/successible/cleanslate/blob/d42527839b00d9637edb433863a35de3bd25599b/src/components/standard-adder/helpers/getAllDummyFoodLeaves.ts#L9-L18
d42527839b00d9637edb433863a35de3bd25599b
cleanslate
github_2023
successible
typescript
Food.constructor
constructor() { this.name = 'Chicken' this.group = 'Protein' this.category = 'Chicken' this.type = 'food' this.isDummy = false }
// For AllFoodItem
https://github.com/successible/cleanslate/blob/d42527839b00d9637edb433863a35de3bd25599b/src/models/food.ts#L51-L57
d42527839b00d9637edb433863a35de3bd25599b
cleanslate
github_2023
successible
typescript
Recipe.constructor
constructor() { this.type = 'recipe' this.ingredients = [] as Ingredient[] }
// For dynamically created DummyFoods, like Pasta
https://github.com/successible/cleanslate/blob/d42527839b00d9637edb433863a35de3bd25599b/src/models/recipe.ts#L40-L43
d42527839b00d9637edb433863a35de3bd25599b
opengpts
github_2023
langchain-ai
typescript
isObject
const isObject = (item: unknown): item is Record<string, unknown> => { return ( typeof item === "object" && item !== null && item.toString() === {}.toString() ); };
/** * check whether item is plain object * @param {*} item * @return {Boolean} */
https://github.com/langchain-ai/opengpts/blob/2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec/frontend/src/utils/defaults.ts#L14-L20
2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec
opengpts
github_2023
langchain-ai
typescript
cloneJSON
const cloneJSON = (source: any): any => { return JSON.parse(JSON.stringify(source)); };
/** * deep JSON object clone * * @param {Object} source * @return {Object} */
https://github.com/langchain-ai/opengpts/blob/2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec/frontend/src/utils/defaults.ts#L28-L30
2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec
opengpts
github_2023
langchain-ai
typescript
merge
const merge = ( target: Record<string, unknown>, source: Record<string, unknown>, ) => { target = cloneJSON(target); for (const key in source) { if (source.hasOwnProperty(key)) { const sourceKeyValue = source[key]; const targetKeyValue = target[key]; if (isObject(sourceKeyValue) && isObject(targetKeyValue)) { target[key] = merge(targetKeyValue, sourceKeyValue); } else { target[key] = sourceKeyValue; } } } return target; };
/** * returns a result of deep merge of two objects * * @param {Object} target * @param {Object} source * @return {Object} */
https://github.com/langchain-ai/opengpts/blob/2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec/frontend/src/utils/defaults.ts#L39-L58
2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec
opengpts
github_2023
langchain-ai
typescript
defaults
const defaults = (schema: any, definitions: Record<string, any>): unknown => { if (typeof schema["default"] !== "undefined") { return schema["default"]; } else if (typeof schema.allOf !== "undefined") { const mergedItem = mergeAllOf(schema.allOf, definitions); return defaults(mergedItem, definitions); } else if (typeof schema.$ref !== "undefined") { const reference = getLocalRef(schema.$ref, definitions); return defaults(reference, definitions); } else if (schema.type === "object") { if (!schema.properties) { return {}; } for (const key in schema.properties) { if (schema.properties.hasOwnProperty(key)) { schema.properties[key] = defaults(schema.properties[key], definitions); if (typeof schema.properties[key] === "undefined") { delete schema.properties[key]; } } } return schema.properties; } else if (schema.type === "array") { if (!schema.items) { return []; } // minimum item count const ct = schema.minItems || 0; // tuple-typed arrays if (schema.items.constructor === Array) { const values = schema.items.map((item: unknown) => defaults(item, definitions), ); // remove undefined items at the end (unless required by minItems) for (let i = values.length - 1; i >= 0; i--) { if (typeof values[i] !== "undefined") { break; } if (i + 1 > ct) { values.pop(); } } // if all values are undefined -> return undefined even // if minItems is set if (values.every((item: unknown) => typeof item === "undefined")) { return undefined; } return values; } // object-typed arrays const value = defaults(schema.items, definitions); if (typeof value === "undefined") { return []; } else { const values = []; for (let i = 0; i < Math.max(1, ct); i++) { values.push(cloneJSON(value)); } return values; } } };
/** * returns a object that built with default values from json schema * * @param {Object} schema * @param {Object} definitions * @return {Object} */
https://github.com/langchain-ai/opengpts/blob/2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec/frontend/src/utils/defaults.ts#L129-L200
2cf3bf75e11eecbbf3ae4c04a0f73f6ac5d9d6ec
next-shadcn-dashboard-starter
github_2023
Kiranism
typescript
reload
const reload = () => { startTransition(() => { router.refresh(); reset(); }); };
// the reload fn ensures the refresh is deffered until the next render phase allowing react to handle any pending states before processing
https://github.com/Kiranism/next-shadcn-dashboard-starter/blob/cd10b1399eb0641c534625bf5ec1d7bd08c88bae/src/app/dashboard/overview/@bar_stats/error.tsx#L18-L23
cd10b1399eb0641c534625bf5ec1d7bd08c88bae
next-shadcn-dashboard-starter
github_2023
Kiranism
typescript
useCallbackRef
function useCallbackRef<T extends (...args: never[]) => unknown>( callback: T | undefined ): T { const callbackRef = React.useRef(callback); React.useEffect(() => { callbackRef.current = callback; }); // https://github.com/facebook/react/issues/19240 return React.useMemo( () => ((...args) => callbackRef.current?.(...args)) as T, [] ); }
/** * @see https://github.com/radix-ui/primitives/blob/main/packages/react/use-callback-ref/src/useCallbackRef.tsx */
https://github.com/Kiranism/next-shadcn-dashboard-starter/blob/cd10b1399eb0641c534625bf5ec1d7bd08c88bae/src/hooks/use-callback-ref.tsx#L11-L25
cd10b1399eb0641c534625bf5ec1d7bd08c88bae
xiaoju-survey
github_2023
didi
typescript
startServerAndRunScript
async function startServerAndRunScript() { // 启动 MongoDB 内存服务器 const mongod = await MongoMemoryServer.create(); const mongoUri = mongod.getUri(); console.log('MongoDB Memory Server started:', mongoUri); // const redisServer = new RedisMemoryServer(); // const redisHost = await redisServer.getHost(); // const redisPort = await redisServer.getPort(); // 通过 spawn 运行另一个脚本,并传递 MongoDB 连接 URL 作为环境变量 const tsnode = spawn( 'cross-env', [ `XIAOJU_SURVEY_MONGO_URL=${mongoUri}`, // `XIAOJU_SURVEY_REDIS_HOST=${redisHost}`, // `XIAOJU_SURVEY_REDIS_PORT=${redisPort}`, 'NODE_ENV=development', 'SERVER_ENV=local', 'npm', 'run', 'start:dev', ], { stdio: 'inherit', shell: process.platform === 'win32', }, ); tsnode.stdout?.on('data', (data) => { console.log(data.toString()); }); tsnode.stderr?.on('data', (data) => { console.error(data); }); tsnode.on('close', async (code) => { console.log(`Nodemon process exited with code ${code}`); await mongod.stop(); // 停止 MongoDB 内存服务器 // await redisServer.stop(); }); }
// import { RedisMemoryServer } from 'redis-memory-server';
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/server/scripts/run-local.ts#L5-L47
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
WorkspaceService.findAllByUserId
async findAllByUserId(userId: string) { return await this.workspaceRepository.find({ where: { ownerId: userId, isDeleted: { $ne: true, }, }, order: { _id: -1, }, select: [ '_id', 'curStatus', 'name', 'description', 'ownerId', 'createdAt', ], }); }
// 用户下的所有空间
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/server/src/modules/workspace/services/workspace.service.ts#L165-L185
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
WorkspaceMemberService.batchSearchByWorkspace
async batchSearchByWorkspace(workspaceList: string[]) { return await this.workspaceMemberRepository.find({ where: { workspaceId: { $in: workspaceList, }, }, order: { _id: -1, }, select: ['_id', 'userId', 'role', 'workspaceId'], }); }
// 根据空间id批量查询成员
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/server/src/modules/workspace/services/workspaceMember.service.ts#L163-L175
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
PluginManager.registerPlugin
registerPlugin(...plugins: Array<SecurityPlugin>) { this.plugins.push(...plugins); }
// 注册插件
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/server/src/securityPlugin/pluginManager.ts#L12-L14
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
PluginManager.triggerHook
async triggerHook(hookName: AllowHooks, data?: any) { for (const plugin of this.plugins) { if (plugin[hookName]) { return await plugin[hookName](data); } } }
// 触发钩子
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/server/src/securityPlugin/pluginManager.ts#L17-L23
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
isPhone
const isPhone = (data: string) => phoneRegex.test(data);
// 性别
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/server/src/securityPlugin/responseSecurityPlugin/utils.ts#L10-L10
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleBuild.addRule
addRule(rule: RuleNode) { this.rules.push(rule) }
// 添加条件规则到规则引擎中
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RuleBuild.ts#L62-L64
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleBuild.findTargetsByScope
findTargetsByScope(scope: string) { return this.rules.filter((rule) => rule.scope === scope).map((rule) => rule.target) }
// 实现目标选择了下拉框置灰效果
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RuleBuild.ts#L109-L111
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleBuild.findTargetsByField
findTargetsByField(field: string) { const nodes = this.findRulesByField(field) return nodes.map((item: any) => { return item.target }) }
// 实现前置题删除校验
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RuleBuild.ts#L118-L123
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleBuild.findConditionByTarget
findConditionByTarget(target: string) { return this.rules.filter((rule) => rule.target === target).map((item) => item.conditions) }
// 根据目标题获取关联的逻辑条件
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RuleBuild.ts#L125-L127
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
ConditionNode.calculateHash
calculateHash(): string { // 假设哈希值计算方法为简单的字符串拼接或其他哈希算法 return this.field + this.operator + this.value }
// 计算条件规则的哈希值
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L14-L17
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleNode.addCondition
addCondition(condition: ConditionNode<string, Operator>) { const hash = condition.calculateHash() this.conditions.set(hash, condition) }
// 添加条件规则到规则引擎中
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L80-L83
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleNode.match
match(fact: Fact, comparor?: any) { let res: boolean | undefined = undefined if (comparor === 'or') { res = Array.from(this.conditions.entries()).some(([, value]) => { const res = value.match(fact) if (res) { return true } else { return false } }) } else { res = Array.from(this.conditions.entries()).every(([, value]) => { const res = value.match(fact) if (res) { return true } else { return false } }) } this.result = res return res }
// 匹配条件规则
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L86-L110
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleNode.calculateHash
calculateHash(): string { // 假设哈希值计算方法为简单的字符串拼接或其他哈希算法 return this.target + this.scope }
// 计算条件规则的哈希值
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L120-L123
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.constructor
constructor() { this.rules = new Map() // if (!RuleMatch.instance) { // RuleMatch.instance = this // } // return RuleMatch.instance }
// static instance: any
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L138-L145
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.addRule
addRule(rule: RuleNode) { const hash = rule.calculateHash() if (this.rules.has(hash)) { const existRule: any = this.rules.get(hash) existRule.conditions.forEach((item: ConditionNode<string, Operator>) => { rule.addCondition(item) }) } this.rules.set(hash, rule) }
// 添加条件规则到规则引擎中
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L165-L175
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.match
match(target: string, scope: string, fact: Fact, comparor?: any) { const hash = this.calculateHash(target, scope) const rule = this.rules.get(hash) if (rule) { const result = rule.match(fact, comparor) return result } else { // 默认显示 return true } }
// 特定目标题规则匹配
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L178-L189
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.getResultsByField
getResultsByField(field: string, fact: Fact) { const rules = this.findRulesByField(field) return rules.map(([, rule]) => { return { target: rule.target, result: this.match(rule.target, 'question', fact, 'or') } }) }
/* 获取条件题关联的多个目标题匹配情况 */
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L191-L199
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.getResultByTarget
getResultByTarget(target: string, scope: string) { const hash = this.calculateHash(target, scope) const rule = this.rules.get(hash) if (rule) { const result = rule.getResult() return result } else { // 默认显示 return true } }
/* 获取目标题的规则是否匹配 */
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L201-L211
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.calculateHash
calculateHash(target: string, scope: string): string { // 假设哈希值计算方法为简单的字符串拼接或其他哈希算法 return target + scope }
// 计算哈希值的方法
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L213-L216
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
RuleMatch.findRulesByField
findRulesByField(field: string) { const list = [...this.rules.entries()] const match = list.filter(([, ruleValue]) => { const list = [...ruleValue.conditions.entries()] const res = list.filter(([, conditionValue]) => { const hit = conditionValue.field === field return hit }) return res.length }) return match }
// 查找条件题的规则
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/common/logicEngine/RulesMatch.ts#L218-L229
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
compareQuestionSeq
const compareQuestionSeq = (val: Array<any>) => { const newSeq: Array<string> = [] const oldSeq: Array<string> = [] let status = false for (const v of val) { newSeq.push(v.field) } for (const v of questionDataList.value as Array<any>) { oldSeq.push(v.field) } for (let index = 0; index < newSeq.length; index++) { if (newSeq[index] !== oldSeq[index]) { status = true break } } if (status) { setQuestionDataList(val) } }
// 题目大纲移动题目顺序
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/edit.ts#L64-L83
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
moveQuestionDataList
function moveQuestionDataList(data: any) { const { startIndex, endIndex } = getSorter() const newData = [ ...questionDataList.value.slice(0, startIndex), ...data, ...questionDataList.value.slice(endIndex) ] const countTotal: number = (schema.pageConf as Array<number>).reduce( (v: number, i: number) => v + i ) if (countTotal != newData.length) { schema.pageConf[pageEditOne.value - 1] = (schema.pageConf[pageEditOne.value - 1] + 1) as never } setQuestionDataList(newData) }
// 画布区域移动题目顺序
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/edit.ts#L86-L100
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
createNewQuestion
const createNewQuestion = ({ type }: { type: QUESTION_TYPE }) => { const fields = questionDataList.value.map((item: any) => item.field) const newQuestion = getQuestionByType(type, fields) newQuestion.title = newQuestion.title = `标题${newQuestionIndex.value + 1}` if (type === QUESTION_TYPE.VOTE) { newQuestion.innerType = QUESTION_TYPE.RADIO } return newQuestion }
// 增加新分页时新增题目
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/edit.ts#L137-L145
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
initCounts
function initCounts() { resetCount() questionDetailList.value.forEach((question: any) => { calculateCountsForQuestion('INIT', { question }) }) updateGlobalBaseConf() }
// 初始化统计
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/composables/useBaseConfig.ts#L33-L39
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
updateCounts
function updateCounts(type: TypeMethod, data: any) { if (type === 'MODIFY') { calculateOptionCounts(type, data) } else { calculateCountsForQuestion(type, data) } updateGlobalBaseConf() }
// 更新统计
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/composables/useBaseConfig.ts#L42-L49
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
calculateCountsForQuestion
function calculateCountsForQuestion(type: TypeMethod, { question }: any) { Object.keys(globalBaseConfig).forEach((key) => { calculateOptionCounts(type, { key, value: question[key] }) }) }
// 计算整卷配置各项选项选中个数
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/composables/useBaseConfig.ts#L52-L56
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
calculateOptionCounts
function calculateOptionCounts(type: TypeMethod, { key, value }: any) { const _key = `${key}Count` as keyof typeof optionCheckedCounts if (value) { if (type === 'REMOVE') optionCheckedCounts[_key]-- else optionCheckedCounts[_key]++ } else { if (type === 'MODIFY') optionCheckedCounts[_key]-- } }
// 计算单个选项选中个数
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/composables/useBaseConfig.ts#L59-L67
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
updateGlobalBaseConf
function updateGlobalBaseConf() { const len = questionDetailList.value.length const { isRequiredCount, showIndexCount, showSpliterCount, showTypeCount } = optionCheckedCounts Object.assign(globalBaseConfig, { isRequired: isRequiredCount === len, showIndex: showIndexCount === len, showSpliter: showSpliterCount === len, showType: showTypeCount === len }) }
// 更新整卷配置状态
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/composables/useBaseConfig.ts#L70-L79
28098cfdb2d1121070af537c6cbebe085a2c0fa3
xiaoju-survey
github_2023
didi
typescript
updateGlobalConfOption
function updateGlobalConfOption({ key, value }: { key: string; value: boolean }) { const len = questionDetailList.value.length const _key = `${key}Count` as keyof typeof optionCheckedCounts if (value) optionCheckedCounts[_key] = len else optionCheckedCounts[_key] = 0 questionDetailList.value.forEach((question: any) => { question[key] = value }) updateTime() }
// 整卷配置修改
https://github.com/didi/xiaoju-survey/blob/28098cfdb2d1121070af537c6cbebe085a2c0fa3/web/src/management/stores/composables/useBaseConfig.ts#L82-L91
28098cfdb2d1121070af537c6cbebe085a2c0fa3
coffee
github_2023
Coframe
typescript
cn
const cn = (...classes: (string | undefined | false)[]) => classes.filter(Boolean).join(' ')
// A utility function to concatenate class names (handles falsy values as well)
https://github.com/Coframe/coffee/blob/8ac3cf4156b9d2a800defcbcdb61901cdd30e92d/_roastery/shadcn_ui_app/components/ui/card.tsx#L4-L4
8ac3cf4156b9d2a800defcbcdb61901cdd30e92d
gsplat.js
github_2023
huggingface
typescript
frame
const frame = () => { controls.update(); renderer.render(scene, camera); requestAnimationFrame(frame); };
// Render loop
https://github.com/huggingface/gsplat.js/blob/d6df8ec0b8ac3683438cb99fec308e56ca7b14a9/examples/file-loader/src/main.ts#L39-L44
d6df8ec0b8ac3683438cb99fec308e56ca7b14a9
gsplat.js
github_2023
huggingface
typescript
main
async function main() { // Load and convert ply from url const url = "https://huggingface.co/datasets/dylanebert/3dgs/resolve/main/bonsai/point_cloud/iteration_7000/point_cloud.ply"; await SPLAT.PLYLoader.LoadAsync(url, scene, (progress) => (progressIndicator.value = progress * 100), format); progressDialog.close(); scene.saveToFile("bonsai.splat"); // Alternatively, uncomment below to convert from splat to ply // NOTE: Data like SH coefficients will be lost when converting ply -> splat -> ply /* const url = "https://huggingface.co/datasets/dylanebert/3dgs/resolve/main/bonsai/bonsai-7k-mini.splat"; await SPLAT.Loader.LoadAsync(url, scene, (progress) => (progressIndicator.value = progress * 100)); progressDialog.close(); scene.saveToFile("bonsai-7k-mini.ply", "ply"); */ // Render loop const frame = () => { controls.update(); renderer.render(scene, camera); requestAnimationFrame(frame); }; requestAnimationFrame(frame); // Alternatively, load and convert ply from file let loading = false; const selectFile = async (file: File) => { if (loading) return; loading = true; if (file.name.endsWith(".splat")) { await SPLAT.Loader.LoadFromFileAsync(file, scene, (progress: number) => { progressIndicator.value = progress * 100; }); } else if (file.name.endsWith(".ply")) { await SPLAT.PLYLoader.LoadFromFileAsync( file, scene, (progress: number) => { progressIndicator.value = progress * 100; }, format, ); } scene.saveToFile(file.name.replace(".ply", ".splat")); loading = false; }; document.addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); if (e.dataTransfer != null && e.dataTransfer.files.length > 0) { selectFile(e.dataTransfer.files[0]); } }); }
// const format = "polycam"; // Uncomment to use polycam format
https://github.com/huggingface/gsplat.js/blob/d6df8ec0b8ac3683438cb99fec308e56ca7b14a9/examples/ply-converter/src/main.ts#L15-L71
d6df8ec0b8ac3683438cb99fec308e56ca7b14a9
gsplat.js
github_2023
huggingface
typescript
frame
const frame = () => { controls.update(); renderer.render(scene, camera); requestAnimationFrame(frame); };
// Alternatively, uncomment below to convert from splat to ply
https://github.com/huggingface/gsplat.js/blob/d6df8ec0b8ac3683438cb99fec308e56ca7b14a9/examples/ply-converter/src/main.ts#L31-L36
d6df8ec0b8ac3683438cb99fec308e56ca7b14a9
gsplat.js
github_2023
huggingface
typescript
Matrix3.constructor
constructor(n11: number = 1, n12: number = 0, n13: number = 0, n21: number = 0, n22: number = 1, n23: number = 0, n31: number = 0, n32: number = 0, n33: number = 1) { this.buffer = [ n11, n12, n13, n21, n22, n23, n31, n32, n33 ]; }
// prettier-ignore
https://github.com/huggingface/gsplat.js/blob/d6df8ec0b8ac3683438cb99fec308e56ca7b14a9/src/math/Matrix3.ts#L8-L16
d6df8ec0b8ac3683438cb99fec308e56ca7b14a9
gsplat.js
github_2023
huggingface
typescript
Matrix4.constructor
constructor(n11: number = 1, n12: number = 0, n13: number = 0, n14: number = 0, n21: number = 0, n22: number = 1, n23: number = 0, n24: number = 0, n31: number = 0, n32: number = 0, n33: number = 1, n34: number = 0, n41: number = 0, n42: number = 0, n43: number = 0, n44: number = 1) { this.buffer = [ n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ]; }
// prettier-ignore
https://github.com/huggingface/gsplat.js/blob/d6df8ec0b8ac3683438cb99fec308e56ca7b14a9/src/math/Matrix4.ts#L8-L18
d6df8ec0b8ac3683438cb99fec308e56ca7b14a9
gsplat.js
github_2023
huggingface
typescript
ShaderPass.initialize
initialize(program: ShaderProgram) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/huggingface/gsplat.js/blob/d6df8ec0b8ac3683438cb99fec308e56ca7b14a9/src/renderers/webgl/passes/ShaderPass.ts#L5-L5
d6df8ec0b8ac3683438cb99fec308e56ca7b14a9
tsdocs
github_2023
pastelsky
typescript
start
const start = async () => { try { await fastify.listen({ port }); console.log("Server started at ", `http://localhost:${port}`); console.log("Queue UI at ", `http://localhost:${port}/queue/ui`); // For PM2 to know that our server is up if (process.send) process.send("ready"); } catch (err) { console.error("server threw error on startup: ", err); fastify.log.error(err); process.exit(1); } };
// Run the server!
https://github.com/pastelsky/tsdocs/blob/744da56c879c8b4c3ce976089b1b3274eab64fb9/server.ts#L218-L230
744da56c879c8b4c3ce976089b1b3274eab64fb9