repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
workbench
github_2023
yhtt2020
typescript
TUINotification.install
static install(app: any): void { app.use(this.getInstance()); }
/** * 挂载到 vue 实例的上 * * @param {app} app vue的实例 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/TUIKit/TUIPlugin/TUINotification/index.ts#L53-L55
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
TUIi18n.getInstance
static getInstance() { if (!TUIi18n.instance) { TUIi18n.instance = new TUIi18n(messages); } return TUIi18n.instance; }
/** * 获取 TUIi18n 实例 * * @returns {TUIi18n} */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/TUIKit/TUIPlugin/TUIi18n/index.ts#L20-L25
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
TUIi18n.provideMessage
public provideMessage(messages: any) { this.messages.en = { ...this.messages.en, ...messages.en }; this.messages.zh_cn = { ...this.messages.zh_cn, ...messages.zh_cn }; return this.messages; }
/** * 注入需要国际化的词条 * * @param {Object} messages 数据对象 * @returns {messages} 全部国际化词条 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/TUIKit/TUIPlugin/TUIi18n/index.ts#L33-L37
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
TUIi18n.useI18n
public useI18n() { return useI18n(); }
/** * 使用国际化 * * @returns {useI18n} 国际化使用函数 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/TUIKit/TUIPlugin/TUIi18n/index.ts#L44-L46
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
TUIi18n.install
static install(app: any) { const that = TUIi18n.getInstance(); // const lang = navigator.language.substr(0, 2); const lang = 'zh'; that.i18n = createI18n({ legacy: false, // 使用Composition API,这里必须设置为false globalInjection: true, global: true, locale: lang === 'zh' ? 'zh_cn' : lang, fallbackLocale: 'zh_cn', // 默认语言 messages: that.messages, }); app.use(that.i18n); }
/** * 挂载到 vue 实例的上 * * @param {app} app vue的实例 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/TUIKit/TUIPlugin/TUIi18n/index.ts#L53-L66
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
TUIi18n.plugin
static plugin(TUICore:any) { TUICore.config.i18n = TUIi18n.getInstance(); }
/** * 挂载到 TUICore * * @param {TUICore} TUICore TUICore实例 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/TUIKit/TUIPlugin/TUIi18n/index.ts#L73-L75
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
escapeSpecialChars
function escapeSpecialChars(str) { // 定义需要转义的特殊字符 const specialChars = /[.*+?^${}()|[\]\\]/g; // 使用正则表达式替换特殊字符 return str.replace(specialChars, "\\$&"); }
//替换掉特殊字符,保证查询准确性
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/apps/clipboard/store.ts#L91-L97
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
escapeSpecialChars
function escapeSpecialChars(str) { // 定义需要转义的特殊字符 const specialChars = /[.*+?^${}()|[\]\\]/g; // 使用正则表达式替换特殊字符 return str.replace(specialChars, "\\$&"); }
//替换掉特殊字符,保证查询准确性
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/apps/note/store.ts#L512-L517
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Queue.add
add(func, delay) { this.queue.push({ func, delay }); if (!this.isRunning) { this.run(); } }
// 添加任务到采集任务队列
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/apps/queue/queue.ts#L9-L15
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Queue.run
run() { const task = this.queue.shift(); if (task) { task.func(); this.isRunning = true; setTimeout(() => { this.run(); }, task.delay); } else { this.isRunning = false; } }
// 执行采集任务队列中的任务
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/apps/queue/queue.ts#L18-L32
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
getGuide
const getGuide = (id) => { const store: any = taskStore(); const { startList, currentId, claimRewardsList, completedList } = storeToRefs(store); const toast = useToast(); toast.clear(); let config: any = { timeout: 0, }; // console.log( // "completedList.value.includes(id) :>> ", // completedList.value.includes(id) // ); if (completedList.value.includes(id)) { config = { timeout: 3000, hideProgressBar: false }; } toast( { component: Complete, }, { icon: false, closeOnClick: false, closeButton: false, pauseOnFocusLoss: true, pauseOnHover: true, toastClassName: "notice-toast", ...config, } ); };
// 获取指引
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/apps/task/task.ts#L51-L82
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
endTask
const endTask = (id, cb?) => { const store: any = taskStore(); const { startList, currentId, claimRewardsList, completedList } = storeToRefs(store); // 移除开始中的任务 startList.value = [...new Set(startList.value)].filter((item) => item !== id); if (!completedList.value.includes(id)) { claimRewardsList.value.push(id); } // 数据预处理 currentId.value = id; cb && cb(); getGuide(id); };
// 完成后任务后处理
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/apps/task/task.ts#L85-L99
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
compatible
const compatible = () => { const newClassName = getThemeName(THEME_NAME); const oldClassName = getThemeName(OLD_THEME_NAME); // 为了兼容旧版本 const className = newClassName || oldClassName; return className; };
/** * 兼容旧版本处理 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/card/hooks/themeSwitch/index.ts#L67-L72
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
itemStatus
const itemStatus = (item) => { if (!test) return; const { width, height }: any = useElementSize(item.customData.customSize); console.log( "\u001b[31m" + "----------------数据处理开始----------------" + "\u001b[0m" ); console.log( "id :>> ", item?.id, ",name :>> ", item.customData.name || item.name, ",元素width :>> ", width, ",当前位置left :>> ", left - freeLayoutEnv.value.scrollLeft, ",当前位置缩放后left :>> ", left - freeLayoutEnv.value.scrollLeft / scaleFactor, "item", item ); };
// 卡片数据展示
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L40-L62
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
widthDetectionStatus
const widthDetectionStatus = (width, res, active) => { if (!test) return; console.log( "\u001b[31m" + "----------------换行检测----------------" + "\u001b[0m" ); console.log( "当前元素宽度", width, "画布宽度 :>> ", layoutWidth, "当前宽度 :>> ", res, "是否换行 :>> ", active ); };
// 换行数据展示
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L64-L79
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
widthDetection
const widthDetection = (width) => { let res = left - freeLayoutEnv.value.scrollLeft / scaleFactor - position + width; const active = res > layoutWidth + columns; widthDetectionStatus(width, res, active); return active; };
// 检测是否超出
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L81-L88
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
setData
const setData = (arr: any) => { currentHeight = 0; let last = true; let flag = false; for (let item of arr.splice(0, arr.length)) { // 处理元素位置 const { width, height }: any = useElementSize(item.customData.customSize); console.log( "处理元素位置 get item.customData.customSize :>> ", item.customData.customSize ); itemStatus(item); // 元素超出 if (widthDetection(width)) { console.log( "\u001b[31m" + `----------------元素超出${ height - currentHeight }----------------` + "\u001b[0m" ); currentTop = top; // 先填充空缺的数据 fillGapAlgorithm(); // 重置位置 resetLeft(); flag = true; // 增加高度 top += currentHeight + 12; } if (!last && height != currentHeight) { console.log( "\u001b[31m" + `----------------高度不相等${ height - currentHeight }----------------` + "\u001b[0m" ); // 先填充空缺的数据 let res = left - freeLayoutEnv.value.scrollLeft / scaleFactor - position; currentTop += currentHeight + 12; currentHeight = height; console.log("元素超出 get currentHeight :>> ", currentHeight); fillHeight = currentHeight; if (res) { fillGapAlgorithm(); } // 重置位置 resetLeft(); addCard(top, left, item); left += width + 12; } else { addCard(top, left, item); left += width + 12; currentHeight = height; flag = false; } console.log("setData get currentHeight :>> ", currentHeight); fillHeight = currentHeight; if (last) last = false; console.log( "\u001b[34m" + "----------------数据处理结束----------------" + "\u001b[0m" ); } currentTop = top; let res = left - freeLayoutEnv.value.scrollLeft / scaleFactor - position; if (res) { fillGapAlgorithm(); } resetLeft(); fillHeight = 0; top += currentHeight + 12; };
// 设置卡片数据
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L90-L170
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
scaleAlgorithm
const scaleAlgorithm = () => { let currentZoom = getFreeLayoutState.value.canvas.zoom; if (layoutWidth * currentZoom >= containerWidth) { currentZoom = containerWidth / (layoutWidth + 100); // 确保元素在不改变宽高比的前提下缩放至适合容器宽度 getFreeLayoutState.value.canvas.zoom = currentZoom; position = 50; } else { position = (containerWidth / currentZoom - layoutWidth) / 2; } scaleFactor = currentZoom; };
// 获取元素宽度
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L173-L184
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
fillGapAlgorithm
const fillGapAlgorithm = async () => { // 无余数 if (arr2x4.length == 0 && arr2x2.length == 0 && arr1x1.length == 0) return true; // 无位置 let active = widthDetection(134); if (active) { return; } // 可以存放2x4 if (arr2x4.length > 0 && fillHeight - 280 >= 0) { fill(arr2x4); } else if (arr2x2.length > 0) { fill(arr2x2); } else if (arr1x1.length > 0) { fill(arr1x1); } else { return; } fillGapAlgorithm(); };
// 填充算法
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L186-L207
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
fill
const fill = async (arr, height = fillHeight) => { let flag = false; let itemWidth = 280, itemHeight = 204; for (let item of arr.splice(0, 1)) { if (!item) return; const { width, height }: any = useElementSize(item.customData.customSize); itemWidth = width; itemHeight = height; flag = fillHeight - itemHeight < 0; if (flag) { array.push(item); return; } fillHeight -= height; itemStatus(item); addCard(currentTop, left, item); currentTop += height + 12; } if (fillHeight - 96 < 0) { console.log("换列操作 :>> "); currentTop = top; left += itemWidth + 12; fillHeight = currentHeight; } return; };
// 填充实现
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L209-L237
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
addPositioningData
const addPositioningData = () => { return new Promise((resolve, reject) => { let positioningId = addCard(-999, -999, {}); setTimeout(() => { resolve(positioningId); }, 100); // 在100毫秒后返回 }); };
/** * 添加定位数据 * 用于打开自由布局画布 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L380-L387
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
addCard
const addCard = (top, left, item) => { const freeLayoutStore: any = useFreeLayoutStore(); const { getFreeLayoutData, getFreeLayoutState, freeLayoutEnv } = storeToRefs(freeLayoutStore); let id = item?.id || nanoid(4); if (item.name == "news" || item.name == "HotSearch") { console.log("Item.name :>> ", item); } if (item.name == "notes") { id = item?.id || Date.now(); } let a = left; getFreeLayoutData.value[id] = { left: a, top: top, index: 1, id, }; console.log("getFreeLayoutData.value[id]", id, getFreeLayoutData.value[id]); if (item.id) return; useAddCard( item.name, { ...item?.customData, }, id ); return id; };
// 添加卡片
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/desk/freeLayout/useCustomLayout.ts#L389-L425
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
validateFile
const validateFile = (file: any,size?:number) => { size= size ?? 10 const sizeLimit = size * 1024 * 1024 // 设置文件大小上限为10MB const legalExts = [".jpg", ".jpeg", ".png"] // 合法文件扩展名数组 if (file.size > sizeLimit) { // 如果文件大小超过上限,提示错误并返回false return false } const name = file.name.toLowerCase() // 获取文件名并转换为小写 if (!legalExts.some((ext) => name.endsWith(ext))) { // 如果文件扩展名不合法,提示错误并返回false return false } return true // 文件合法,返回true }
/** * 验证文件是否合法,文件大小不超过10MB,扩展名为.jpg、.jpeg或.png * @param file 待验证的文件 * @returns 如果文件合法返回true,否则返回false */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/widgets/clock/hooks/innerImg.ts#L23-L37
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
findData
function findData(params:any){ // console.log('查找条件参数',params); const isRegex = new RegExp(params) const find = expressList.find((item)=>{ return isRegex.test(item.code) }) return find }
// 通过参数进行查找
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/components/widgets/courier/courierModal/utils/courierUtils.ts#L47-L54
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
ActionHandler.doAction
async doAction(): ActionResult { let {action, args} = this let actionCommander: ActionExecutor switch (action.group.name) { case 'sendKeys': actionCommander = new SendKeysAction(action) break case 'browser': actionCommander = new BrowserAction(action) break case 'cmd': actionCommander = new CmdAction(action) break } return await actionCommander.doAction() }
/** * 处理一个指令 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/action/actionHandler.ts#L24-L40
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
emojiReplace
const emojiReplace=(str)=>{ let result = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => { let emojiValue; Object.entries(fluentEmojis).forEach(([key, value]) => { if (key == item) { emojiValue = value; } }); if (emojiValue) { let url = `https://sad.apps.vip/public/static/emoji/emojistatic/${emojiValue}`; return `<img src="${url}" class=" w-[22px] h-[22px]">`; } return item; }); return result; }
// 用于在动态和评论中使用的表情
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/chat/emoji.ts#L55-L73
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
error
function error() { if(onError) onError('获取失败') }
//调用麦克风捕捉音频信息,成功时触发onSuccess函数,失败时触发onError函数
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/audio.ts#L19-L22
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
initCanvas
function initCanvas() { canvas =document.createElement('canvas') canvas.width=CANVAS_WIDTH canvas.height=CANVAS_HEIGHT ctx = canvas.getContext('2d'); ctx.fillStyle='#00000000' // // 解决canvas绘图模糊问题 // canvas.width = CANVAS_WIDTH * dpr // canvas.height = CANVAS_HEIGHT * dpr // ctx.scale(dpr, dpr) }
// 初始化canvas
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/avatar.ts#L78-L88
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
drawImage
function drawImage() { // 背景 ctx.fillStyle = '#00000000' ctx.fillRect(0, 0, canvas.width, canvas.height) // 背景 const backImg = new Image() backImg.setAttribute("crossOrigin",'Anonymous') backImg.src =frame //背景图片 shareBack const backImgLoadPromise = new Promise((resolve) => { backImg.onload = () => { resolve(backImg) } }) // 头像 const userImg = new Image() userImg.setAttribute("crossOrigin",'Anonymous') userImg.src =avatar// 头像图片this.props.userIcon || avatarDefault const userImgLoadPromise = new Promise((resolve) => { userImg.onload = () => { resolve(userImg) } }) return Promise.all([backImgLoadPromise,userImgLoadPromise]).then(res => { return Promise.resolve(res) }) }
// 生成图片
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/avatar.ts#L90-L117
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
drawCricleImg
function drawCricleImg(ctx, url, x, y, width, height){ var avatarurl_width = width; var avatarurl_heigth = height; var avatarurl_x = x; var avatarurl_y = y; ctx.save(); ctx.beginPath(); ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false); ctx.clip(); ctx.drawImage(url, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); ctx.restore(); }
//绘制圆形图片
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/avatar.ts#L120-L131
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
ClipboardObserver.isDiffText
isDiffText(beforeText: string, afterText: string): boolean { return afterText && beforeText !== afterText; }
/** * 判断内容是否不一致 * @param beforeText * @param afterText * @returns */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/clipboardObserver.ts#L88-L90
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
ClipboardObserver.isDiffImage
isDiffImage(beforeImage: any, afterImage: any): boolean { console.log('判断图片') if(!beforeImage){ return false } try{ // let hasAfterImage= afterImage && !afterImage.isEmpty() // if(!hasAfterImage){ // return false // } // let beforeURL=toRaw(beforeImage).toDataURL() // let afterURL= afterImage.toDataURL() // let diff=beforeURL !==afterURL // return diff }catch (e) { console.error('取图失败',e) } }
/** * 判断图片是否不一致 * @param beforeImage * @param afterImage * @returns */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/clipboardObserver.ts#L98-L116
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
isMain
function isMain(){ let sign=getSign() return sign === 'table.com'; }
/** * 判断是不是主屏 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/screenUtils.ts#L16-L19
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.clockToast
public clockToast(msg: any, title: any, changeIcon: any) { toast.info({ component: ClockNoticeToast, props: { content: msg, noticeType: 'notice', isPlay: appStore().$state.settings.noticePlay, title: title, changeIcon: changeIcon }, listeners: { 'nowCheck': function () { appStore().hideNoticeEntry() }, } }, { icon: false, closeOnClick: false, closeButton: false, pauseOnFocusLoss: true, pauseOnHover: true, timeout: 0, toastClassName: 'notice-toast' }) }
// 闹钟的通知
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L38-L57
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.messageWeak
public messageWeak(msg: any, conversationID: any) { const {settings} = storeToRefs(appStore()) noticeStore().putMessageData(msg); toast.info( { component: MessageNoticeToast, props: {msg, type: 'message', play: settings.value.enablePlay}, listeners: { 'putNotice': function () { console.log('关闭并存储数据', msg); }, // 'nowCheck':function(){ // appStore().hideNoticeEntry(); // noticeStore().putMessageData(msg,'message'); // }, 'messageExamine': function () { chatStore().updateConversation(conversationID) appStore().hideNoticeEntry(); router.push({name: 'chatMain'}); (window as any).$TUIKit.TUIServer.TUIConversation.getConversationProfile(conversationID).then((imResponse: any) => { // 通知 TUIConversation 添加当前会话 // Notify TUIConversation to toggle the current conversation (window as any).$TUIKit.TUIServer.TUIConversation.handleCurrentConversation(imResponse.data.conversation); }) } }, }, { icon: false, closeOnClick: false, closeButton: false, pauseOnFocusLoss: true, pauseOnHover: true, timeout: 5000, toastClassName: 'notice-toast', onClose() { }, } ) }
// 消息弱提醒
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L126-L163
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.messageStrong
public messageStrong(msg: any, conversationID: any) { const {settings} = storeToRefs(appStore()) noticeStore().putMessageData(msg); toast.info( { component: SystemNoticeToast, props: {msg, type: 'notice', play: settings.value.noticePlay}, listeners: { 'putNotice': function () { console.log('关闭并存储数据', msg); }, // 'nowCheck':function(){ // appStore().hideNoticeEntry(); // }, 'systemExamine': function () { chatStore().updateConversation(conversationID) router.push({name: 'chatMain'}); (window as any).$TUIKit.TUIServer.TUIConversation.getConversationProfile(conversationID).then((imResponse: any) => { // 通知 TUIConversation 添加当前会话 // Notify TUIConversation to toggle the current conversation (window as any).$TUIKit.TUIServer.TUIConversation.handleCurrentConversation(imResponse.data.conversation); }) } } }, { icon: false, closeOnClick: false, closeButton: false, pauseOnFocusLoss: true, pauseOnHover: true, timeout: 0, toastClassName: 'notice-toast', } ) }
// 消息强提醒
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L166-L199
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.createSoundElement
private createSoundElement(): HTMLAudioElement { let audioElement = document.getElementById('messageAudio') as HTMLAudioElement; if (!audioElement) { audioElement = document.createElement('audio'); audioElement.src = '/sound/message.mp3' audioElement.setAttribute('id', 'messageAudio'); document.body.appendChild(audioElement); } return audioElement; }
// 创建音频播放组件
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L202-L211
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.createSoundStrongElement
private createSoundStrongElement(): HTMLAudioElement { let audioElement = document.getElementById('messageAudio') as HTMLAudioElement; if (!audioElement) { audioElement = document.createElement('audio'); audioElement.src = '/sound/notice.mp3' audioElement.setAttribute('id', 'messageAudio'); document.body.appendChild(audioElement); } return audioElement; }
// 创建音频强提醒
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L214-L223
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.extractNumbersFromString
private extractNumbersFromString(str: any) { const regex = /\d+/g; // 匹配一个或多个数字的正则表达式 const matches = str.match(regex); // 使用match方法获取匹配的数字数组 if (matches) { return matches.map(Number); // 将字符串数字转换为数字类型 } else { return []; // 如果没有匹配到数字则返回空数组 } }
// 获取字符串中的数字
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L226-L234
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.translateGroupSystemNotice
private async translateGroupSystemNotice(message: any) { const groupResult = await (window as any).$TUIKit.tim.getGroupList() // console.log('请求返回结果',groupResult); const groupList = groupResult?.data?.groupList // console.log('查看群聊列表',groupList); const findGroup = groupList.find((item: any) => { return String(item.groupID) === String(message.to) }) // console.log('获取群聊数据',findGroup); let numArr: any; if (message.payload.data === 'group_create') { const extension = message.payload.extension //console.log('排查',extension); numArr = this.extractNumbersFromString(extension) // console.log('查看strArr',numArr); } const option = { userIDList: message.payload.data === 'group_create' ? [`${numArr[0]}`] : message.payload.userIDList ? message.payload.userIDList : [`${message.payload.operatorID}`] } // console.log('查看参数配置',option); const res = await (window as any).$TUIKit.tim.getUserProfile(option) // console.log('获取用户名称',res.data); let userinfo = res.data[0] // console.log('排查::>>',userinfo); const groupName = findGroup?.name === undefined ? message.payload.groupProfile.name : findGroup?.name; const username = userinfo === undefined ? message.nick : userinfo?.nick; // console.log('查看用户昵称',username); console.log('验证通知消息类型', message.payload.operationType); switch (message.payload.operationType) { case TIM.TYPES.GRP_TIP_MBR_JOIN: // console.log('查看消息通知为什么有两条',message.payload); return `${username} 申请加入群组:${groupName}`; case TIM.TYPES.GRP_TIP_MBR_QUIT: return `${username} 退出群组:${groupName}`; case 3: return `申请加入群组:${groupName} 被拒绝`; case 4: return `你被管理员${username} 踢出:${groupName}群组`; case 5: return `群:${groupName} 被 ${username} 解散`; case 6: return `${username} 创建群:${groupName}`; case 7: return `${username} 邀请你加群:${groupName}`; case 8: return `你退出群组:${groupName}`; case 12: return `${username} 邀请你加群:${groupName}`; case 13: return `${username} 同意加群:${groupName}`; case 14: return `${username} 拒接加群:${groupName}`; case undefined && message.payload.data === 'group_create': return `${username} 创建群:${groupName}`; default: break; } }
// 解析系统通知消息方法
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L237-L294
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
Notifications.receiveNotification
public async receiveNotification(msg: any) { const app:any = appStore(); const {settings, userInfo} = storeToRefs(app); const data = {...msg.data[0]}; const server = (window as any).$TUIKit.TUIServer.TUIChat.store; const config = { enable: settings.value.noticeEnable === false, // 消息通知开关 global: router.options.history.state.current !== '/chatMain', // 是否在聊天页面 cue: settings.value.enablePlay, // 提示音开关 currentSession: server.conversation?.conversationID === data.conversationID, // 当前会话 atMsg: data.atUserList.length !== 0, // @全部消息 atMeMsg: data.atUserList.includes(String(userInfo.value.uid)), // @我的消息 currentDisturb: server.conversation?.groupProfile?.selfInfo.messageRemindType === 'AcceptAndNotify', // 免打扰 emptyData: Object.keys(server.conversation).length === 0 // 空数据 }; // 消息内容为text是否存在 const isText = data.payload.hasOwnProperty('text'); if(isText){ app.showNoticeEntry(); // 好友 if(data.conversationType === 'C2C'){ // 好友消息内容 const friendContent = { icon: data.avatar,title: `好友${data.nick}的消息`, conversationID: data.conversationID, body: `${data.nick}:${data.payload.text}`, time: data.time,type: 'message', } // 通知开关打开情况下、全局情况下、提示音按钮开启情况下、关闭免打扰情况下 if(config.enable && config.global && config.cue && config.currentDisturb) return this.messageWeak(friendContent, data.conversationID); // 通知开关打开、局部情况下、提示音开启情况下、不是当前会话情况下、关闭免打扰的情况下 if(config.enable && !config.global && config.cue && !config.currentSession && config.currentDisturb){ const playElement: HTMLAudioElement = this.createSoundElement(); playElement.play(); } } // 群聊 else{ const groupResult = await (window as any).$TUIKit.tim.getGroupList(); const groupList = groupResult?.data?.groupList; const findItem = groupList.find((item: any) => { return String(item.groupID) === String(data.to) }); const textContent = { icon: findItem.avatar, title: findItem.name, body: `${data.nick}:${data.payload.text}`, conversationID: data.conversationID, time: data.time, type: 'message', } // console.log('测试-1-全局',config.enable && config.global && config.cue && !config.currentDisturb); // console.log('测试-1.1-全局',config); // console.log('测试-2-局部',config.enable && !config.global && config.cue && !config.currentSession && config.currentDisturb); // console.log('测试-2.1-局部',config); // 群聊全局 if(config.enable && config.global && config.cue && config.currentDisturb){ // @我和@所有人 强提醒 if (config.atMeMsg && config.atMsg) return this.messageStrong(textContent, data.conversationID); // 弱提醒 this.messageWeak(textContent, data.conversationID) } else if (config.enable && !config.global && config.cue && !config.currentSession && config.currentDisturb) { // @我和@所有人 if (config.atMeMsg && config.atMsg) { // 强提醒 const strongEl: HTMLAudioElement = this.createSoundStrongElement() strongEl.play() } else { const playElement: HTMLAudioElement = this.createSoundElement(); playElement.play() } } } } else{ if (data.conversationType !== 'C2C'){ // 将群聊通知的用户uid进行中文昵称显示 const systemText = await this.translateGroupSystemNotice(data) // 通知、提示音开关是否打开 if (config.enable && config.cue || !config.currentDisturb) { const systemContent = { title: '社群沟通', icon: '/icons/IM.png', time: data.time,type: 'system', body: systemText, conversationID: data.conversationID, } this.messageWeak(systemContent, data?.conversationID) } } } }
// 社群消息通知
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/common/sessionNotice.ts#L298-L387
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
execAsPromised
function execAsPromised( command: string, options: { cwd?: string; useChildProcess?: (child: ChildProcess) => void; } = {} ): Promise<CommandOutput> { return new Promise((resolve, reject) => { const child = exec( '' + command, {cwd: options?.cwd, encoding: 'binary'}, (err, stdout, stderr) => { if (err) { reject(err); } let outDecode = iconv.decode(Buffer.from(stdout, "binary"), 'utf-8') let errDecode = iconv.decode(Buffer.from(stderr, "binary"), 'utf-8') resolve({ stdout: outDecode, stderr: errDecode, exitCode: child.exitCode, }); } ); if (options?.useChildProcess !== undefined) { options.useChildProcess(child); } }); }
/** * A Promise wrapper around child_process.exec() */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/ext/audio/audio.ts#L117-L146
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
getValidId
function getValidId(output: AudioOutput | string): string { const id = typeof output === 'string' ? output : output.id; if (!id || typeof id !== 'string' || id.length === 0) { throw new Error('invalid output id: ' + id); } return id; }
/** * Get the id of the given output and check that it is valid */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/js/ext/audio/audio.ts#L275-L283
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.constructor
constructor(config: XyRequestConfig) { this.instance = axios.create(config) this.interceptors = config.interceptors this.alone() this.all() }
// 单例拦截器
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/page/AIAssistant/service/request/request.ts#L9-L14
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.alone
alone() { // 注册单例请求拦截 this.instance.interceptors.request.use( this.interceptors?.requestInterceptor, this.interceptors?.requestInterceptorCatch ) // 注册单例响应拦截 this.instance.interceptors.response.use( this.interceptors?.responseInterceptor, this.interceptors?.responseInterceptorCatch ) }
// 单例拦截
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/page/AIAssistant/service/request/request.ts#L16-L27
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.all
all() { // 注册全局请求拦截 this.instance.interceptors.request.use( (config: any) => { return config }, (err) => { return err } ) // 注册全局响应拦截 this.instance.interceptors.response.use( (res: any) => { return res }, (err) => { return err } ) }
// 全局拦截
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/page/AIAssistant/service/request/request.ts#L29-L49
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.request
request<T = any>(config: XyRequestConfig): Promise<T> { return new Promise((resolve, reject) => { // 单独请求拦截 config = config.interceptors?.requestInterceptor ? config.interceptors.requestInterceptor(config) : config this.instance .request<T, any>(config) .then((res) => { // 单独响应拦截 res = config.interceptors?.responseInterceptor ? config.interceptors.responseInterceptor(res) : res resolve(res) }) .catch((err) => { reject(err) }) }) }
// 网络请求
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/page/AIAssistant/service/request/request.ts#L52-L72
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
getUnReadCount
function getUnReadCount(groupID:any){ const server = (window as any).$TUIKit.TUIServer.TUIConversation; const list =server.store.conversationList; if(list){ const find = _.find(list,function(item:any){ const itemInfo = item.groupProfile; return String(itemInfo?.groupID) === String(groupID); }); if(find){ return { unreadCount:find?.unreadCount }; } else { return { unreadCount:0 }; } } }
// 根据群聊id获取unreadCount
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/page/chat/libs/utils.ts#L4-L12
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
showConfirm
const showConfirm = (name) => { confirm(name + "无法使用", "下载客户端体验完整内容。", { noText: "稍后再说", okText: "立即下载", ok: () => { window.open("https://www.apps.vip/download/"); }, okButtonWidth: "95", noButtonWidth: "95", }); };
// 提示
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/useEnv.ts#L8-L18
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
envSort
const envSort = (arr) => { arr.sort((a, b) => { const indexA = PRIORITY.indexOf(a); const indexB = PRIORITY.indexOf(b); if (indexA === -1 && indexB === -1) { return 0; } else if (indexA === -1) { return 1; } else if (indexB === -1) { return -1; } else { return indexA - indexB; } }); return arr; };
// 环境优先级排序
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/useEnv.ts#L20-L37
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
envDetection
const envDetection = (type) => { if (type == "web") { return isWeb ? "web" : ""; } else if (type == "mac") { return isMac ? "mac" : ""; } else if (type == "offline") { return cache.get("isOffline") ? "offline" : ""; } else if (type == "guest") { return !cache.get("ttUserToken") ? "guest" : ""; } else if (type == "window") { return isWindow ? "window" : ""; } };
// 环境判断
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/useEnv.ts#L39-L51
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
checkLimit
const checkLimit = (env, name, options) => { let { msg = true, limitArr } = options; let res = useEnv(env); let limit = limitArr[res]?.includes(name); if (limit && msg) { showConfirm(res); } return limit; };
// 条件判断
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/useEnv.ts#L53-L61
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.constructor
constructor(config: XyRequestConfig) { this.instance = axios.create(config); this.interceptors = config.interceptors; this.alone(); this.all(); }
// 单例拦截器
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/request/request.ts#L9-L14
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.alone
alone() { // 注册单例请求拦截 this.instance.interceptors.request.use( this.interceptors?.requestInterceptor, this.interceptors?.requestInterceptorCatch ); // 注册单例响应拦截 this.instance.interceptors.response.use( this.interceptors?.responseInterceptor, this.interceptors?.responseInterceptorCatch ); }
// 单例拦截
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/request/request.ts#L16-L27
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.all
all() { // 注册全局请求拦截 this.instance.interceptors.request.use( (config: any) => { return config; }, (err) => { return err; } ); // 注册全局响应拦截 this.instance.interceptors.response.use( (res: any) => { return res; }, (err) => { return err; } ); }
// 全局拦截
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/request/request.ts#L29-L48
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
XyRequest.request
request<T = any>(config: XyRequestConfig): Promise<T> { return new Promise((resolve, reject) => { // 单独请求拦截 config = config.interceptors?.requestInterceptor ? config.interceptors.requestInterceptor(config) : config; this.instance .request<T, any>(config) .then((res) => { // 单独响应拦截 res = config.interceptors?.responseInterceptor ? config.interceptors.responseInterceptor(res) : res; resolve(res); }) .catch((err) => { reject(err); }); }); }
// 网络请求
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/request/request.ts#L51-L71
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
close
const close = () => { render(null, document.body); };
// 3 把渲染的 vNode 移除
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/user/useLogin.ts#L7-L9
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
setUserInfo
const setUserInfo = async () => { const userStore: any = appStore(); // 先判断用户信息是否存在,不存在进行赋值 if (userStore.userInfo) return userStore.userInfo; return await useUpdateUserInfo(); };
/** * 获取用户信息 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/user/useUserPermit.ts#L12-L17
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
gradeTableGenerate
const gradeTableGenerate = (num) => { // 初始化一个空对象,用于存储等级系统信息 let lvSys = {}; // 遍历从0到num(包含num)的每一个整数,代表不同的等级 for (let i = 0; i < num + 1; i++) { // 初始化两个变量,用于计算等级左边界和右边界 let arrLef = 0; // 等级左边界,初始值为0 let arrRg = 0; // 等级右边界,初始值为0 // 计算等级左边界的值 // 循环从0到i-1的每一个整数,每次累加10乘以(j+2)的值 for (let j = 0; j < i; j++) { arrLef += 10 * (j + 2); } // 计算等级右边界的值 // 循环从0到i的每一个整数,每次累加10乘以(k+2)的值 for (let k = 0; k < i + 1; k++) { arrRg += 10 * (k + 2); } // 减去1,可能是为了调整右边界的值,使其更符合实际规则 arrRg -= 1; // 将计算得到的左边界和右边界值存储到lvSys对象中,以等级i作为键 lvSys[`${i}`] = [arrLef, arrRg]; } // 从lvSys对象中删除键为"lv0"的项,可能是不需要等级0或者它有特殊的含义 delete lvSys["lv0"]; // 返回构建好的等级系统对象 return lvSys; };
/** * * 功能不详 复制来的 * 以下所有注释均由ai编写 不保证正确 */
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/permission/user/useUtils.ts#L8-L42
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
handleStream
const handleStream = (stream) => { //document.body.style.cursor = oldCursor // document.body.style.opacity = '1' // Create hidden video tag let video = document.createElement('video') video.autoplay = 'autoplay' video.style.cssText = 'position:absolute;top:-10000px;left:-10000px;' // Event connected to stream let loaded = false video.onplaying = () => { if (loaded) { return } loaded = true // Set video ORIGINAL height (screenshot) video.style.height = video.videoHeight + 'px' // videoHeight video.style.width = video.videoWidth + 'px' // videoWidth // Create canvas let canvas = document.createElement('canvas') canvas.width = video.videoWidth canvas.height = video.videoHeight let ctx = canvas.getContext('2d') // Draw video on canvas ctx.drawImage(video, 0, 0, canvas.width, canvas.height) if (this.callback) { // Save screenshot to png - base64 this.callback(canvas.toDataURL('image/png'), cb) } else { // console.log('Need callback!') } // Remove hidden video tag video.remove() try { stream.getTracks()[0].stop() } catch (e) { // nothing } } video.srcObject = stream document.body.appendChild(video) }
//ipc.send('captureImage',{source:this.currentSource})
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/store/capture.ts#L77-L121
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
handleContextMenu
const handleContextMenu = (e: any) => { if (!start.value || model.value != "contextmenu") return; setup(e); };
// 右键
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/ui/components/Menu/useMenuEvent.ts#L21-L24
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
handleClickMenu
const handleClickMenu = (e: any) => { if (!start.value || model.value != "click") return; setup(e); };
// 左键
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/ui/components/Menu/useMenuEvent.ts#L27-L30
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
closeMenu
const closeMenu = () => { show.value = false; handleCloseMenu(); };
// 关闭显示
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/ui/components/Menu/useMenuEvent.ts#L32-L35
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
updateWindowDimensions
const updateWindowDimensions = () => { // 在窗口大小变化停止后才更新窗口大小 clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { windowWidth.value = document.documentElement.clientWidth; windowHeight.value = document.documentElement.clientHeight; callback && callback({ windowWidth, windowHeight, }); }, 200); // 设置防抖延迟为200毫秒 };
// 用于存储 setTimeout 的返回值
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/ui/components/Menu/useWindowViewport.ts#L10-L22
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
openTeam
const openTeam = async () => { const store = useComStore(); const team = teamStore(); await team.updateMy(0); if (team.status === false) { store.showTeamTip = true; } else { team.teamVisible = !team.teamVisible; } };
// 打开小队判断
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/ui/hooks/useStartApp.ts#L211-L220
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
workbench
github_2023
yhtt2020
typescript
close
const close = () => { console.log("关闭事件 :>> "); render(null, document.body); };
// 3 把渲染的 vNode 移除
https://github.com/yhtt2020/workbench/blob/3d30910f185bdd2f72c14bff51d39fb2e774dd0a/vite/packages/table/ui/new/confirm/index.ts#L80-L83
3d30910f185bdd2f72c14bff51d39fb2e774dd0a
mockbin
github_2023
zuplo
typescript
addInvokeBinUrlToOpenApiDoc
function addInvokeBinUrlToOpenApiDoc(openApiDoc, invokeBinUrl) { // Ensure the 'servers' section exists if (!openApiDoc.servers) { openApiDoc.servers = []; } // Add the invokeBinUrl as the first server openApiDoc.servers.unshift({ url: invokeBinUrl }); return openApiDoc; }
// Module-level function to add invokeBinUrl to the OpenAPI document
https://github.com/zuplo/mockbin/blob/b77ed83fc4fa5e4c3b68ccd770509b40711e3203/modules/add-server-to-openapi.ts#L5-L13
b77ed83fc4fa5e4c3b68ccd770509b40711e3203
mockbin
github_2023
zuplo
typescript
handleRouteChange
const handleRouteChange = () => posthog?.capture("$pageview");
// Track page views
https://github.com/zuplo/mockbin/blob/b77ed83fc4fa5e4c3b68ccd770509b40711e3203/www/pages/_app.tsx#L26-L26
b77ed83fc4fa5e4c3b68ccd770509b40711e3203
draw-a-ui
github_2023
SawyerHood
typescript
crc
const crc: CRCCalculator<Uint8Array> = (current, previous) => { let crc = previous === 0 ? 0 : ~~previous! ^ -1; for (let index = 0; index < current.length; index++) { crc = TABLE[(crc ^ current[index]) & 0xff] ^ (crc >>> 8); } return crc ^ -1; };
// crc32, https://github.com/alexgorbatchev/crc/blob/master/src/calculators/crc32.ts
https://github.com/SawyerHood/draw-a-ui/blob/9058da6ed94d74a519b65206462e25f9a3e558dd/lib/png.ts#L58-L66
9058da6ed94d74a519b65206462e25f9a3e558dd
omniclip
github_2023
omni-media
typescript
getProxies
const getProxies = () => { const files = [...mediaController.values()] return files.filter(file => file.kind === "video" && file.proxy && use.context.state.effects.some(e => e.kind === "video" && e.file_hash === file.hash)) }
// get proxy videos on timeline
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/components/omni-timeline/views/export/view.ts#L191-L194
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
handleAction
function handleAction<T extends keyof Actions>(actionType: T, payload: ActionParams<T>, host: boolean, broadcastAction: Function, connection: Connection) { // 1) Look up the specialized handler, or fall back to default // somtimes action is inpure in the sense that it needs to be run through controller // to create some side effect eg. create object on canvas const specializedHandler = (actionHandlers as any)[actionType] if (specializedHandler) { specializedHandler(payload) } else { actionHandlers.default(actionType, payload) } // 2) If host, re-broadcast if (host) { broadcastAction(actionType, payload, connection) } }
// Utility to handle a single action by type
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/collaboration/parts/message-handler.ts#L37-L52
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
AlignGuidelines.omitCoords
private omitCoords(objCoords: ACoordsAppendCenter, type: "vertical" | "horizontal") { let newCoords; type PointArr = [keyof ACoordsAppendCenter, Point]; if (type === "vertical") { let l: PointArr = ["tl", objCoords.tl]; let r: PointArr = ["tl", objCoords.tl]; Keys(objCoords).forEach((key) => { if (objCoords[key].x < l[1].x) { l = [key, objCoords[key]]; } if (objCoords[key].x > r[1].x) { r = [key, objCoords[key]]; } }); newCoords = { [l[0]]: l[1], [r[0]]: r[1], c: objCoords.c, } as ACoordsAppendCenter; } else { let t: PointArr = ["tl", objCoords.tl]; let b: PointArr = ["tl", objCoords.tl]; Keys(objCoords).forEach((key) => { if (objCoords[key].y < t[1].y) { t = [key, objCoords[key]]; } if (objCoords[key].y > b[1].y) { b = [key, objCoords[key]]; } }); newCoords = { [t[0]]: t[1], [b[0]]: b[1], c: objCoords.c, } as ACoordsAppendCenter; } return newCoords; }
// 当对象被旋转时,需要忽略一些坐标,例如水平辅助线只取最上、下边的坐标(参考 figma)
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/compositor/lib/aligning_guidelines.ts#L195-L232
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
AlignGuidelines.calcCenterPointByACoords
private calcCenterPointByACoords(coords: NonNullable<FabricObject["aCoords"]>): Point { return new Point((coords.tl.x + coords.br.x) / 2, (coords.tl.y + coords.br.y) / 2); }
/** * fabric.Object.getCenterPoint will return the center point of the object calc by mouse moving & dragging distance. * calcCenterPointByACoords will return real center point of the object position. */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/compositor/lib/aligning_guidelines.ts#L244-L246
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
VideoManager.reset
reset(effect: VideoEffect) { const video = this.get(effect.id) if(video) { const element = this.#videoElements.get(effect.id)! video.setElement(element) } }
//reset element to state before export started
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/compositor/parts/video-manager.ts#L93-L99
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
Media.syncFile
async syncFile(file: File, hash: string, proxy?: boolean, isHost?: boolean) { const alreadyAdded = this.get(hash) if(alreadyAdded && proxy) {return} if(file.type.startsWith("image")) { const media = {file, hash, kind: "image"} satisfies AnyMedia this.set(hash, media) if(isHost) { this.import_file(file, hash, proxy) } else this.on_media_change.publish({files: [media], action: "added"}) } else if(file.type.startsWith("video")) { const {frames, duration, fps} = await this.getVideoFileMetadata(file) const media = {file, hash, kind: "video", frames, duration, fps, proxy: proxy ?? false} satisfies AnyMedia this.set(hash, media) if(isHost) { this.import_file(file, hash, proxy) } else this.on_media_change.publish({files: [media], action: "added"}) } else if(file.type.startsWith("audio")) { const media = {file, hash, kind: "audio"} satisfies AnyMedia this.set(hash, media) if(isHost) { this.import_file(file, hash, proxy) } else this.on_media_change.publish({files: [media], action: "added"}) } }
// syncing files for collaboration (no permament storing to db)
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/media/controller.ts#L151-L176
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
Timeline.calculate_proposed_timecode
calculate_proposed_timecode(effectTimecode: EffectTimecode, drag: EffectDrag, state: State): ProposedTimecode { return this.#placementProposal.calculateProposedTimecode(effectTimecode, drag, state) }
/** * Calculates a proposed timecode for an effect's placement, considering overlaps * and positioning on the timeline. * * @param effectTimecode - The start and end time of the effect to place. * @param grabbed_effect_id - The ID of the effect currently being dragged. * @param state - The current application state. * @returns A ProposedTimecode object containing the suggested placement and any adjustments. */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/timeline/controller.ts#L39-L41
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
Timeline.set_proposed_timecode
set_proposed_timecode(dragProps: EffectDrop, proposedTimecode: ProposedTimecode, state: State) { this.#effectManager.setProposedTimecode(dragProps, proposedTimecode, state) }
/** * Sets the proposed timecode for an effect based on the calculated proposal, adjusting * the effect’s start position, track, and duration if needed. * * @param effect - The effect to update with a new timecode. * @param proposedTimecode - The calculated timecode proposal for placement. */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/timeline/controller.ts#L50-L52
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
Timeline.remove_selected_effect
remove_selected_effect(state: State) { if (state.selected_effect) { this.#effectManager.removeEffect(state, state.selected_effect) } }
/** * Removes the currently selected effect from the application state, both * compositor and timeline will reflect this removal * * @param state - The current application state, which includes the selected effect. */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/timeline/controller.ts#L60-L64
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
Timeline.set_selected_effect
set_selected_effect(effect: AnyEffect | undefined, state: State) { this.#effectManager.setSelectedEffect(effect, state) }
/** * Sets the selected effect in the application state, allowing both the timeline * and the compositor canvas to reflect the selection. * * @param effect - The effect to set as selected, or undefined to clear the selection. * @param state - The current application state, where the selected effect will be updated. */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/timeline/controller.ts#L73-L75
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
Timeline.split
split(state: State) { this.#effectManager.splitEffectAtTimestamp(state) }
/** * Splits the selected effect or, if none is selected, splits the first effect found * at the current timestamp. The original effect is updated, and a new effect is created * at the split point. * * @param state - The current application state. */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/timeline/controller.ts#L84-L86
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
processFrame
function processFrame(currentFrame: VideoFrame, targetFrameInterval: number) { if(lastProcessedTimestamp === 0) { self.postMessage({ action: "new-frame", frame: { timestamp, frame: currentFrame, effect_id: id, } }) timestamp += 1000 / timebase lastProcessedTimestamp += currentFrame.timestamp } // if met frame is duplicated while (currentFrame.timestamp >= lastProcessedTimestamp + targetFrameInterval) { self.postMessage({ action: "new-frame", frame: { timestamp, frame: currentFrame, effect_id: id, } }) timestamp += 1000 / timebase lastProcessedTimestamp += targetFrameInterval } // if not met frame is skipped if (currentFrame.timestamp >= lastProcessedTimestamp) { self.postMessage({ action: "new-frame", frame: { timestamp, frame: currentFrame, effect_id: id, } }) timestamp += 1000 / timebase lastProcessedTimestamp += targetFrameInterval } currentFrame.close() }
/* * -- processFrame -- * Function responsible for maintaining * video framerate to desired timebase */
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/video-export/parts/decode_worker.ts#L62-L107
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
BinaryAccumulator.binary
get binary() { // Return cached binary if available if (this.#cachedBinary) { return this.#cachedBinary } let offset = 0 const binary = new Uint8Array(this.#size) for (const chunk of this.#uints) { binary.set(chunk, offset) offset += chunk.byteLength } this.#cachedBinary = binary // Cache the result return binary }
// in most cases getting size should be enough
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/context/controllers/video-export/tools/BinaryAccumulator/tool.ts#L14-L29
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
omniclip
github_2023
omni-media
typescript
renderShortcutsList
const renderShortcutsList = () => manager.listShortcuts().map(({ shortcut, actionType }) => html` <tr> <td>${actionType}</td> <td> <input type="text" .value=${shortcut} @keyup=${(e: PointerEvent) => onPointerUpInput(e, actionType)} @keydown=${onPointerDownInput} class="shortcut-input" > </td> </tr> ` )
// Render the list of shortcuts
https://github.com/omni-media/omniclip/blob/25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2/s/views/shortcuts/view.ts#L16-L32
25e66be6ef104ea0ed9e498f8dc2081a7a3ddee2
pigment-css
github_2023
mui
typescript
git
function git(args: any) { return new Promise((resolve, reject) => { exec(`git ${args}`, (err, stdout) => { if (err) { reject(err); } else { resolve(stdout.trim()); } }); }); }
/** * executes a git subcommand * @param {any} args */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L20-L30
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
reportBundleSizeCleanup
async function reportBundleSizeCleanup() { await git(`remote remove ${UPSTREAM_REMOTE}`); }
/** * This is mainly used for local development. It should be executed before the * scripts exit to avoid adding internal remotes to the local machine. This is * not an issue in CI. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L39-L41
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
createComparisonFilter
function createComparisonFilter(parsedThreshold: number, gzipThreshold: number) { return (comparisonEntry: any) => { const [, snapshot] = comparisonEntry; return ( Math.abs(snapshot.parsed.absoluteDiff) >= parsedThreshold || Math.abs(snapshot.gzip.absoluteDiff) >= gzipThreshold ); }; }
/** * creates a callback for Object.entries(comparison).filter that excludes every * entry that does not exceed the given threshold values for parsed and gzip size * @param {number} parsedThreshold * @param {number} gzipThreshold */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L49-L57
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
isPackageComparison
function isPackageComparison(comparisonEntry: [string, any]) { const [bundleKey] = comparisonEntry; return /^@[\w-]+\/[\w-]+$/.test(bundleKey); }
/** * checks if the bundle is of a package e.b. `@mui/material` but not * `@mui/material/Paper` * @param {[string, any]} comparisonEntry */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L64-L67
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
addPercent
function addPercent(change: number, goodEmoji = '', badEmoji = ':small_red_triangle:') { const formatted = (change * 100).toFixed(2); if (/^-|^0(?:\.0+)$/.test(formatted)) { return `${formatted}% ${goodEmoji}`; } return `+${formatted}% ${badEmoji}`; }
/** * Generates a user-readable string from a percentage change * @param {number} change * @param {string} goodEmoji emoji on reduction * @param {string} badEmoji emoji on increase */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L75-L81
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
sieveResults
function sieveResults<T>(results: Array<[string, T]>) { const main: [string, T][] = []; const pages: [string, T][] = []; results.forEach((entry) => { const [bundleId] = entry; if (bundleId.startsWith('docs:')) { pages.push(entry); } else { main.push(entry); } }); return { all: results, main, pages }; }
/** * Puts results in different buckets wh * @param {*} results */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L98-L113
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
loadLastComparison
async function loadLastComparison( upstreamRef: any, n = 0, ): Promise<Awaited<ReturnType<typeof loadComparison>>> { const mergeBaseCommit = await git(`merge-base HEAD~${n} ${UPSTREAM_REMOTE}/${upstreamRef}`); try { return await loadComparison(mergeBaseCommit, upstreamRef); } catch (err) { if (n >= 5) { throw err; } return loadLastComparison(upstreamRef, n + 1); } }
// A previous build might have failed to produce a snapshot
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L125-L138
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
formatFileToLink
function formatFileToLink(path: string) { let url = path.replace('docs/data', '').replace(/\.md$/, ''); const fragments = url.split('/').reverse(); if (fragments[0] === fragments[1]) { // check if the end of pathname is the same as the one before // for example `/data/material/getting-started/overview/overview.md url = fragments.slice(1).reverse().join('/'); } if (url.startsWith('/material')) { // needs to convert to correct material legacy folder structure to the existing url. url = replaceUrl(url.replace('/material', ''), '/material-ui').replace(/^\//, ''); } else { url = url .replace(/^\//, '') // remove initial `/` .replace('joy/', 'joy-ui/') .replace('components/', 'react-'); } return url; }
/** * The incoming path from danger does not start with `/` * e.g. ['docs/data/joy/components/button/button.md'] */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/dangerfile.ts#L192-L213
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
CreateExtendSxPropProcessor.build
build(): void {}
// eslint-disable-next-line class-methods-use-this
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/createExtendSxProp.ts#L16-L16
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
CreateUseThemePropsProcessor.build
build(): void {}
// eslint-disable-next-line class-methods-use-this
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/createUseThemeProps.ts#L34-L34
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
GenerateAtomicsProcessor.asSelector
get asSelector(): string { throw new Error('Method not implemented.'); }
// eslint-disable-next-line class-methods-use-this
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/generateAtomics.ts#L39-L41
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
GenerateAtomicsProcessor.value
get value(): Expression { throw new Error('Method not implemented.'); }
// eslint-disable-next-line class-methods-use-this
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/generateAtomics.ts#L44-L46
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.buildForTemplateTag
private buildForTemplateTag(values: ValueCache) { const templateStrs: string[] = []; // @ts-ignore @TODO - Fix this. No idea how to initialize a Tagged String array. templateStrs.raw = []; const templateExpressions: Primitive[] = []; const { themeArgs } = this.options as IOptions; this.styleArgs.flat().forEach((item) => { if ('kind' in item) { switch (item.kind) { case ValueType.FUNCTION: { const value = values.get(item.ex.name) as TemplateCallback; templateExpressions.push(value(themeArgs)); break; } case ValueType.CONST: templateExpressions.push(item.value); break; case ValueType.LAZY: { const evaluatedValue = values.get(item.ex.name); if (typeof evaluatedValue === 'function') { templateExpressions.push(evaluatedValue(themeArgs)); } else { templateExpressions.push(evaluatedValue as Primitive); } break; } default: break; } } else if (item.type === 'TemplateElement') { templateStrs.push(item.value.cooked as string); // @ts-ignore templateStrs.raw.push(item.value.raw); } }); this.buildTemplateTag( templateStrs as unknown as TemplateStringsArray, templateExpressions, values, ); }
/** * This handles transformation for direct tagged-template literal styled calls. * * @example * ```js * const Component = style('a')` * color: red; * `; */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L270-L311
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.buildForTransformedTemplateTag
private buildForTransformedTemplateTag(values: ValueCache) { // the below types are already validated in isMaybeTransformedTemplateLiteral check const [templateStrArg, ...restArgs] = this.styleArgs as (LazyValue | FunctionValue)[]; const templateStrings = values.get(templateStrArg.ex.name) as string[]; const templateStrs: string[] = [...templateStrings]; // @ts-ignore @TODO - Fix this. No idea how to initialize a Tagged String array. templateStrs.raw = [...templateStrings]; const templateExpressions: Primitive[] = []; const { themeArgs } = this.options as IOptions; restArgs.forEach((item) => { switch (item.kind) { case ValueType.FUNCTION: { const value = values.get(item.ex.name) as TemplateCallback; templateExpressions.push(value(themeArgs)); break; } case ValueType.LAZY: { const evaluatedValue = values.get(item.ex.name); if (typeof evaluatedValue === 'function') { templateExpressions.push(evaluatedValue(themeArgs)); } else { templateExpressions.push(evaluatedValue as Primitive); } break; } default: break; } }); this.buildTemplateTag( templateStrs as unknown as TemplateStringsArray, templateExpressions, values, ); }
/** * This handles transformation for tagged-template literal styled calls that have already been * transformed through swc. See [styled-swc-transformed-tagged-string.input.js](../../tests/styled/fixtures/styled-swc-transformed-tagged-string.input.js) * for sample code. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L318-L354
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.doEvaltimeReplacement
doEvaltimeReplacement() { this.replacer(this.astService.stringLiteral(this.asSelector), false); }
/** * There are 2 main phases in Wyw-in-JS's processing, Evaltime and Runtime. During Evaltime, Wyw-in-JS prepares minimal code that gets evaluated to get the actual values of the styled arguments. Here, we mostly want to replace the styled calls with a simple string/object of its classname. This is necessary for class composition. For ex, you could potentially do this - * ```js * const Component = styled(...)(...) * const Component2 = styled()({ * [`${Component} &`]: { * color: 'red' * } * }) * ``` * to further target `Component` rendered inside `Component2`. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L392-L394
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.build
build(values: ValueCache) { if (this.isTemplateTag) { this.buildForTemplateTag(values); return; } if (this.isMaybeTransformedTemplateLiteral(values)) { this.buildForTransformedTemplateTag(values); return; } this.buildForStyledCall(values); }
/** * This is called by Wyw-in-JS after evaluating the code. Here, we * get access to the actual values of the `styled` arguments * which we can use to generate our styles. * Order of processing styles - * 1. CSS directly declared in styled call * 3. Variants declared in styled call * 2. CSS declared in theme object's styledOverrides * 3. Variants declared in theme object */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L418-L428
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.doRuntimeReplacement
doRuntimeReplacement(): void { const t = this.astService; let componentName: Expression; if (typeof this.component === 'string') { if (this.component === 'FunctionalComponent') { componentName = t.arrowFunctionExpression([], t.blockStatement([])); } else { componentName = t.stringLiteral(this.component); } } else if (this.component?.node) { componentName = t.callExpression(t.identifier(this.component.node.name), []); } else { componentName = t.nullLiteral(); } const argProperties: ReturnType< typeof t.objectProperty | typeof t.spreadElement | typeof t.objectMethod >[] = []; const classNames = Array.from( new Set([this.className, ...(this.baseClasses.length ? this.baseClasses : [])]), ); argProperties.push( t.objectProperty( t.identifier('classes'), t.arrayExpression(classNames.map((cls) => t.stringLiteral(cls))), ), ); const varProperties: ReturnType<typeof t.objectProperty>[] = this.collectedVariables.map( ([variableId, expression, isUnitLess]) => t.objectProperty( t.stringLiteral(variableId), t.arrayExpression([expression, t.booleanLiteral(isUnitLess)]), ), ); if (varProperties.length) { argProperties.push(t.objectProperty(t.identifier('vars'), t.objectExpression(varProperties))); } if (this.collectedVariants.length) { argProperties.push( t.objectProperty(t.identifier('variants'), valueToLiteral(this.collectedVariants)), ); } let componentMetaExpression: ObjectExpression | undefined; if (this.componentMetaArg) { const parsedMeta = parseExpression(this.componentMetaArg.source); if (parsedMeta.type === 'ObjectExpression') { componentMetaExpression = parsedMeta as ObjectExpression; } } const styledImportIdentifier = t.addNamedImport('styled', this.getImportPath()); const styledCall = t.callExpression( styledImportIdentifier, componentMetaExpression ? [componentName, componentMetaExpression] : [componentName], ); const mainCall = t.callExpression(styledCall, [t.objectExpression(argProperties)]); this.replacer(mainCall, true); }
/** * This is the runtime phase where all of the css have been transformed and we finally want to replace the `styled` call with the code that we want in the final bundle. In this particular case, we replace the `styled` calls with * ```js * const Component = styled('div')({ * displayName: 'Component', * name: 'MuiSlider', * slot: 'root', * classes: ['class', 'class-1', '...'], * vars: { * 'var-id': [(props) => props.isRed ? 'red' : 'blue', false], * // ... * }, * variants: [{ * props: { * }, * className: 'class-variant-1', * }], * // ... * }) * ``` */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L451-L511
65364cab373927119abcbebad2edee6e59a8ee12