type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
TypeAliasDeclaration
type PageName = string
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
TypeAliasDeclaration
type FilePath = string
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
async clean () { const tempPath = this.tempPath const outputPath = this.outputPath try { await pRimraf(tempPath) await pRimraf(outputPath) } catch (e) { console.log(e) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
copyFiles () {}
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
classifyFiles (filename) { const pages = this.pages const appPath = this.appPath const entryFilePath = this.entryFilePath const relPath = path.normalize( path.relative(appPath, filename) ) if (path.relative(filename, entryFilePath) === '') return FILE_TYPE.ENTRY let relSrcPath = path.relative(this.sourceRoot, relPath) relSrcPath = path.format({ dir: path.dirname(relSrcPath), base: path.basename(relSrcPath, path.extname(relSrcPath)) }) const isPage = pages.some(([pageName, filePath]) => { const relPage = path.normalize( path.relative(appPath, pageName) ) if (path.relative(relPage, relSrcPath) === '') return true return false }) if (isPage) { return FILE_TYPE.PAGE } else { return FILE_TYPE.NORMAL } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
buildTemp () { const tempPath = this.tempPath const sourcePath = this.sourcePath const appPath = this.appPath fs.ensureDirSync(tempPath) const readPromises: any[] = [] function readFiles (sourcePath, originalFilePath) { readPromises.push(new Promise((resolve, reject) => { klaw(sourcePath) .on('data', file => { const REG_IGNORE = /(\\|\/)\.(svn|git)\1/i; const relativePath = path.relative(appPath, file.path) if (file.stats.isSymbolicLink()) { let linkFile = fs.readlinkSync(file.path) if (!path.isAbsolute(linkFile)) { linkFile = path.resolve(file.path, '..', linkFile) } readFiles.call(this, linkFile, file.path) } else if (!file.stats.isDirectory() && !REG_IGNORE.test(relativePath)) { printLog(processTypeEnum.CREATE, '发现文件', relativePath) this.processFiles(file.path, originalFilePath) } }) .on('end', () => { resolve() }) })) } readFiles.call(this, sourcePath, sourcePath) return Promise.all(readPromises) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
async buildDist ({ watch, port }: IBuildOptions, { modifyWebpackChain, modifyBuildAssets, onBuildFinish }: IBuildHooks) { const isMultiRouterMode = get(this.h5Config, 'router.mode') === 'multi' const entryFileName = this.entryFileName const projectConfig = this.projectConfig /** 不是真正意义上的IH5Config对象 */ const h5Config: IH5Config & { deviceRatio?: IDeviceRatio env?: IOption } = this.h5Config const outputDir = this.outputDir const sourceRoot = this.sourceRoot const tempPath = this.tempPath const pathAlias = this.pathAlias const getEntryFile = (filename: string) => { return path.join(tempPath, filename) } const entryFile = path.basename(entryFileName, path.extname(entryFileName)) + '.js' const defaultEntry = isMultiRouterMode ? fromPairs(this.pages.map(([pagename, filePath]) => { return [filePath, [getEntryFile(filePath) + '.js']] })) : { app: [getEntryFile(entryFile)] } if (projectConfig.deviceRatio) { h5Config.deviceRatio = projectConfig.deviceRatio } if (projectConfig.env) { h5Config.env = projectConfig.env } recursiveMerge(h5Config, { alias: pathAlias, copy: projectConfig.copy, homePage: first(this.pages), defineConstants: projectConfig.defineConstants, designWidth: projectConfig.designWidth, entry: merge(defaultEntry, h5Config.entry), env: { TARO_ENV: JSON.stringify('h5') }, isWatch: !!watch, outputRoot: outputDir, babel: projectConfig.babel, csso: projectConfig.csso, uglify: projectConfig.uglify, sass: projectConfig.sass, plugins: projectConfig.plugins, port, sourceRoot, modifyWebpackChain, modifyBuildAssets, onBuildFinish }) const webpackRunner = await npmProcess.getNpmPkg('@tarojs/webpack-runner', this.appPath) webpackRunner(this.appPath, h5Config) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
watchFiles () { const sourcePath = this.sourcePath const appPath = this.appPath const watcher = chokidar.watch(path.join(sourcePath), { ignored: /(^|[/\\])\../, persistent: true, ignoreInitial: true }) watcher .on('add', filePath => { const relativePath = path.relative(appPath, filePath) printLog(processTypeEnum.CREATE, '添加文件', relativePath) this.processFiles(filePath, filePath) }) .on('change', filePath => { const relativePath = path.relative(appPath, filePath) printLog(processTypeEnum.MODIFY, '文件变动', relativePath) this.processFiles(filePath, filePath) }) .on('unlink', filePath => { const relativePath = path.relative(appPath, filePath) const extname = path.extname(relativePath) const distDirname = this.getTempDir(filePath, filePath) const isScriptFile = REG_SCRIPTS.test(extname) const dist = this.getDist(distDirname, filePath, isScriptFile) printLog(processTypeEnum.UNLINK, '删除文件', relativePath) fs.unlinkSync(dist) }) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
enter (astPath: NodePath<t.ClassDeclaration> | NodePath<t.ClassExpression>) { const node = astPath.node if (!node.superClass) return if (isTaroClass(astPath)) { resetTSClassProperty(node.body.body) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ClassMethod>) { if (isMultiRouterMode) return const node = astPath.node const key = node.key const keyName = toVar(key) const isRender = keyName === 'render' const isComponentWillMount = keyName === 'componentWillMount' const isComponentDidMount = keyName === 'componentDidMount' const isComponentWillUnmount = keyName === 'componentWillUnmount' const isConstructor = keyName === 'constructor' if (isRender) { const createFuncBody = (pages: [PageName, FilePath][]) => { const routes = pages.map(([pageName, filePath], k) => { const shouldLazyloadPage = typeof routerLazyload === 'function' ? routerLazyload(pageName) : routerLazyload return createRoute({ pageName, lazyload: shouldLazyloadPage, isIndex: k === 0 }) }) return ` <Router mode={${JSON.stringify(routerMode)}} history={_taroHistory} routes={[${routes.join(',')}]} ${tabBar ? `tabBar={this.state.${tabBarConfigName}}` : ''} customRoutes={${JSON.stringify(customRoutes)}} /> ` } const buildFuncBody = pipe( ...compact([ createFuncBody, tabBar && partial(wrapWithTabbar, ['']), providerComponentName && storeName && wrapWithProvider, wrapWithFuncBody ]) ) node.body = toAst(buildFuncBody(pages), { preserveComments: true }) } else { node.body.body = compact([ hasComponentDidHide && isComponentWillUnmount && callComponentDidHideNode, ...node.body.body, tabBar && isComponentWillMount && initTabbarApiNode, hasConstructor && isConstructor && additionalConstructorNode, hasComponentDidShow && isComponentDidMount && callComponentDidShowNode ]) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ClassBody>) { const node = astPath.node if (hasComponentDidShow && !hasComponentDidMount) { node.body.push(t.classMethod( 'method', t.identifier('componentDidMount'), [], t.blockStatement([callComponentDidShowNode]), false, false)) } if (hasComponentDidHide && !hasComponentWillUnmount) { node.body.push(t.classMethod( 'method', t.identifier('componentWillUnmount'), [], t.blockStatement([callComponentDidHideNode]), false, false)) } if (!hasConstructor) { node.body.push(t.classMethod( 'method', t.identifier('constructor'), [t.identifier('props'), t.identifier('context')], t.blockStatement([toAst('super(props, context)'), additionalConstructorNode] as t.Statement[]), false, false)) } if (tabBar) { if (!hasComponentWillMount) { node.body.push(t.classMethod( 'method', t.identifier('componentWillMount'), [], t.blockStatement([initTabbarApiNode]), false, false)) } if (!stateNode) { stateNode = t.classProperty( t.identifier('state'), t.objectExpression([]) ) node.body.unshift(stateNode) } if (t.isObjectExpression(stateNode.value)) { stateNode.value.properties.push(t.objectProperty( t.identifier(tabBarConfigName), tabBar )) } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
ObjectProperty (astPath: NodePath<t.ObjectProperty>) { const node = astPath.node const key = node.key const value = node.value const keyName = toVar(key) if (keyName === 'pages' && t.isArrayExpression(value)) { const subPackageParent = astPath.findParent(isUnderSubPackages) if (subPackageParent) { /* 在subPackages属性下,说明是分包页面,需要处理root属性 */ const parent = astPath.parent as t.ObjectExpression const rootNode = parent.properties.find(v => { if (t.isSpreadProperty(v)) return false return toVar(v.key) === 'root' }) as t.ObjectProperty const root = rootNode ? toVar(rootNode.value) : ''; value.elements.forEach((v: t.StringLiteral) => { const pagePath = `${root}/${v.value}`.replace(/\/{2,}/g, '/') const pageName = removeLeadingSlash(pagePath) pages.push([pageName, renamePagename(pageName).replace(/\//g, '')]) v.value = addLeadingSlash(v.value) }) } else { value.elements.forEach((v: t.StringLiteral) => { const pagePath = v.value.replace(/\/{2,}/g, '/') const pageName = removeLeadingSlash(pagePath) pages.push([pageName, renamePagename(pageName).replace(/\//g, '')]) v.value = addLeadingSlash(v.value) }) } } else if (keyName === 'tabBar' && t.isObjectExpression(value)) { // tabBar相关处理 tabBar = value value.properties.forEach((node) => { if (t.isSpreadProperty(node)) return switch (toVar(node.key)) { case 'position': tabbarPos = toVar(node.value) break case 'list': t.isArrayExpression(node.value) && node.value.elements.forEach(v => { if (!t.isObjectExpression(v)) return v.properties.forEach(property => { if (!t.isObjectProperty(property)) return switch (toVar(property.key)) { case 'iconPath': case 'selectedIconPath': if (t.isStringLiteral(property.value)) { property.value = t.callExpression( t.identifier('require'), [t.stringLiteral(`./${property.value.value}`)] ) } break case 'pagePath': property.value = t.stringLiteral(addLeadingSlash(toVar(property.value))) break } }) }) } }) value.properties.push(t.objectProperty( t.identifier('mode'), t.stringLiteral(routerMode) )) value.properties.push(t.objectProperty( t.identifier('basename'), t.stringLiteral(routerBasename) )) value.properties.push(t.objectProperty( t.identifier('customRoutes'), t.objectExpression(objToAst(customRoutes)) )) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
enter (astPath: NodePath<t.ClassProperty>) { const node = astPath.node const key = node.key const keyName = toVar(key) if (keyName === 'state') { stateNode = node } else if (keyName === 'config') { astPath.traverse(classPropertyVisitor) if (isMultiRouterMode) { merge(customRoutes, transform(pages, (res, [pageName, filePath], key) => { res[addLeadingSlash(pageName)] = addLeadingSlash(filePath) }, {})) } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
enter (astPath: NodePath<t.CallExpression>) { const node = astPath.node const callee = node.callee const calleeName = toVar(callee) const parentPath = astPath.parentPath const arg0 = node.arguments[0] if (calleeName === 'require' && t.isStringLiteral(arg0)) { const required = arg0.value if (required === '@tarojs/taro-h5') { arg0.value = `@tarojs/taro-h5/dist/index.cjs.js` } } else if (t.isMemberExpression(callee)) { const object = callee.object as t.Identifier const property = callee.property as t.Identifier if (object.name === taroImportDefaultName && property.name === 'render') { object.name = nervJsImportDefaultName renderCallCode = generate(astPath.node).code astPath.remove() } } else { if (calleeName === setStoreFuncName) { if (parentPath.isAssignmentExpression() || parentPath.isExpressionStatement() || parentPath.isVariableDeclarator()) { parentPath.remove() } } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ClassMethod>) { const node = astPath.node const key = node.key const keyName = toVar(key) if (keyName === 'constructor') { hasConstructor = true } else if (keyName === 'componentWillMount') { hasComponentWillMount = true } else if (keyName === 'componentDidMount') { hasComponentDidMount = true } else if (keyName === 'componentDidShow') { hasComponentDidShow = true } else if (keyName === 'componentDidHide') { hasComponentDidHide = true } else if (keyName === 'componentWillUnmount') { hasComponentWillUnmount = true } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
enter (astPath: NodePath<t.JSXOpeningElement>) { const node = astPath.node if (toVar(node.name) === 'Provider') { for (const v of node.attributes) { if (v.name.name !== 'store') continue if (!t.isJSXExpressionContainer(v.value)) return storeName = toVar(v.value.expression) break } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.Program>) { const node = astPath.node const lastImportIndex = findLastIndex(astPath.node.body, t.isImportDeclaration) const lastImportNode = astPath.get(`body.${lastImportIndex > -1 ? lastImportIndex : 0}`) as NodePath<t.ImportDeclaration> const firstPage = first(pages) const routerConfigs = JSON.stringify({ basename: routerBasename, customRoutes }) const extraNodes: (t.Node | false)[] = [ !hasNerv && toAst(`import ${nervJsImportDefaultName} from 'nervjs'`), tabBar && toAst(`import { View, ${tabBarComponentName}, ${tabBarContainerComponentName}, ${tabBarPanelComponentName}} from '@tarojs/components'`), toAst(`import { Router, createHistory, mountApis } from '@tarojs/router'`), toAst(`Taro.initPxTransform(${JSON.stringify(pxTransformConfig)})`), toAst(` const _taroHistory = createHistory({ mode: "${routerMode}", basename: "${routerBasename}", customRoutes: ${JSON.stringify(customRoutes)}, firstPagePath: "${addLeadingSlash(firstPage ? firstPage[0] : '')}" }); `), isMultiRouterMode ? toAst(`mountApis(${routerConfigs});`) : toAst(`mountApis(${routerConfigs}, _taroHistory);`) ] astPath.traverse(programExitVisitor) if (!isUi) { lastImportNode.insertAfter(compact(extraNodes)) } if (renderCallCode) { const renderCallNode = toAst(renderCallCode) node.body.push(renderCallNode) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ClassMethod>) { const node = astPath.node const key = node.key const keyName = toVar(key) const isRender = keyName === 'render' const isComponentWillMount = keyName === 'componentWillMount' const isComponentDidMount = keyName === 'componentDidMount' const isComponentWillUnmount = keyName === 'componentWillUnmount' const isConstructor = keyName === 'constructor' if (isRender) { const buildFuncBody = pipe( ...compact([ createFuncBody, tabBar && partial(wrapWithTabbar, [addLeadingSlash(pageName)]), providerComponentName && storeName && wrapWithProvider, wrapWithFuncBody ]) ) node.body = toAst(buildFuncBody(pages), { preserveComments: true }) } else { node.body.body = compact([ hasComponentDidHide && isComponentWillUnmount && callComponentDidHideNode, ...node.body.body, tabBar && isComponentWillMount && initTabbarApiNode, hasConstructor && isConstructor && additionalConstructorNode, hasComponentDidShow && isComponentDidMount && callComponentDidShowNode ]) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.Program>) { const node = astPath.node node.body.forEach((bodyNode) => { if (t.isExpressionStatement(bodyNode) && t.isCallExpression(bodyNode.expression) && t.isIdentifier(bodyNode.expression.callee) && bodyNode.expression.callee.name === 'mountApis') { const mountApisOptNode = bodyNode.expression.arguments[0] if (t.isObjectExpression(mountApisOptNode)) { const valueNode = t.stringLiteral(addLeadingSlash(pageName)) let basenameNode = mountApisOptNode.properties.find((property: t.ObjectProperty) => { return toVar<string>(property.key) === 'currentPagename' }) as t.ObjectProperty | undefined if (basenameNode) { basenameNode.value = valueNode } else { basenameNode = t.objectProperty(t.stringLiteral('currentPagename'), valueNode) mountApisOptNode.properties.push(basenameNode) } } } }) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
enter (astPath: NodePath<t.ClassDeclaration> | NodePath<t.ClassExpression>) { const node = astPath.node if (!node.superClass) return if (isTaroClass(astPath)) { resetTSClassProperty(node.body.body) if (t.isClassDeclaration(astPath)) { if (node.id === null) { componentClassName = '_TaroComponentClass' astPath.replaceWith( t.classDeclaration( t.identifier(componentClassName), node.superClass as t.Expression, node.body as t.ClassBody, node.decorators as t.Decorator[] || [] ) ) } else { componentClassName = node.id.name } } else { if (node.id === null) { const parentNode = astPath.parentPath.node as any if (t.isVariableDeclarator(astPath.parentPath)) { componentClassName = parentNode.id.name } else { componentClassName = '_TaroComponentClass' } astPath.replaceWith( t.classExpression( t.identifier(componentClassName), node.superClass as t.Expression, node.body as t.ClassBody, node.decorators as t.Decorator[] || [] ) ) } else { componentClassName = node.id.name } } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.JSXElement>) { hasJSX = true }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.JSXOpeningElement>) { const node = astPath.node const tagName = toVar(node.name) const componentName = componentnameMap.get(tagName) const componentId = getComponentId(componentName, node) const componentRef = getComponentRef(node) if (tagName === BLOCK_TAG_NAME) { node.name = t.jSXMemberExpression( t.jSXIdentifier('Nerv'), t.jSXIdentifier('Fragment') ) } if (!componentId) return const refFunc = createRefFunc(componentId) if (componentRef) { const expression = (componentRef.value as t.JSXExpressionContainer).expression; (refFunc.body as t.BlockStatement).body.unshift( t.expressionStatement( t.callExpression(expression, [t.identifier('ref')]) ) ); (componentRef.value as t.JSXExpressionContainer).expression = refFunc } else { node.attributes.push( t.jSXAttribute( t.jSXIdentifier('ref'), t.jSXExpressionContainer(refFunc) ) ) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.JSXClosingElement>) { const node = astPath.node const tagName = toVar(node.name) if (tagName === BLOCK_TAG_NAME) { node.name = t.jSXMemberExpression( t.jSXIdentifier('Nerv'), t.jSXIdentifier('Fragment') ) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.CallExpression>) { const node = astPath.node const callee = node.callee const calleeName = toVar(callee) let needToAppendThis = false let funcName = '' const arg0 = node.arguments[0] if (calleeName === 'require' && t.isStringLiteral(arg0)) { const required = arg0.value if (required === '@tarojs/taro-h5') { arg0.value = `@tarojs/taro-h5/dist/index.cjs.js` } } else if (t.isMemberExpression(callee)) { const objName = toVar(callee.object) const tmpFuncName = toVar(callee.property) if (objName === taroImportDefaultName && APIS_NEED_TO_APPEND_THIS.has(tmpFuncName)) { needToAppendThis = true funcName = tmpFuncName } } else if (t.isIdentifier(callee)) { const tmpFuncName = toVar(callee) const oriFuncName = taroapiMap.get(tmpFuncName) if (APIS_NEED_TO_APPEND_THIS.has(oriFuncName)) { needToAppendThis = true funcName = oriFuncName } } if (needToAppendThis) { const thisOrder = APIS_NEED_TO_APPEND_THIS.get(funcName) if (thisOrder && !node.arguments[thisOrder]) { node.arguments[thisOrder] = t.thisExpression() } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
AssignmentExpression (astPath) { const node = astPath.node const left = node.left if (t.isMemberExpression(left) && t.isIdentifier(left.object)) { if (left.object.name === componentClassName && t.isIdentifier(left.property) && left.property.name === 'config') { needSetConfigFromHooks = true configFromHooks = node.right pageConfig = toVar(node.right) } } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.Program>) { const node = astPath.node if (hasJSX) { if (!importNervNode) { importNervNode = t.importDeclaration( [t.importDefaultSpecifier(t.identifier(nervJsImportDefaultName))], t.stringLiteral('nervjs') ) const specifiers = importNervNode.specifiers const defaultSpecifier = specifiers.find(item => t.isImportDefaultSpecifier(item)) if (!defaultSpecifier) { specifiers.unshift( t.importDefaultSpecifier(t.identifier(nervJsImportDefaultName)) ) } node.body.unshift(importNervNode) } if (!importTaroNode) { importTaroNode = t.importDeclaration( [t.importDefaultSpecifier(t.identifier('Taro'))], t.stringLiteral('@tarojs/taro-h5') ) node.body.unshift(importTaroNode) } astPath.traverse({ ClassBody (astPath) { if (needSetConfigFromHooks) { const classPath = astPath.findParent((p: NodePath<t.Node>) => p.isClassExpression() || p.isClassDeclaration()) as NodePath<t.ClassDeclaration> classPath.node.body.body.unshift( t.classProperty( t.identifier('config'), configFromHooks as t.ObjectExpression ) ) } } }) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
ClassBody (astPath) { if (needSetConfigFromHooks) { const classPath = astPath.findParent((p: NodePath<t.Node>) => p.isClassExpression() || p.isClassDeclaration()) as NodePath<t.ClassDeclaration> classPath.node.body.body.unshift( t.classProperty( t.identifier('config'), configFromHooks as t.ObjectExpression ) ) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
enter (astPath: NodePath<t.ClassProperty>) { const node = astPath.node const key = toVar(node.key) if (key === 'config') { pageConfig = toVar(node.value) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ClassMethod>) { const node = astPath.node const key = node.key const keyName = toVar(key) if (keyName === 'componentDidMount') { componentDidMountNode = node } else if (keyName === 'componentDidShow') { componentDidShowNode = node } else if (keyName === 'componentDidHide') { componentDidHideNode = node } else if (keyName === 'onPageScroll') { hasOnPageScroll = true } else if (keyName === 'onReachBottom') { hasOnReachBottom = true } else if (keyName === 'onPullDownRefresh') { hasOnPullDownRefresh = true } else if (keyName === 'render') { renderReturnStatementPaths.length = 0 renderClassMethodNode = node astPath.traverse({ ReturnStatement: { exit (returnAstPath: NodePath<t.ReturnStatement>) { renderReturnStatementPaths.push(returnAstPath) } } }) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (returnAstPath: NodePath<t.ReturnStatement>) { renderReturnStatementPaths.push(returnAstPath) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ClassBody>) { const node = astPath.node if (!componentDidMountNode) { componentDidMountNode = t.classMethod('method', t.identifier('componentDidMount'), [], t.blockStatement([ toAst('super.componentDidMount && super.componentDidMount()') as t.Statement ]), false, false) node.body.push(componentDidMountNode) } if (!componentDidShowNode) { componentDidShowNode = t.classMethod('method', t.identifier('componentDidShow'), [], t.blockStatement([ toAst('super.componentDidShow && super.componentDidShow()') as t.Statement ]), false, false) node.body.push(componentDidShowNode) } if (!componentDidHideNode) { componentDidHideNode = t.classMethod('method', t.identifier('componentDidHide'), [], t.blockStatement([ toAst('super.componentDidHide && super.componentDidHide()') as t.Statement ]), false, false) node.body.push(componentDidHideNode) } if (hasOnReachBottom) { componentDidShowNode.body.body.push( toAst(` this._offReachBottom = Taro.onReachBottom({ callback: this.onReachBottom, ctx: this, onReachBottomDistance: ${JSON.stringify(pageConfig.onReachBottomDistance)} }) `) ) componentDidHideNode.body.body.push( toAst('this._offReachBottom && this._offReachBottom()') ) } if (hasOnPageScroll) { componentDidShowNode.body.body.push( toAst('this._offPageScroll = Taro.onPageScroll({ callback: this.onPageScroll, ctx: this })') ) componentDidHideNode.body.body.push( toAst('this._offPageScroll && this._offPageScroll()') ) } if (hasOnPullDownRefresh) { componentDidShowNode.body.body.push( toAst(` this.pullDownRefreshRef && this.pullDownRefreshRef.bindEvent() `) ) componentDidHideNode.body.body.push( toAst(` this.pullDownRefreshRef && this.pullDownRefreshRef.unbindEvent() `) ) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ExportDefaultDeclaration>) { exportDefaultDeclarationNode = astPath.node }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.ExportNamedDeclaration>) { exportNamedDeclarationPath = astPath }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
exit (astPath: NodePath<t.Program>) { if (hasOnPullDownRefresh) { // 增加PullDownRefresh组件 if (!importTaroComponentNode) { importTaroComponentNode = t.importDeclaration( [], t.stringLiteral('@tarojs/components') ) astPath.node.body.unshift(importTaroComponentNode) } const specifiers = importTaroComponentNode.specifiers const pos = importTaroComponentNode.specifiers.findIndex(specifier => { if (!t.isImportSpecifier(specifier)) return false const importedComponent = toVar(specifier.imported) return importedComponent === 'PullDownRefresh' }) if (pos === -1) { specifiers.push( t.importSpecifier( t.identifier('PullDownRefresh'), t.identifier('PullDownRefresh') ) ) } const returnStatement = renderReturnStatementPaths.filter(renderReturnStatementPath => { const funcParentPath: NodePath = renderReturnStatementPath.getFunctionParent() return funcParentPath.node === renderClassMethodNode }) returnStatement.forEach(returnAstPath => { const statement = returnAstPath.node const varName = returnAstPath.scope.generateUid() const returnValue = statement.argument const pullDownRefreshNode = t.variableDeclaration( 'const', [t.variableDeclarator( t.identifier(varName), returnValue )] ) returnAstPath.insertBefore(pullDownRefreshNode) statement.argument = (toAst(` <PullDownRefresh onRefresh={this.onPullDownRefresh && this.onPullDownRefresh.bind(this)} ref={ref => { if (ref) this.pullDownRefreshRef = ref }}>{${varName}}</PullDownRefresh>`) as t.ExpressionStatement).expression }) } if (!exportDefaultDeclarationNode && exportNamedDeclarationPath) { replaceExportNamedToDefault(exportNamedDeclarationPath) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
getTempDir (filePath, originalFilePath) { const appPath = this.appPath const sourcePath = this.sourcePath const tempDir = this.tempDir let dirname = path.dirname(filePath) if (filePath.indexOf(sourcePath) < 0) { dirname = path.extname(originalFilePath) ? path.dirname(originalFilePath) : originalFilePath } const relPath = path.relative(sourcePath, dirname) return path.resolve(appPath, tempDir, relPath) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
transformToTempDir (filePath: string) { const sourcePath = this.sourcePath const isAbsolute = path.isAbsolute(filePath) if (!isAbsolute) return filePath const relPath = path.relative(sourcePath, filePath) return relPath.startsWith('..') ? filePath : path.resolve(this.tempPath, relPath) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
processFiles (filePath, originalFilePath) { const original = fs.readFileSync(filePath, { encoding: 'utf8' }) const extname = path.extname(filePath) const distDirname = this.getTempDir(filePath, originalFilePath) const isScriptFile = REG_SCRIPTS.test(extname) const distPath = this.getDist(distDirname, filePath, isScriptFile) fs.ensureDirSync(distDirname) try { if (isScriptFile) { // 脚本文件 处理一下 const fileType = this.classifyFiles(filePath) if (fileType === FILE_TYPE.ENTRY) { this.pages = [] const result = this.processEntry(original, filePath) if (Array.isArray(result)) { result.forEach(([pageName, code]) => { fs.writeFileSync( path.join(distDirname, `${pageName}.js`), code ) }) } else { fs.writeFileSync(distPath, result) } } else { const code = this.processOthers(original, filePath, fileType) fs.writeFileSync(distPath, code) } } else { // 其他 直接复制 fs.copySync(filePath, distPath) } } catch (e) { console.log(e) } }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
MethodDeclaration
getDist (distDirname, filename, isScriptFile) { return isScriptFile ? path.format({ dir: distDirname, ext: '.js', name: path.basename(filename, path.extname(filename)) }) : path.format({ dir: distDirname, base: path.basename(filename) }) }
CooperFu/taro
packages/taro-cli/src/h5/index.ts
TypeScript
ArrowFunction
responsePriceData => { this.estates = responsePriceData; console.log('success', this.estates); }
v786/Koya
koya-app/src/app/compare-rent/compare-rent.component.ts
TypeScript
ArrowFunction
responsePriceError => { this.estates = null; console.log('fail') }
v786/Koya
koya-app/src/app/compare-rent/compare-rent.component.ts
TypeScript
ArrowFunction
() => console.log('get scraps method executed')
v786/Koya
koya-app/src/app/compare-rent/compare-rent.component.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-compare-rent', templateUrl: './compare-rent.component.html', styleUrls: ['./compare-rent.component.css'] }) export class CompareRentComponent implements OnInit { public barChartOptions: ChartOptions = { responsive: true, // We use these empty structures as placeholders for dynamic theming. scales: { xAxes: [{}], yAxes: [{}] }, plugins: { datalabels: { anchor: 'end', align: 'end', } } }; data = [ { "_id": "5ca7e5c5fdbfa311d857c11c", "Locality": "Bannimantap", "Min": "4211", "max": "5614", "AvgPrice": "4912" }, { "_id": "5ca7e639f271a611d88312ae", "Locality": "Bogadi", "Min": "2042", "max": "3500", "AvgPrice": "2771" }, { "_id": "5ca7e664f271a611d88312af", "Locality": "Gokulam", "Min": "5093", "max": "5648", "AvgPrice": "5370" }]; public barChartLabels: Label[] = ['Min', 'Max', 'AvgPrice']; public barChartType: ChartType = 'bar'; public barChartLegend = true; public estates: any[]; public barChartData: ChartDataSets[] = [ { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' }, { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' } ]; constructor(private _scrapper: ScrapperService) { const temp = []; this.data.forEach(function (elem) { temp.push({ data: [ parseInt(elem['Min'], 10), parseInt(elem['max'], 10), parseInt(elem['AvgPrice'], 10) ], label: elem['Locality'] }); console.log(temp); }); this.barChartData = temp; } getScrapper() { this._scrapper.getScraps('gokulam').subscribe( responsePriceData => { this.estates = responsePriceData; console.log('success', this.estates); }, responsePriceError => { this.estates = null; console.log('fail') }, () => console.log('get scraps method executed') ); } ngOnInit() { this.getScrapper(); } }
v786/Koya
koya-app/src/app/compare-rent/compare-rent.component.ts
TypeScript
MethodDeclaration
getScrapper() { this._scrapper.getScraps('gokulam').subscribe( responsePriceData => { this.estates = responsePriceData; console.log('success', this.estates); }, responsePriceError => { this.estates = null; console.log('fail') }, () => console.log('get scraps method executed') ); }
v786/Koya
koya-app/src/app/compare-rent/compare-rent.component.ts
TypeScript
MethodDeclaration
ngOnInit() { this.getScrapper(); }
v786/Koya
koya-app/src/app/compare-rent/compare-rent.component.ts
TypeScript
ArrowFunction
async () => { const input = parseInt("foo", 10); await expect(wait(input)).rejects.toThrow("milliseconds not a number"); }
halvardssm/typescript-action
lib/main.test.ts
TypeScript
ArrowFunction
async () => { const start = new Date(); await wait(500); const end = new Date(); var delta = Math.abs(end.getTime() - start.getTime()); expect(delta).toBeGreaterThan(450); }
halvardssm/typescript-action
lib/main.test.ts
TypeScript
ArrowFunction
() => { process.env["INPUT_MILLISECONDS"] = "500"; const np = process.execPath; const ip = path.join(__dirname, "..", "dist", "index.js"); const options: cp.ExecFileSyncOptions = { env: process.env }; console.log(cp.execFileSync(np, [ip], options).toString()); }
halvardssm/typescript-action
lib/main.test.ts
TypeScript
ArrowFunction
params => { const artistId = params['id']; return this.artistService.getById(artistId); }
sevgin0954/Spotify
src/app/artist/artist/artist.component.ts
TypeScript
ClassDeclaration
@Component({ selector: 'app-artist', templateUrl: './artist.component.html', styleUrls: ['./artist.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ArtistComponent implements OnInit { artist$: Observable<Artist>; @ViewChild('albums') albumsElement: ElementRef; @ViewChild('artists') artistsElement: ElementRef; constructor( private route: ActivatedRoute, private renderer2: Renderer2, private artistService: ArtistService ) { } ngOnInit(): void { this.artist$ = this.route.params.pipe( concatMap(params => { const artistId = params['id']; return this.artistService.getById(artistId); }) ); } onShowButtonClick(): void { this.renderer2.addClass(this.albumsElement.nativeElement, ALBUMS_EXPANDED_CLASS); this.renderer2.addClass(this.artistsElement.nativeElement, SIMILAR_ARTISTS_SHRINKED_CLASS); } onHideButtonClick(): void { this.renderer2.removeClass(this.albumsElement.nativeElement, ALBUMS_EXPANDED_CLASS); this.renderer2.removeClass(this.artistsElement.nativeElement, SIMILAR_ARTISTS_SHRINKED_CLASS); } }
sevgin0954/Spotify
src/app/artist/artist/artist.component.ts
TypeScript
MethodDeclaration
ngOnInit(): void { this.artist$ = this.route.params.pipe( concatMap(params => { const artistId = params['id']; return this.artistService.getById(artistId); }) ); }
sevgin0954/Spotify
src/app/artist/artist/artist.component.ts
TypeScript
MethodDeclaration
onShowButtonClick(): void { this.renderer2.addClass(this.albumsElement.nativeElement, ALBUMS_EXPANDED_CLASS); this.renderer2.addClass(this.artistsElement.nativeElement, SIMILAR_ARTISTS_SHRINKED_CLASS); }
sevgin0954/Spotify
src/app/artist/artist/artist.component.ts
TypeScript
MethodDeclaration
onHideButtonClick(): void { this.renderer2.removeClass(this.albumsElement.nativeElement, ALBUMS_EXPANDED_CLASS); this.renderer2.removeClass(this.artistsElement.nativeElement, SIMILAR_ARTISTS_SHRINKED_CLASS); }
sevgin0954/Spotify
src/app/artist/artist/artist.component.ts
TypeScript
FunctionDeclaration
function AdapterGitHubButton(props: { repo: Repository; user: User }) { const { repo, user } = props; const [counts, setCounts] = useState(`${repo.open_issues} open issues/PRs`); const [color, setColor] = useState<"primary" | "error">("primary"); useEffect(() => { const loadPullRequests = async () => { if (!repo.open_issues) { setCounts("no open PRs / no open issues"); return; } const gitHub = GitHubComm.forToken(user.token); const pullRequests = await gitHub .getRepo(repo) .getPullRequests("open"); const prCount = pullRequests.length; const issueCount = repo.open_issues - prCount; const getText = (value: number, type: string) => { return `${value || "no"} open ${type}${value === 1 ? "" : "s"}`; }; setCounts( `${getText(prCount, "PR")} / ${getText(issueCount, "issue")}`, ); setColor(prCount > 0 ? "error" : "primary"); }; loadPullRequests().catch(console.error); }, [repo, user]); return ( <CardButton icon={ <Tooltip title={`GitHub Repository (${counts})`}
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
function AdapterSentryButton(props: { projects: ProjectInfo[] }) { const { projects } = props; const [tooltip, setTooltip] = useState("Sentry available for this adapter"); const [errorCount, setErrorCount] = useState<number[]>(); const [errorCounts, setErrorCounts] = useState<number[][]>([]); const [open, setOpen] = useState(false); useEffect(() => { if (projects.length === 0) { return; } const loadProjectInfos = async () => { const stats24h = await getSentryStats( projects.map((p) => p.id), "24h", ); const stats30d = await getSentryStats( projects.map((p) => p.id), "30d", ); const errors = [ stats24h.map( (stat) => stat.stats.reduce((old, num) => old + num[1], 0), 0, ), stats30d.map( (stat) => stat.stats.reduce((old, num) => old + num[1], 0), 0, ), ]; setErrorCounts(errors); const totalErrors = errors.map((e) => e.reduce((old, err) => old + err, 0), ); setErrorCount(totalErrors); if (totalErrors[0]) { setTooltip( `Sentry (${totalErrors[0]} errors in the last 24 hours)`, ); } else { setTooltip( `Sentry (${totalErrors[1]} errors in the last 30 days)`, ); } }; loadProjectInfos().catch(console.error); }, [projects]); if (projects.length === 0) { return ( <Tooltip title="Sentry not used by this adapter"> <span> <CardButton disabled icon={<SentryIcon />} /> </span> </Tooltip> ); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
function AddWatchDialog(props: AddWatchDialogProps) { const { user, open, onClose } = props; const [repoNames, setRepoNames] = useState<string[]>([]); const [repoName, setRepoName] = useState(""); const [error, setError] = useState(""); const [validating, setValidating] = useState(false); useEffect(() => { if (!open) { return; } const loadData = async () => { const latest = await getLatest(); const names = Object.keys(latest).map((adapterName) => latest[adapterName].meta.replace( /^\w+:\/\/[^/]+\/([^/]+\/[^/]+)\/.+$/, "$1", ), ); setRepoNames(names); }; loadData().catch(console.error); }, [open]); const validate = async () => { setValidating(true); try { const gitHub = GitHubComm.forToken(user.token); const [owner, repo] = repoName.split("/", 2); const latest = await getLatest(); const infos = await getAdapterInfos( await gitHub.getRepo(owner, repo).getRepo(), latest, ); if (!infos.info) { throw new Error("This is not an ioBroker adapter"); } onClose(repoName); } catch (error: any) { setError(error.message || error); } finally { setValidating(false); } }; return ( <Dialog open={!!open}
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
async function getDiscoveryLink(adapterName: string) { return (await hasDiscoverySupport(adapterName)) ? `https://github.com/ioBroker/ioBroker.discovery/blob/master/lib/adapters/` + `${uc(adapterName)}.js` : ""; }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
async function getWeblateLink(adapterName: string) { try { const components = await getWeblateAdapterComponents(); const component = components.results.find( (c: any) => c.name === adapterName, ); if (component) { return ( `https://weblate.iobroker.net/projects/adapters/` + `${uc(component.slug)}/` ); } } catch { // ignore and leave "weblateLink" empty } return ""; }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
async function getSentryProjects(adapterName: string) { const allProjects = await getSentryProjectInfos(); return allProjects.filter((p) => p.adapterName === adapterName); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
async function getAdapterCard( infos: AdapterInfos, history: H.History<AdapterCheckLocationState>, user: User, onClose?: () => void, ): Promise<DashboardCardProps | undefined> { const { repo, info } = infos; if (!info) { return; } const [discoveryLink, weblateLink, sentryProjects, ratings] = await Promise.all([ getDiscoveryLink(info.name), getWeblateLink(info.name), getSentryProjects(info.name), getAllRatings(), ]); const openAdapterCheck = () => { history.push("/adapter-check", { repoFullName: repo.full_name, }); }; return { title: repo.name, onClose, img: info?.extIcon, badges: { "npm version": `https://img.shields.io/npm/v/iobroker.${info.name}.svg`, "Stable version": `https://iobroker.live/badges/${info.name}-stable.svg`, }, rating: ratings[info.name]?.rating, text: info?.desc?.en || repo.description || "No description available", squareImg: true, to: `/adapter/${info.name}`, buttons: [ <AdapterGitHubButton repo={repo} user={user} />, <CardButton icon={ <Tooltip title="Start Adapter Check"> <AdapterCheckIcon /> </Tooltip> } onClick={openAdapterCheck} />, <Tooltip title={`${ discoveryLink ? "S" : "Not s" }upported by ioBroker.discovery`} > <span> <CardButton disabled={!discoveryLink} icon={<DiscoveryIcon />}
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
FunctionDeclaration
export default function Dashboard(props: DashboardProps) { const { user, onAdapterListChanged } = props; const history = useHistory<AdapterCheckLocationState>(); const [categories, setCategories] = useState<Record<string, CardGridProps>>( { Resources: { cards: resourcesCards }, Social: { cards: socialCards }, Tools: { cards: getToolsCards(!!user) }, [MY_ADAPTERS_CATEGORY]: { cards: [] }, }, ); let storedCollapsed; try { storedCollapsed = JSON.parse( localStorage.getItem(COLLAPSED_CATEGORIES_KEY) || "[]", ); } catch { storedCollapsed = []; } const [collapsed, setCollapsed] = useState<boolean[]>(storedCollapsed); const [showAddWatch, setShowAddWatch] = useState(false); const handleAccordion = (index: number) => { setCollapsed((old) => { const result = [...old]; result[index] = !result[index]; localStorage.setItem( COLLAPSED_CATEGORIES_KEY, JSON.stringify(result), ); return result; }); }; const loadWatchedAdapters = async (user: User) => { setCategories((old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [] }, })); // clear the list (and show the spinner) let adapters: DashboardCardProps[] = []; try { const infos = await getWatchedAdapterInfos(user.token); const cards = await Promise.all( infos.map((info) => getAdapterCard(info, history, user, () => handleRemoveWatch(info).catch(console.error), ).catch(console.error), ), ); adapters = cards .filter((c) => !!c) .map((c) => c as DashboardCardProps); } catch (error) { console.error(error); } setCategories((old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [...adapters], onAdd: () => setShowAddWatch(true), }, })); }; useEffect(() => { const loadMyAdapters = async (user: User) => { setCategories((old) => ({ ...old, [MY_ADAPTERS_CATEGORY]: { cards: [] }, })); // clear the list (and show the spinner) const infos = await getMyAdapterInfos(user.token); const cards = await Promise.all( infos.map((info) => getAdapterCard(info, history, user).catch(console.error), ), ); const adapters = cards .filter((c) => !!c) .map((c) => c as DashboardCardProps); if (adapters.length === 0) { adapters.push({ title: "No adapters found", img: "images/adapter-creator.png", text: "You can create your first ioBroker adapter by answering questions in the Adapter Creator.", buttons: [ <CardButton text="Open Adapter Creator" to="/create-adapter" />, ], }); } setCategories((old) => ({ ...old, Tools: { cards: getToolsCards(true) }, [MY_ADAPTERS_CATEGORY]: { cards: [...adapters] }, })); }; if (user) { loadMyAdapters(user).catch(console.error); loadWatchedAdapters(user).catch(console.error); } else { const loginCard = (type: string) => ({ title: "Login Required", img: "images/github.png", text: `You must be logged in to see your ${type}.`, buttons: [<CardButton text="Login" onClick={handleLogin} />], }); setCategories((old) => { const result = { ...old }; result.Tools = { cards: getToolsCards(false) }; result[MY_ADAPTERS_CATEGORY] = { cards: [loginCard("adapters")], }; delete result[WATCHED_ADAPTERS_CATEGORY]; return result; }); } }, [user]); useEffect(() => { const updateBlogIcon = async () => { const url = "https://raw.githubusercontent.com/ioBroker/ioBroker.docs/master/engine/front-end/public/blog.json"; const { data: blog } = await axios.get<{ pages: Record< string, { date: string; title: Record<string, string>; logo: string; } >; }>(url); const page = Object.values(blog.pages)[0]; if (!page) return; setCategories((old) => { const res = old.Resources; const index = res.cards.findIndex((c) => c.title === "Blog"); if (index >= 0) { const card = res.cards[index]; const date = page.date.replace( /^(\d{4})\.(\d{2})\.(\d{2})$/, "$3.$2.$1", ); res.cards[index] = { ...card, img: `https://www.iobroker.net/${page.logo}`, text: `${card.text}\n \nLatest entry: ${page.title.en} (${date})`, }; } return { ...old }; }); }; updateBlogIcon().catch(console.error); }, []); const handleAddWatch = async (repo?: string) => { setShowAddWatch(false); if (!repo) { return; } try { setCategories((old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [] }, })); // show spinner const url = getApiUrl("user"); const { data: dbUser } = await axios.get<DbUser>(url); dbUser.watches.push(repo); await axios.put(url, dbUser); onAdapterListChanged(); await loadWatchedAdapters(user!); } catch (error) { console.error(error); } }; const handleRemoveWatch = async (info: AdapterInfos) => { setCategories((old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [] }, })); // show spinner const url = getApiUrl("user"); const { data: dbUser } = await axios.get<DbUser>(url); dbUser.watches = dbUser.watches.filter( (w) => !equalIgnoreCase(w, info.repo.full_name), ); await axios.put(url, dbUser); onAdapterListChanged(); await loadWatchedAdapters(user!); }; return ( <> {user && ( <AddWatchDialog user={user} open={showAddWatch} onClose={handleAddWatch} /> )}
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => { const loadPullRequests = async () => { if (!repo.open_issues) { setCounts("no open PRs / no open issues"); return; } const gitHub = GitHubComm.forToken(user.token); const pullRequests = await gitHub .getRepo(repo) .getPullRequests("open"); const prCount = pullRequests.length; const issueCount = repo.open_issues - prCount; const getText = (value: number, type: string) => { return `${value || "no"} open ${type}${value === 1 ? "" : "s"}`; }; setCounts( `${getText(prCount, "PR")} / ${getText(issueCount, "issue")}`, ); setColor(prCount > 0 ? "error" : "primary"); }; loadPullRequests().catch(console.error); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async () => { if (!repo.open_issues) { setCounts("no open PRs / no open issues"); return; } const gitHub = GitHubComm.forToken(user.token); const pullRequests = await gitHub .getRepo(repo) .getPullRequests("open"); const prCount = pullRequests.length; const issueCount = repo.open_issues - prCount; const getText = (value: number, type: string) => { return `${value || "no"} open ${type}${value === 1 ? "" : "s"}`; }; setCounts( `${getText(prCount, "PR")} / ${getText(issueCount, "issue")}`, ); setColor(prCount > 0 ? "error" : "primary"); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(value: number, type: string) => { return `${value || "no"} open ${type}${value === 1 ? "" : "s"}`; }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(props: { errors: number[]; children: any }, ref: any) => { const { errors, children } = props; const errorCount = errors[0] || errors[1]; const color = errors[0] ? "error" : "primary"; return ( <Badge badgeContent={errorCount} color={color} {
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => { if (projects.length === 0) { return; } const loadProjectInfos = async () => { const stats24h = await getSentryStats( projects.map((p) => p.id), "24h", ); const stats30d = await getSentryStats( projects.map((p) => p.id), "30d", ); const errors = [ stats24h.map( (stat) => stat.stats.reduce((old, num) => old + num[1], 0), 0, ), stats30d.map( (stat) => stat.stats.reduce((old, num) => old + num[1], 0), 0, ), ]; setErrorCounts(errors); const totalErrors = errors.map((e) => e.reduce((old, err) => old + err, 0), ); setErrorCount(totalErrors); if (totalErrors[0]) { setTooltip( `Sentry (${totalErrors[0]} errors in the last 24 hours)`, ); } else { setTooltip( `Sentry (${totalErrors[1]} errors in the last 30 days)`, ); } }; loadProjectInfos().catch(console.error); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async () => { const stats24h = await getSentryStats( projects.map((p) => p.id), "24h", ); const stats30d = await getSentryStats( projects.map((p) => p.id), "30d", ); const errors = [ stats24h.map( (stat) => stat.stats.reduce((old, num) => old + num[1], 0), 0, ), stats30d.map( (stat) => stat.stats.reduce((old, num) => old + num[1], 0), 0, ), ]; setErrorCounts(errors); const totalErrors = errors.map((e) => e.reduce((old, err) => old + err, 0), ); setErrorCount(totalErrors); if (totalErrors[0]) { setTooltip( `Sentry (${totalErrors[0]} errors in the last 24 hours)`, ); } else { setTooltip( `Sentry (${totalErrors[1]} errors in the last 30 days)`, ); } }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(stat) => stat.stats.reduce((old, num) => old + num[1], 0)
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old, num) => old + num[1]
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(e) => e.reduce((old, err) => old + err, 0)
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old, err) => old + err
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(project: ProjectInfo) => { window.open( `https://sentry.iobroker.net/organizations/iobroker/issues/?project=${project.id}`, "_blank", ); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(project, index) => ( <ListItem button
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => { if (!open) { return; } const loadData = async () => { const latest = await getLatest(); const names = Object.keys(latest).map((adapterName) => latest[adapterName].meta.replace( /^\w+:\/\/[^/]+\/([^/]+\/[^/]+)\/.+$/, "$1", ), ); setRepoNames(names); }; loadData().catch(console.error); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async () => { const latest = await getLatest(); const names = Object.keys(latest).map((adapterName) => latest[adapterName].meta.replace( /^\w+:\/\/[^/]+\/([^/]+\/[^/]+)\/.+$/, "$1", ), ); setRepoNames(names); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(adapterName) => latest[adapterName].meta.replace( /^\w+:\/\/[^/]+\/([^/]+\/[^/]+)\/.+$/, "$1", )
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async () => { setValidating(true); try { const gitHub = GitHubComm.forToken(user.token); const [owner, repo] = repoName.split("/", 2); const latest = await getLatest(); const infos = await getAdapterInfos( await gitHub.getRepo(owner, repo).getRepo(), latest, ); if (!infos.info) { throw new Error("This is not an ioBroker adapter"); } onClose(repoName); } catch (error: any) { setError(error.message || error); } finally { setValidating(false); } }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => onClose()
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(c: any) => c.name === adapterName
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(p) => p.adapterName === adapterName
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => { history.push("/adapter-check", { repoFullName: repo.full_name, }); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(index: number) => { setCollapsed((old) => { const result = [...old]; result[index] = !result[index]; localStorage.setItem( COLLAPSED_CATEGORIES_KEY, JSON.stringify(result), ); return result; }); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => { const result = [...old]; result[index] = !result[index]; localStorage.setItem( COLLAPSED_CATEGORIES_KEY, JSON.stringify(result), ); return result; }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async (user: User) => { setCategories((old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [] }, })); // clear the list (and show the spinner) let adapters: DashboardCardProps[] = []; try { const infos = await getWatchedAdapterInfos(user.token); const cards = await Promise.all( infos.map((info) => getAdapterCard(info, history, user, () => handleRemoveWatch(info).catch(console.error), ).catch(console.error), ), ); adapters = cards .filter((c) => !!c) .map((c) => c as DashboardCardProps); } catch (error) { console.error(error); } setCategories((old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [...adapters], onAdd: () => setShowAddWatch(true), }, })); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [] }, })
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(info) => getAdapterCard(info, history, user, () => handleRemoveWatch(info).catch(console.error), ).catch(console.error)
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => handleRemoveWatch(info).catch(console.error)
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(c) => !!c
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(c) => c as DashboardCardProps
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => ({ ...old, [WATCHED_ADAPTERS_CATEGORY]: { cards: [...adapters], onAdd: () => setShowAddWatch(true), }, })
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => setShowAddWatch(true)
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => { const loadMyAdapters = async (user: User) => { setCategories((old) => ({ ...old, [MY_ADAPTERS_CATEGORY]: { cards: [] }, })); // clear the list (and show the spinner) const infos = await getMyAdapterInfos(user.token); const cards = await Promise.all( infos.map((info) => getAdapterCard(info, history, user).catch(console.error), ), ); const adapters = cards .filter((c) => !!c) .map((c) => c as DashboardCardProps); if (adapters.length === 0) { adapters.push({ title: "No adapters found", img: "images/adapter-creator.png", text: "You can create your first ioBroker adapter by answering questions in the Adapter Creator.", buttons: [ <CardButton text="Open Adapter Creator" to="/create-adapter" />, ], }); } setCategories((old) => ({ ...old, Tools: { cards: getToolsCards(true) }, [MY_ADAPTERS_CATEGORY]: { cards: [...adapters] }, })); }; if (user) { loadMyAdapters(user).catch(console.error); loadWatchedAdapters(user).catch(console.error); } else { const loginCard = (type: string) => ({ title: "Login Required", img: "images/github.png", text: `You must be logged in to see your ${type}.`, buttons: [<CardButton text="Login" onClick={handleLogin} />], }); setCategories((old) => { const result = { ...old }; result.Tools = { cards: getToolsCards(false) }; result[MY_ADAPTERS_CATEGORY] = { cards: [loginCard("adapters")], }; delete result[WATCHED_ADAPTERS_CATEGORY]; return result; }); } }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async (user: User) => { setCategories((old) => ({ ...old, [MY_ADAPTERS_CATEGORY]: { cards: [] }, })); // clear the list (and show the spinner) const infos = await getMyAdapterInfos(user.token); const cards = await Promise.all( infos.map((info) => getAdapterCard(info, history, user).catch(console.error), ), ); const adapters = cards .filter((c) => !!c) .map((c) => c as DashboardCardProps); if (adapters.length === 0) { adapters.push({ title: "No adapters found", img: "images/adapter-creator.png", text: "You can create your first ioBroker adapter by answering questions in the Adapter Creator.", buttons: [ <CardButton text="Open Adapter Creator" to="/create-adapter" />, ], }); } setCategories((old) => ({ ...old, Tools: { cards: getToolsCards(true) }, [MY_ADAPTERS_CATEGORY]: { cards: [...adapters] }, })); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => ({ ...old, [MY_ADAPTERS_CATEGORY]: { cards: [] }, })
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(info) => getAdapterCard(info, history, user).catch(console.error)
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => ({ ...old, Tools: { cards: getToolsCards(true) }, [MY_ADAPTERS_CATEGORY]: { cards: [...adapters] }, })
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(type: string) => ({ title: "Login Required", img: "images/github.png", text: `You must be logged in to see your ${type}.`, buttons: [<CardButton text="Login" onClick={handleLogin} />], })
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => { const result = { ...old }; result.Tools = { cards: getToolsCards(false) }; result[MY_ADAPTERS_CATEGORY] = { cards: [loginCard("adapters")], }; delete result[WATCHED_ADAPTERS_CATEGORY]; return result; }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
() => { const updateBlogIcon = async () => { const url = "https://raw.githubusercontent.com/ioBroker/ioBroker.docs/master/engine/front-end/public/blog.json"; const { data: blog } = await axios.get<{ pages: Record< string, { date: string; title: Record<string, string>; logo: string; } >; }>(url); const page = Object.values(blog.pages)[0]; if (!page) return; setCategories((old) => { const res = old.Resources; const index = res.cards.findIndex((c) => c.title === "Blog"); if (index >= 0) { const card = res.cards[index]; const date = page.date.replace( /^(\d{4})\.(\d{2})\.(\d{2})$/, "$3.$2.$1", ); res.cards[index] = { ...card, img: `https://www.iobroker.net/${page.logo}`, text: `${card.text}\n \nLatest entry: ${page.title.en} (${date})`, }; } return { ...old }; }); }; updateBlogIcon().catch(console.error); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
async () => { const url = "https://raw.githubusercontent.com/ioBroker/ioBroker.docs/master/engine/front-end/public/blog.json"; const { data: blog } = await axios.get<{ pages: Record< string, { date: string; title: Record<string, string>; logo: string; } >; }>(url); const page = Object.values(blog.pages)[0]; if (!page) return; setCategories((old) => { const res = old.Resources; const index = res.cards.findIndex((c) => c.title === "Blog"); if (index >= 0) { const card = res.cards[index]; const date = page.date.replace( /^(\d{4})\.(\d{2})\.(\d{2})$/, "$3.$2.$1", ); res.cards[index] = { ...card, img: `https://www.iobroker.net/${page.logo}`, text: `${card.text}\n \nLatest entry: ${page.title.en} (${date})`, }; } return { ...old }; }); }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript
ArrowFunction
(old) => { const res = old.Resources; const index = res.cards.findIndex((c) => c.title === "Blog"); if (index >= 0) { const card = res.cards[index]; const date = page.date.replace( /^(\d{4})\.(\d{2})\.(\d{2})$/, "$3.$2.$1", ); res.cards[index] = { ...card, img: `https://www.iobroker.net/${page.logo}`, text: `${card.text}\n \nLatest entry: ${page.title.en} (${date})`, }; } return { ...old }; }
UncleSamSwiss/iobroker-dev-portal
express/frontend/src/components/Dashboard.tsx
TypeScript