repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
CodeFuse-Query
github_2023
codefuse-ai
typescript
forEach
function forEach<T, U>( array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined, ): U | undefined { if (array) { for (let i = 0; i < array.length; i++) { const result = callback(array[i], i); if (result) { return result; } } } return undefined; }
/** * typescript 内部方法 forEach * * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. * If no such value is found, the callback is applied to each element of array and undefined is returned. * * 参考: https://github.com/microsoft/TypeScript/blob/v4.5.5/src/compiler/core.ts#L63 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/util.ts#L471-L484
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getRouterSourceFiles
function getRouterSourceFiles( program: ts.Program, projectPath: string, ): ts.SourceFile[] { return program .getSourceFiles() .filter( x => path .relative(projectPath, x.fileName) .match(/^app\/router(\.[jt]s|\/.+\.[jt]s)$/g) !== null, ); }
/** * Get router SourceFiles * * @param program * @param projectPath * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L18-L30
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getControllerModuleSourceFileMap
function getControllerModuleSourceFileMap( program: ts.Program, projectPath: string, ): Map<string, ts.SourceFile> { const controllerPathPrefixes = ['app/controller/', 'app/controllers/'].map( x => path.join(projectPath, x), ); function convertControllerPathToModule(filePath: string): string { const relativePath = path.relative(projectPath, filePath); const pathParts = relativePath.split('.')[0].split('/').slice(2); return pathParts.map(x => camelCase(x)).join('.'); } const controllerModuleSourceFiles = program .getSourceFiles() .map(sourceFile => ({ path: sourceFile.fileName, sourceFile })) .filter(x => controllerPathPrefixes.some(prefix => x.path.startsWith(prefix)), ) .map(x => ({ module: convertControllerPathToModule(x.path), sourceFile: x.sourceFile, })); return new Map( controllerModuleSourceFiles.map(x => [x.module, x.sourceFile]), ); }
/** * Get a map of controller qualified module name and corresponding ts SourceFile * @param program * @param projectPath * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L38-L66
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getServiceModuleSourceFileMap
function getServiceModuleSourceFileMap( program: ts.Program, projectPath: string, ): Map<string, ts.SourceFile> { const servicePathPrefix = path.join(projectPath, 'app/service/'); function convertServicePathToModule(filePath: string): string { const relativePath = path.relative(projectPath, filePath); const pathParts = relativePath.split('.')[0].split('/').slice(2); return pathParts.map(x => camelCase(x)).join('.'); } const serviceModuleSourceFiles = program .getSourceFiles() .map(sourceFile => ({ path: sourceFile.fileName, sourceFile })) .filter(x => x.path.startsWith(servicePathPrefix)) .map(x => ({ module: convertServicePathToModule(x.path), sourceFile: x.sourceFile, })); return new Map(serviceModuleSourceFiles.map(x => [x.module, x.sourceFile])); }
/** * Get a map of service qualified module name and corresponding ts SourceFile * * @param program * @param projectPath * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L75-L97
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getServiceAccessExpressionInfos
function getServiceAccessExpressionInfos( sourceFile: ts.SourceFile, serviceModuleSourceFileMap: Map<string, ts.SourceFile>, ) { const re = /^(this\.|ctx\.|this\.ctx\.)?service\.(.+)$/; const serviceAccessExpressionInfos: ServiceAccessExpressionInfo[] = []; util.forEachNode(sourceFile, (node: ts.Node) => { if ( !util.isAccessExpression(node) || util.isAccessExpression(node.parent) ) { return; } const propertyAccessText = util.getAccessExpressionText(node); const matchArray = propertyAccessText.match(re); const serviceFuncQualifiedName = matchArray?.[2]; if (!serviceFuncQualifiedName) { return; } const nameParts = serviceFuncQualifiedName.split('.'); const serviceModuleQualifiedName = nameParts.slice(0, -1).join('.'); if (!serviceModuleSourceFileMap.has(serviceModuleQualifiedName)) { return; } const functionName = nameParts[nameParts.length - 1]; const serviceSourceFile = serviceModuleSourceFileMap.get( serviceModuleQualifiedName, ) as ts.SourceFile; serviceAccessExpressionInfos.push({ accessExpression: node, serviceModuleQualifiedName, functionName, serviceSourceFile, }); }); return serviceAccessExpressionInfos; }
/** * Get service access expression information. * * @param sourceFile * @param serviceModuleSourceFileMap * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L347-L388
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractServiceAccessCorefByServiceClass
function extractServiceAccessCorefByServiceClass( serviceAccessExpressionInfo: ServiceAccessExpressionInfo, serviceClass: ts.ClassLikeDeclaration, typeChecker: ts.TypeChecker, projectPath: string, ): { symbol: coref.Symbol | undefined; nodeSymbols: coref.NodeSymbol[]; callSite: coref.CallSite | undefined; } { const { accessExpression, functionName } = serviceAccessExpressionInfo; const member = util.getClassMemberByName(serviceClass, functionName); const tsSymbol = member && util.getSymbol(member, typeChecker); const declaration = tsSymbol && util.getSymbolDeclaration(tsSymbol); // Symbol const symbol = tsSymbol && util.createSymbolFromTsSymbol(tsSymbol, typeChecker, projectPath); const nodeSymbols: coref.NodeSymbol[] = symbol ? [ { node: util.ensureCorefAstNode( util.getAccessExpressionPropertyNode(accessExpression), ) as coref.Node, symbol, }, { node: util.ensureCorefAstNode(accessExpression) as coref.Node, symbol, }, ] : []; // Call site let callSite: coref.CallSite | undefined; // TODO: getter and setter const corefInvokeExpression = ts.isCallLikeExpression(accessExpression.parent) ? (util.ensureCorefAstNode(accessExpression.parent) as coref.Node) : undefined; if (corefInvokeExpression && declaration) { if (ts.isMethodDeclaration(declaration)) { callSite = { invokeExpression: corefInvokeExpression, callee: util.ensureCorefAstNode(declaration) as coref.Node, }; } else if (ts.isPropertyDeclaration(declaration)) { const functionNode = declaration.initializer; if ( functionNode && (ts.isFunctionExpression(functionNode) || ts.isArrowFunction(functionNode)) ) { callSite = { invokeExpression: corefInvokeExpression, callee: util.ensureCorefAstNode(functionNode) as coref.Node, }; } } } return { symbol, nodeSymbols, callSite, }; }
/** * Extract the COREF for a service property access by the specified service class * * @param serviceAccessExpressionInfo * @param serviceClass * @param typeChecker * @param projectPath * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L399-L465
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getServiceClass
function getServiceClass( expression: ts.Expression, typeChecker: ts.TypeChecker, ) { // Resolve service class from the expression const classLikeDeclaration = util.getClassOfExpression( expression, typeChecker, ); if (classLikeDeclaration) { return classLikeDeclaration; } // Resolve service class from return value of the default function const functionLikeDeclaration = util.getFunctionOfExpression( expression, typeChecker, ); return ( functionLikeDeclaration && functionLikeDeclaration.body?.forEachChild(funcChildNode => { if (ts.isReturnStatement(funcChildNode)) { const returnExpression = funcChildNode.expression; // console.log(typeChecker.getSymbolAtLocation(returnExpression as ts.Node)); return returnExpression ? util.getClassOfExpression(returnExpression, typeChecker) : undefined; } }) ); }
/** * Get the service class from the expression. * * @param expression * @param typeChecker * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L474-L506
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractServiceAccessCoref
function extractServiceAccessCoref( serviceAccessExpressionInfo: ServiceAccessExpressionInfo, typeChecker: ts.TypeChecker, projectPath: string, ): { symbol: coref.Symbol | undefined; nodeSymbols: coref.NodeSymbol[]; callSite: coref.CallSite | undefined; } { const result = serviceAccessExpressionInfo.serviceSourceFile.forEachChild( topNode => { if (ts.isExpressionStatement(topNode)) { // module.exports = xxxClass const expression = topNode.expression; if (util.isModuleExportsAssignExpression(expression)) { const serviceClass = getServiceClass( (expression as ts.BinaryExpression).right, typeChecker, ); return ( serviceClass && extractServiceAccessCorefByServiceClass( serviceAccessExpressionInfo, serviceClass, typeChecker, projectPath, ) ); } } else if (ts.isExportAssignment(topNode)) { // export default xxxClass; const expression = topNode.expression; const serviceClass = getServiceClass(expression, typeChecker); return ( serviceClass && extractServiceAccessCorefByServiceClass( serviceAccessExpressionInfo, serviceClass, typeChecker, projectPath, ) ); } else if (ts.isClassDeclaration(topNode)) { // export default class xxx {} if (util.isExportDefaultDeclaration(topNode)) { return extractServiceAccessCorefByServiceClass( serviceAccessExpressionInfo, topNode, typeChecker, projectPath, ); } } }, ); return ( result ?? { symbol: undefined, nodeSymbols: [], callSite: undefined, } ); }
/** * Extract the COREF for a service property access. * * @param serviceAccessExpressionInfo * @param typeChecker * @param projectPath * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/framework/chair.ts#L516-L579
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getSymbolName
function getSymbolName(tsSymbol: ts.Symbol): string { // export default class A // symbol.name cannot get 'default' instead of 'A' if (tsSymbol.flags & ts.SymbolFlags.Class && tsSymbol.name === 'default') { const { valueDeclaration: { localSymbol }, } = tsSymbol as any; if (localSymbol != null) { return localSymbol.name; } // export default class { } // class without a name return 'default'; } // other cases return tsSymbol.name; }
/** * Try to get the symbol name * * @param tsSymbol the specified ts.Symbol * @returns symbol name */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/model/coref/symbol.ts#L25-L43
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
createSyntheticCfgNode
function createSyntheticCfgNode( astNodeOid: bigint, kind: SyntheticCfgNodeKind, ): SyntheticCfgNode { const kindName = kind === SyntheticCfgNodeKind.Entry ? 'entry' : 'exit'; const uri = `cfg:${kindName}:${astNodeOid}`; const oid = hashToInt64(uri); return { oid, astNodeOid, }; }
/** * Create a synthetic CFG node, which is a entry or exit node. * * @param astNodeOid * @param kind * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/model/coref/synthetic-cfg-node.ts#L22-L33
c262c419616db680bb8a8a3f91b669f5e961dc81
GPT-Vis
github_2023
antvis
typescript
streamOutput
const streamOutput = () => { timerRef.current = setInterval(() => { const step = parseInt((Math.random() * 10).toString(), 20); const nowText = nowTextRef.current + markdownContent.substring(nowTextRef.current.length, nowTextRef.current.length + step); nowTextRef.current = nowText; setText(nowText); if (text.length === markdownContent.length - 1) { clearTimeout(timerRef.current); } }, 200); };
/** 模拟流式输出markdownContent */
https://github.com/antvis/GPT-Vis/blob/ec2b0f27094d17cc04688f2977febe2a24d8aed9/src/ChartCodeRender/demos/stream.tsx#L44-L56
ec2b0f27094d17cc04688f2977febe2a24d8aed9
GPT-Vis
github_2023
antvis
typescript
normalizeProportion
function normalizeProportion(data: number | undefined) { if (typeof data !== 'number') return 0; if (data > 1) return 1; if (data < 0) return 0; return data; }
/** * make data between 0 ~ 1 */
https://github.com/antvis/GPT-Vis/blob/ec2b0f27094d17cc04688f2977febe2a24d8aed9/src/Text/mini-charts/proportion/getArcPath.ts#L4-L9
ec2b0f27094d17cc04688f2977febe2a24d8aed9
GPT-Vis
github_2023
antvis
typescript
visG2Encode2ADCEncode
function visG2Encode2ADCEncode<T extends Record<string, any>>(config: T) { const encodeConfig = config.encode; if (!encodeConfig) return config; const _config = { ...config }; for (const field of encodeConfig) { const adcField = ADC_ENCODE_FIELDS.get(field); if (adcField) { // @ts-expect-error _config[adcField] = encodeConfig[field]; } } return _config; }
/** * 将 G2 encode 写法转换为 ADC Plot 字段映射 */
https://github.com/antvis/GPT-Vis/blob/ec2b0f27094d17cc04688f2977febe2a24d8aed9/src/utils/plot.ts#L16-L30
ec2b0f27094d17cc04688f2977febe2a24d8aed9
GPT-Vis
github_2023
antvis
typescript
axisTitle2G2axis
function axisTitle2G2axis<T extends Record<string, any>>(config: T) { const { axisXTitle, axisYTitle } = config; const _config: T = { axis: {}, ...config }; if (axisXTitle) { if (get(_config, 'axis.x')) { _config.axis.x.title = axisXTitle; } else { _config.axis.x = { title: axisXTitle }; } } if (axisYTitle) { if (get(_config, 'axis.y')) { _config.axis.y.title = axisYTitle; } else { _config.axis.y = { title: axisYTitle }; } } return _config; }
/** * 将缩写的 axisTitle 转换为 G2 axis 配置 */
https://github.com/antvis/GPT-Vis/blob/ec2b0f27094d17cc04688f2977febe2a24d8aed9/src/utils/plot.ts#L35-L56
ec2b0f27094d17cc04688f2977febe2a24d8aed9
cleave-zen
github_2023
nosir
typescript
stripPrefix
const stripPrefix = ({ value, prefix, tailPrefix, }: GetPrefixStrippedValueProps): string => { const prefixLength: number = prefix.length // No prefix if (prefixLength === 0) { return value } // Value is prefix if (value === prefix && value !== '') { return '' } // result prefix string does not match pre-defined prefix if (value.slice(0, prefixLength) !== prefix && !tailPrefix) { return '' } else if (value.slice(-prefixLength) !== prefix && tailPrefix) { return '' } // No issue, strip prefix for new value return tailPrefix ? value.slice(0, -prefixLength) : value.slice(prefixLength) }
// strip prefix
https://github.com/nosir/cleave-zen/blob/22b1d89ca47c4c733e22218ec1a545c80bf43b57/src/general/index.ts#L9-L35
22b1d89ca47c4c733e22218ec1a545c80bf43b57
football_frontend
github_2023
czl0325
typescript
EAxios.init
init () { // 请求接口拦截器 this.instance.interceptors.request.use( config => { config.headers["Content-Type"] = 'application/json;' if (localStorage.getItem("token")) { config.headers["Authorization"] = localStorage.getItem("token") } return config }, err => { console.error(err) } ) // 响应拦截器 this.instance.interceptors.response.use( response => { if (response.status === 200) { return Promise.resolve(response.data) } else { return Promise.reject(response) } }, err => { const { response } = err if (response) { showToast({ message: `错误:${response.status}`, position: 'bottom', }) return Promise.reject(err) } else { showToast({ message: "网络连接异常,请稍后再试!", position: 'bottom', }) } }) }
// 初始化拦截器
https://github.com/czl0325/football_frontend/blob/75bbf39d2c4da1c8b8458add4dec29d0b6384814/src/http/EAxios.ts#L20-L59
75bbf39d2c4da1c8b8458add4dec29d0b6384814
codemirror-ts
github_2023
val-town
typescript
formatDisplayParts
function formatDisplayParts(displayParts: ts.SymbolDisplayPart[]) { let text = displayParts .map((d) => d.text) .join("") .replace(/\r?\n\s*/g, " "); if (text.length > 120) text = `${text.slice(0, 119)}...`; return text; }
/** * Generally based off of the playground version of this method. * Format displayParts into a short string with no linebreaks. */
https://github.com/val-town/codemirror-ts/blob/f91a46e7dd8c4bba7591d2c713466ce795a21e9f/src/twoslash/tsTwoslash.ts#L31-L38
f91a46e7dd8c4bba7591d2c713466ce795a21e9f
codemirror-ts
github_2023
val-town
typescript
twoslashes
function twoslashes(view: EditorView, config: FacetConfig) { if (!config) return null; const promises: Promise<SetTwoSlashes | null>[] = []; for (const { from, to } of view.visibleRanges) { syntaxTree(view.state).iterate({ from, to, enter: (node) => { if (node.name === "LineComment") { const doc = view.state.doc; const commentText = doc.sliceString(node.from, node.to); const queryRegex = /^\s*\/\/\s*\^\?$/gm; const isTwoslash = queryRegex.test(commentText); if (isTwoslash) { const nodeTo = node.to; // Taking one character off of ^? to position this. const targetChar = nodeTo - 2; const sourceLine = doc.lineAt(targetChar); // TODO: may want to use countColumn here to make this // work with tab indentation // I do care about the visual alignment here, if you have some // indented line with tabs, then the ^? should show what is // visually above it. const col = targetChar - sourceLine.from; // Now find the position of the node above. const targetLine = doc.line(sourceLine.number - 1); const targetPosition = targetLine.from + col; promises.push( config.worker .getHover({ path: config.path, pos: targetPosition, }) .then((hoverInfo) => { const displayParts = hoverInfo?.quickInfo?.displayParts; if (!displayParts) return null; return { from: nodeTo, text: formatDisplayParts(displayParts), }; }), ); } else { // Pass } } }, }); } Promise.all(promises).then((states) => { config.log?.("tsTwoslash: got data", { states }); view.dispatch({ effects: setTwoSlashes.of(states.filter((x) => x !== null)), }); }); }
// https://github.com/microsoft/TypeScript-Website/blob/v2/packages/playground/src/twoslashInlays.ts
https://github.com/val-town/codemirror-ts/blob/f91a46e7dd8c4bba7591d2c713466ce795a21e9f/src/twoslash/tsTwoslash.ts#L64-L121
f91a46e7dd8c4bba7591d2c713466ce795a21e9f
tailwind-nextjs-starter-blog-i18n
github_2023
PxlSyl
typescript
createTagCount
function createTagCount(allBlogs) { const tagCount = { [fallbackLng]: {}, [secondLng]: {}, } allBlogs.forEach((file) => { if (file.tags && (!isProduction || file.draft !== true)) { file.tags.forEach((tag: string) => { const formattedTag = slug(tag) if (file.language === fallbackLng) { tagCount[fallbackLng][formattedTag] = (tagCount[fallbackLng][formattedTag] || 0) + 1 } else if (file.language === secondLng) { tagCount[secondLng][formattedTag] = (tagCount[secondLng][formattedTag] || 0) + 1 } }) } }) writeFileSync('./app/[locale]/tag-data.json', JSON.stringify(tagCount)) }
/** * Count the occurrences of all tags across blog posts and write to json file * Add logic to your own locales and project */
https://github.com/PxlSyl/tailwind-nextjs-starter-blog-i18n/blob/3f55faa95469e4b902c74f9c86260a3910b91ba4/contentlayer.config.ts#L75-L95
3f55faa95469e4b902c74f9c86260a3910b91ba4
tailwind-nextjs-starter-blog-i18n
github_2023
PxlSyl
typescript
initI18next
const initI18next = async (lang: LocaleTypes, ns: string) => { const i18nInstance = createInstance() await i18nInstance .use(initReactI18next) .use( resourcesToBackend( (language: string, namespace: typeof ns) => // load the translation file depending on the language and namespace import(`./locales/${language}/${namespace}.json`) ) ) .init(getOptions(lang, ns)) return i18nInstance }
// Initialize the i18n instance
https://github.com/PxlSyl/tailwind-nextjs-starter-blog-i18n/blob/3f55faa95469e4b902c74f9c86260a3910b91ba4/app/[locale]/i18n/server.ts#L7-L21
3f55faa95469e4b902c74f9c86260a3910b91ba4
clickhouse-monitoring
github_2023
duyet
typescript
handleResize
function handleResize() { if (contentRef && contentRef.current) { setClamped( contentRef.current.scrollHeight > contentRef.current.clientHeight ) } }
// Function that should be called on window resize
https://github.com/duyet/clickhouse-monitoring/blob/75597792b356d205932e6cb4111e5b63062a80dc/components/truncated-paragraph.tsx#L23-L29
75597792b356d205932e6cb4111e5b63062a80dc
inertia
github_2023
adonisjs
typescript
defineExampleRoute
async function defineExampleRoute(command: Configure, codemods: Codemods) { const tsMorph = await codemods.getTsMorphProject() const routesFile = tsMorph?.getSourceFile(command.app.makePath('./start/routes.ts')) if (!routesFile) { return command.logger.warning('Unable to find the routes file') } const action = command.logger.action('update start/routes.ts file') try { routesFile?.addStatements((writer) => { writer.writeLine(`router.on('/').renderInertia('home')`) }) await tsMorph?.save() action.succeeded() } catch (error) { codemods.emit('error', error) action.failed(error.message) } }
/** * Adds the example route to the routes file */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/configure.ts#L106-L126
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
InertiaProvider.registerEdgePlugin
protected async registerEdgePlugin() { if (!this.app.usingEdgeJS) return const edgeExports = await import('edge.js') const { edgePluginInertia } = await import('../src/plugins/edge/plugin.js') edgeExports.default.use(edgePluginInertia()) }
/** * Registers edge plugin when edge is installed */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/providers/inertia_provider.ts#L43-L49
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
InertiaProvider.register
async register() { this.app.container.singleton(InertiaMiddleware, async () => { const inertiaConfigProvider = this.app.config.get<InertiaConfig>('inertia') const config = await configProvider.resolve<ResolvedConfig>(this.app, inertiaConfigProvider) const vite = await this.app.container.make('vite') if (!config) { throw new RuntimeException( 'Invalid "config/inertia.ts" file. Make sure you are using the "defineConfig" method' ) } return new InertiaMiddleware(config, vite) }) }
/** * Register inertia middleware */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/providers/inertia_provider.ts#L54-L68
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
InertiaProvider.boot
async boot() { await this.registerEdgePlugin() /** * Adding brisk route to render inertia pages * without an explicit handler */ BriskRoute.macro('renderInertia', function (this: BriskRoute, template, props, viewProps) { return this.setHandler(({ inertia }) => { return inertia.render(template, props, viewProps) }) }) }
/** * Register edge plugin and brisk route macro */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/providers/inertia_provider.ts#L73-L85
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
FilesDetector.detectEntrypoint
async detectEntrypoint(defaultPath: string) { const possiblesLocations = [ './inertia/app/app.ts', './inertia/app/app.tsx', './resources/app.ts', './resources/app.tsx', './resources/app.jsx', './resources/app.js', './inertia/app/app.jsx', ] const path = await locatePath(possiblesLocations, { cwd: this.app.appRoot }) return this.app.makePath(path || defaultPath) }
/** * Try to locate the entrypoint file based * on the conventional locations */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/files_detector.ts#L20-L33
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
FilesDetector.detectSsrEntrypoint
async detectSsrEntrypoint(defaultPath: string) { const possiblesLocations = [ './inertia/app/ssr.ts', './inertia/app/ssr.tsx', './resources/ssr.ts', './resources/ssr.tsx', './resources/ssr.jsx', './resources/ssr.js', './inertia/app/ssr.jsx', ] const path = await locatePath(possiblesLocations, { cwd: this.app.appRoot }) return this.app.makePath(path || defaultPath) }
/** * Try to locate the SSR entrypoint file based * on the conventional locations */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/files_detector.ts#L39-L52
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
FilesDetector.detectSsrBundle
async detectSsrBundle(defaultPath: string) { const possiblesLocations = ['./ssr/ssr.js', './ssr/ssr.mjs'] const path = await locatePath(possiblesLocations, { cwd: this.app.appRoot }) return this.app.makePath(path || defaultPath) }
/** * Try to locate the SSR bundle file based * on the conventional locations */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/files_detector.ts#L58-L63
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.share
share(data: Record<string, Data>) { this.#sharedData = { ...this.#sharedData, ...data } }
/** * Share data for the current request. * This data will override any shared data defined in the config. */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L283-L285
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.render
async render< TPageProps extends Record<string, any> = {}, TViewProps extends Record<string, any> = {}, >( component: string, pageProps?: TPageProps, viewProps?: TViewProps ): Promise<string | PageObject<TPageProps>> { const pageObject = await this.#buildPageObject(component, pageProps) const isInertiaRequest = !!this.ctx.request.header(InertiaHeaders.Inertia) if (!isInertiaRequest) { const shouldRenderOnServer = await this.#shouldRenderOnServer(component) if (shouldRenderOnServer) return this.#renderOnServer(pageObject, viewProps) return this.ctx.view.render(this.#resolveRootView(), { ...viewProps, page: pageObject }) } this.ctx.response.header(InertiaHeaders.Inertia, 'true') return pageObject }
/** * Render a page using Inertia */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L290-L310
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.clearHistory
clearHistory() { this.#shouldClearHistory = true }
/** * Clear history state. * * See https://v2.inertiajs.com/history-encryption#clearing-history */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L317-L319
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.encryptHistory
encryptHistory(encrypt = true) { this.#shouldEncryptHistory = encrypt }
/** * Encrypt history * * See https://v2.inertiajs.com/history-encryption */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L326-L328
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.lazy
lazy<T>(callback: () => MaybePromise<T>) { return new OptionalProp(callback) }
/** * Create a lazy prop * * Lazy props are never resolved on first visit, but only when the client * request a partial reload explicitely with this value. * * See https://inertiajs.com/partial-reloads#lazy-data-evaluation * * @deprecated use `optional` instead */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L340-L342
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.optional
optional<T>(callback: () => MaybePromise<T>) { return new OptionalProp(callback) }
/** * Create an optional prop * * See https://inertiajs.com/partial-reloads#lazy-data-evaluation */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L349-L351
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.merge
merge<T>(callback: () => MaybePromise<T>) { return new MergeProp(callback) }
/** * Create a mergeable prop * * See https://v2.inertiajs.com/merging-props */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L358-L360
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.always
always<T>(callback: () => MaybePromise<T>) { return new AlwaysProp(callback) }
/** * Create an always prop * * Always props are resolved on every request, no matter if it's a partial * request or not. * * See https://inertiajs.com/partial-reloads#lazy-data-evaluation */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L370-L372
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.defer
defer<T>(callback: () => MaybePromise<T>, group = 'default') { return new DeferProp(callback, group) }
/** * Create a deferred prop * * Deferred props feature allows you to defer the loading of certain * page data until after the initial page render. * * See https://v2.inertiajs.com/deferred-props */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L382-L384
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
Inertia.location
async location(url: string) { this.ctx.response.header(InertiaHeaders.Location, url) this.ctx.response.status(409) }
/** * This method can be used to redirect the user to an external website * or even a non-inertia route of your application. * * See https://inertiajs.com/redirects#external-redirects */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/inertia.ts#L392-L395
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
ServerRenderer.render
async render(pageObject: PageObject) { let render: { default: RenderInertiaSsrApp } const devServer = this.vite?.getDevServer() /** * Use the Vite Runtime API to execute the entrypoint * if we are in development mode */ if (devServer) { ServerRenderer.runtime ??= await this.vite!.createModuleRunner() ServerRenderer.runtime.clearCache() render = await ServerRenderer.runtime.import(this.config.ssr.entrypoint!) } else { /** * Otherwise, just import the SSR bundle */ render = await import(pathToFileURL(this.config.ssr.bundle).href) } /** * Call the render function and return head and body */ const result = await render.default(pageObject) return { head: result.head, body: result.body } }
/** * Render the page on the server * * On development, we use the Vite Runtime API * On production, we just import and use the SSR bundle generated by Vite */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/server_renderer.ts#L37-L61
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
VersionCache.computeVersion
async computeVersion() { if (!this.assetsVersion) await this.#getManifestHash() return this }
/** * Pre-compute the version */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/version_cache.ts#L54-L57
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
VersionCache.getVersion
getVersion() { if (!this.#cachedVersion) throw new Error('Version has not been computed yet') return this.#cachedVersion }
/** * Returns the current assets version */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/version_cache.ts#L62-L65
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
VersionCache.setVersion
async setVersion(version: AssetsVersion) { this.#cachedVersion = version }
/** * Set the assets version */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/version_cache.ts#L70-L72
b3ded845557c5aa9d3715069d1f8f14a4857ed64
inertia
github_2023
adonisjs
typescript
ensureIsInertiaResponse
function ensureIsInertiaResponse(this: ApiResponse) { if (!this.header('x-inertia')) { throw new Error( 'Response is not an Inertia response. Make sure to call `withInertia()` on the request' ) } }
/** * Ensure the response is an inertia response, otherwise throw an error */
https://github.com/adonisjs/inertia/blob/b3ded845557c5aa9d3715069d1f8f14a4857ed64/src/plugins/japa/api_client.ts#L62-L68
b3ded845557c5aa9d3715069d1f8f14a4857ed64
Cap
github_2023
CapSoftware
typescript
drawGuideLines
function drawGuideLines({ ctx, bounds, prefersDark }: DrawContext) { ctx.strokeStyle = prefersDark ? "rgba(255, 255, 255, 0.5)" : "rgba(0, 0, 0, 0.5)"; ctx.lineWidth = 1; ctx.setLineDash([5, 2]); // Rule of thirds ctx.beginPath(); for (let i = 1; i < 3; i++) { const x = bounds.x + (bounds.width * i) / 3; ctx.moveTo(x, bounds.y); ctx.lineTo(x, bounds.y + bounds.height); } ctx.stroke(); ctx.beginPath(); for (let i = 1; i < 3; i++) { const y = bounds.y + (bounds.height * i) / 3; ctx.moveTo(bounds.x, y); ctx.lineTo(bounds.x + bounds.width, y); } ctx.stroke(); // Center crosshair const centerX = Math.round(bounds.x + bounds.width / 2); const centerY = Math.round(bounds.y + bounds.height / 2); ctx.setLineDash([]); ctx.lineWidth = 2; const crosshairLength = 7; ctx.beginPath(); ctx.moveTo(centerX - crosshairLength, centerY); ctx.lineTo(centerX + crosshairLength, centerY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(centerX, centerY - crosshairLength); ctx.lineTo(centerX, centerY + crosshairLength); ctx.stroke(); }
// Rule of thirds guide lines and center crosshair
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/desktop/src/components/CropAreaRenderer.tsx#L122-L163
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
Cap
github_2023
CapSoftware
typescript
draw
function draw( ctx: CanvasRenderingContext2D, bounds: Bounds, radius: number, guideLines: boolean, showHandles: boolean, highlighted: boolean, selected: boolean, prefersDark: boolean ) { if (bounds.width <= 0 || bounds.height <= 0) return; const drawContext: DrawContext = { ctx, bounds, radius, prefersDark, highlighted, selected, }; ctx.save(); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = "rgba(0, 0, 0, 0.65)"; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Shadow ctx.save(); ctx.shadowColor = "rgba(0, 0, 0, 0.8)"; ctx.shadowBlur = 200; ctx.shadowOffsetY = 25; ctx.beginPath(); ctx.roundRect(bounds.x, bounds.y, bounds.width, bounds.height, radius); ctx.fill(); ctx.restore(); if (showHandles) drawHandles(drawContext); ctx.beginPath(); ctx.roundRect(bounds.x, bounds.y, bounds.width, bounds.height, radius); ctx.clip(); ctx.clearRect(bounds.x, bounds.y, bounds.width, bounds.height); if (guideLines) drawGuideLines(drawContext); ctx.restore(); }
// Main draw function
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/desktop/src/components/CropAreaRenderer.tsx#L166-L212
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
Cap
github_2023
CapSoftware
typescript
radioGroupOnChange
const radioGroupOnChange = async (photoUrl: string) => { try { const wallpaper = wallpapers()?.find((w) => w.url === photoUrl); if (!wallpaper) return; // Get the raw path without any URL prefixes const rawPath = decodeURIComponent( photoUrl.replace("file://", "") ); debouncedSetProject(rawPath); } catch (err) { toast.error("Failed to set wallpaper"); } };
// Directly trigger the radio group's onChange handler
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/desktop/src/routes/editor/ConfigSidebar.tsx#L236-L250
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
Cap
github_2023
CapSoftware
typescript
polyfillCanvasContextRoundRect
function polyfillCanvasContextRoundRect() { if ("roundRect" in CanvasRenderingContext2D) return; CanvasRenderingContext2D.prototype.roundRect = function ( x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable<number | DOMPointInit> ) { this.beginPath(); let radius = typeof radii === "number" ? radii : 0; if (typeof radii === "object") { if (Symbol.iterator in radii) { const radiiArray = Array.from(radii) as number[]; radius = radiiArray[0] || 0; } else if ("x" in radii && "y" in radii) { radius = radii.x!; } } const adjustedRadius = Math.min(radius, w / 2, h / 2); this.moveTo(x + adjustedRadius, y); this.arcTo(x + w, y, x + w, y + h, adjustedRadius); this.arcTo(x + w, y + h, x, y + h, adjustedRadius); this.arcTo(x, y + h, x, y, adjustedRadius); this.arcTo(x, y, x + w, y, adjustedRadius); this.closePath(); }; }
// TODO: May not be needed depending on the minimum macOS version.
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/desktop/src/utils/canvas.ts#L41-L71
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
Cap
github_2023
CapSoftware
typescript
getAbsolutePath
function getAbsolutePath(value: string): any { return dirname(require.resolve(join(value, "package.json"))); }
/** * This function is used to resolve the absolute path of a package. * It is needed in projects that use Yarn PnP or are set up within a monorepo. */
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/storybook/.storybook/main.ts#L9-L11
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
Cap
github_2023
CapSoftware
typescript
findUserWithRetry
async function findUserWithRetry( email: string, userId?: string, maxRetries = 5 ): Promise<typeof users.$inferSelect | null> { for (let i = 0; i < maxRetries; i++) { console.log(`[Attempt ${i + 1}/${maxRetries}] Looking for user:`, { email, userId, }); try { // Try finding by userId first if available if (userId) { console.log(`Attempting to find user by ID: ${userId}`); const userById = await db .select() .from(users) .where(eq(users.id, userId)) .limit(1) .then((rows) => rows[0] ?? null); if (userById) { console.log(`Found user by ID: ${userId}`); return userById; } console.log(`No user found by ID: ${userId}`); } // If not found by ID or no ID provided, try email if (email) { console.log(`Attempting to find user by email: ${email}`); const userByEmail = await db .select() .from(users) .where(eq(users.email, email)) .limit(1) .then((rows) => rows[0] ?? null); if (userByEmail) { console.log(`Found user by email: ${email}`); return userByEmail; } console.log(`No user found by email: ${email}`); } // If we reach here, no user was found on this attempt if (i < maxRetries - 1) { const delay = Math.pow(2, i) * 3000; // 3s, 6s, 12s, 24s, 48s console.log( `No user found on attempt ${ i + 1 }. Waiting ${delay}ms before retry...` ); await new Promise((resolve) => setTimeout(resolve, delay)); } } catch (error) { console.error(`Error during attempt ${i + 1}:`, error); // If this is not the last attempt, continue to next retry if (i < maxRetries - 1) { const delay = Math.pow(2, i) * 3000; await new Promise((resolve) => setTimeout(resolve, delay)); continue; } } } console.log("All attempts exhausted. No user found."); return null; }
// Helper function to find user with retries
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/web/app/api/webhooks/stripe/route.ts#L16-L85
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
Cap
github_2023
CapSoftware
typescript
fetchTranscript
const fetchTranscript = async () => { const transcriptionUrl = data.bucket && data.awsBucket !== clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET ? `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription` : `${S3_BUCKET_URL}/${data.ownerId}/${data.id}/transcription.vtt`; try { const response = await fetch(transcriptionUrl); const vttContent = await response.text(); const parsed = parseVTT(vttContent); setTranscriptData(parsed); } catch (error) { console.error("Error resetting transcript:", error); } setIsLoading(false); };
// Re-fetch the transcript
https://github.com/CapSoftware/Cap/blob/fa735f60d2e8af1247ca9127b84aad7dd86f17c3/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx#L189-L204
fa735f60d2e8af1247ca9127b84aad7dd86f17c3
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
R2Client
const R2Client = () => { const accountId = process.env.R2_ACCOUNT_ID; const accessKeyId = process.env.R2_KEY_ID; const accessKeySecret = process.env.R2_KEY_SECRET; const endpoint = new AWS.Endpoint(`https://${accountId}.r2.cloudflarestorage.com`); const s3 = new AWS.S3({ endpoint: endpoint, region: 'auto', credentials: new AWS.Credentials(accessKeyId, accessKeySecret), signatureVersion: 'v4', }); return s3; };
// R2Client function
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/service/src/index.ts#L222-L234
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
chatSetting.constructor
constructor(uuid: number) { this.uuid = uuid; //this.gptConfig = gptConfigStore.myData; //this.init(); }
// 构造函数
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/chat.ts#L18-L22
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
chatSetting.getObjs
public getObjs():gptConfigType[]{ const now= Math.floor(Date.now() / 1) const dt= now- this.time_limit; mlog("toMyuid15","getObjs", this.uuid , dt) if(dt<500 ){ //防止卡死 return this.mObj ; } this.time_limit=now ; const obj = ss.get( this.localKey ) as undefined| gptConfigType[]; this.mObj= obj? obj:[] return this.mObj; }
//卡死 可疑点
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/chat.ts#L40-L53
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
uploadR2
function uploadR2(file: File) { return new Promise<any>((resolve, reject) => { //预签名 axios.post(gptGetUrl("/pre_signed"), { file_name: file.name, content_type: file.type }, { headers: { 'Content-Type': 'application/json' } }).then(response => { if (response.data.status == "Success") { const signedUrl = response.data.data.up; //上传 fetch(signedUrl, { method: 'PUT', body: file, headers: { 'Content-Type': file.type, }, }).then(res2 => { if (res2.ok) { console.log('Upload successful!', response.data.data.url); return resolve({ url: response.data.data.url }); } else { return reject(res2) } }).catch(error => { return reject(error) }); } else { return reject(response.data); } } ).catch(error => reject(error)); }); }
// 前端直传 cloudflare r2
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/openapi.ts#L102-L134
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
upLoaderR2
const upLoaderR2= ()=>{ const file = FormData.get('file') as File; return uploadR2(file); }
//R2上传
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/openapi.ts#L139-L142
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
uploadNomalDo
const uploadNomalDo = (url:string, headers:any)=>{ return new Promise<any>((resolve, reject) => { axios.post( url , FormData, { headers }).then(response => resolve(response.data ) ).catch(error =>reject(error) ); }) }
//执行上传
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/openapi.ts#L145-L152
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
uploadNomal
const uploadNomal= (url:string)=>{ url= gptServerStore.myData.UPLOADER_URL? gptServerStore.myData.UPLOADER_URL : gptGetUrl( url ); let headers= {'Content-Type': 'multipart/form-data' } if(gptServerStore.myData.OPENAI_API_BASE_URL && url.indexOf(gptServerStore.myData.OPENAI_API_BASE_URL)>-1 ) { headers={...headers,...getHeaderAuthorization()} }else{ const authStore = useAuthStore() if( authStore.token ) { const header2={ 'x-ptoken': authStore.token }; headers= {...headers, ...header2} } } if( homeStore.myData.vtoken ){ const vtokenh={ 'x-vtoken': homeStore.myData.vtoken }; headers= {...headers, ...vtokenh} } return uploadNomalDo(url,headers ); }
//除R2外默认流程
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/openapi.ts#L155-L174
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
getHeaderAuthorization
function getHeaderAuthorization(){ let headers={} if( homeStore.myData.vtoken ){ const vtokenh={ 'x-vtoken': homeStore.myData.vtoken ,'x-ctoken': homeStore.myData.ctoken}; headers= {...headers, ...vtokenh} } if(!gptServerStore.myData.KLING_KEY){ const authStore = useAuthStore() if( authStore.token ) { const bmi= { 'x-ptoken': authStore.token }; headers= {...headers, ...bmi } return headers; } return headers } const bmi={ 'Authorization': 'Bearer ' +gptServerStore.myData.PIXVERSE_KEY } headers= {...headers, ...bmi } return headers }
// import { KlingTask, klingStore } from "./klingStore";
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/pixverse.ts#L10-L30
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
feed
const feed = (chunk: string) => { let response = null try { response = JSON.parse(chunk) } catch { // ignore } if (response?.detail?.type === 'invalid_request_error') { const msg = `ChatGPT error ${response.detail.message}: ${response.detail.code} (${response.detail.type})` const error = new types.ChatGPTError(msg, { cause: response }) error.statusCode = response.detail.code error.statusText = response.detail.message if (onError) { onError(error) } else { console.error(error) } // don't feed to the event parser return } parser.feed(chunk) }
// handle special response errors
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/api/sse/fetchsse.ts#L49-L75
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
naiveStyleOverride
function naiveStyleOverride() { const meta = document.createElement('meta') meta.name = 'naive-ui-style' document.head.appendChild(meta) }
/** Tailwind's Preflight Style Override */
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/plugins/assets.ts#L8-L12
33ca008832510af2c5bc4d07082dd7055c324c84
chatgpt-web-midjourney-proxy
github_2023
Dooy
typescript
normalizeArray
const normalizeArray = ( data: Float32Array, m: number, downsamplePeaks: boolean = false, memoize: boolean = false ) => { let cache, mKey, dKey; if (memoize) { mKey = m.toString(); dKey = downsamplePeaks.toString(); cache = dataMap.has(data) ? dataMap.get(data) : {}; dataMap.set(data, cache); cache[mKey] = cache[mKey] || {}; if (cache[mKey][dKey]) { return cache[mKey][dKey]; } } const n = data.length; const result = new Array(m); if (m <= n) { // Downsampling result.fill(0); const count = new Array(m).fill(0); for (let i = 0; i < n; i++) { const index = Math.floor(i * (m / n)); if (downsamplePeaks) { // take highest result in the set result[index] = Math.max(result[index], Math.abs(data[i])); } else { result[index] += Math.abs(data[i]); } count[index]++; } if (!downsamplePeaks) { for (let i = 0; i < result.length; i++) { result[i] = result[i] / count[i]; } } } else { for (let i = 0; i < m; i++) { const index = (i * (n - 1)) / (m - 1); const low = Math.floor(index); const high = Math.ceil(index); const t = index - low; if (high >= n) { result[i] = data[n - 1]; } else { result[i] = data[low] * (1 - t) + data[high] * t; } } } if (memoize) { cache[mKey as string][dKey as string] = result; } return result; };
/** * Normalizes a Float32Array to Array(m): We use this to draw amplitudes on a graph * If we're rendering the same audio data, then we'll often be using * the same (data, m, downsamplePeaks) triplets so we give option to memoize */
https://github.com/Dooy/chatgpt-web-midjourney-proxy/blob/33ca008832510af2c5bc4d07082dd7055c324c84/src/utils/wav_renderer.ts#L8-L63
33ca008832510af2c5bc4d07082dd7055c324c84
inpaint-web
github_2023
lxfater
typescript
loadImage
function loadImage(url: string): Promise<HTMLImageElement> { return new Promise((resolve, reject) => { const img = new Image() img.crossOrigin = 'Anonymous' img.onload = () => resolve(img) img.onerror = () => reject(new Error(`Failed to load image from ${url}`)) img.src = url }) }
// ort.env.debug = true
https://github.com/lxfater/inpaint-web/blob/f7ff41f0163fa7e4db47889be18cdba656a728dc/src/adapters/inpainting.ts#L12-L20
f7ff41f0163fa7e4db47889be18cdba656a728dc
inpaint-web
github_2023
lxfater
typescript
getAllFileEntries
async function getAllFileEntries(items: DataTransferItemList) { const fileEntries: Array<File> = [] // Use BFS to traverse entire directory/file structure const queue = [] // Unfortunately items is not iterable i.e. no forEach for (let i = 0; i < items.length; i += 1) { queue.push(items[i].webkitGetAsEntry()) } while (queue.length > 0) { const entry = queue.shift() if (entry?.isFile) { // Only append images const file = await getFile(entry) fileEntries.push(file) } else if (entry?.isDirectory) { queue.push( ...(await readAllDirectoryEntries((entry as any).createReader())) ) } } return fileEntries }
/* eslint-disable no-await-in-loop */
https://github.com/lxfater/inpaint-web/blob/f7ff41f0163fa7e4db47889be18cdba656a728dc/src/components/FileSelect.tsx#L44-L65
f7ff41f0163fa7e4db47889be18cdba656a728dc
inpaint-web
github_2023
lxfater
typescript
readAllDirectoryEntries
async function readAllDirectoryEntries(directoryReader: any) { const entries = [] let readEntries = await readEntriesPromise(directoryReader) while (readEntries.length > 0) { entries.push(...readEntries) readEntries = await readEntriesPromise(directoryReader) } return entries }
// Get all the entries (files or sub-directories) in a directory
https://github.com/lxfater/inpaint-web/blob/f7ff41f0163fa7e4db47889be18cdba656a728dc/src/components/FileSelect.tsx#L69-L77
f7ff41f0163fa7e4db47889be18cdba656a728dc
inpaint-web
github_2023
lxfater
typescript
readEntriesPromise
async function readEntriesPromise(directoryReader: any): Promise<any> { return new Promise((resolve, reject) => { directoryReader.readEntries(resolve, reject) }) }
/* eslint-enable no-await-in-loop */
https://github.com/lxfater/inpaint-web/blob/f7ff41f0163fa7e4db47889be18cdba656a728dc/src/components/FileSelect.tsx#L84-L88
f7ff41f0163fa7e4db47889be18cdba656a728dc
IronCalc
github_2023
ironcalc
typescript
useKeyboardNavigation
const useKeyboardNavigation = ( options: Options, ): { onKeyDown: (event: KeyboardEvent) => void } => { const onKeyDown = useCallback( (event: KeyboardEvent) => { const { key } = event; const { root } = options; // Silence the linter if (!root.current) { return; } if (event.target !== root.current) { return; } if (event.metaKey || event.ctrlKey) { switch (key) { case "z": { options.onUndo(); event.stopPropagation(); event.preventDefault(); break; } case "y": { options.onRedo(); event.stopPropagation(); event.preventDefault(); break; } case "b": { options.onBold(); event.stopPropagation(); event.preventDefault(); break; } case "i": { options.onItalic(); event.stopPropagation(); event.preventDefault(); break; } case "u": { options.onUnderline(); event.stopPropagation(); event.preventDefault(); break; } case "a": { // TODO: Area selection. CTRL+A should select "continuous" area around the selection, // if it does exist then whole sheet is selected. event.stopPropagation(); event.preventDefault(); break; } // No default } if (isNavigationKey(key)) { // Ctrl+Arrows, Ctrl+Home/End options.onNavigationToEdge(key); // navigate_to_edge_in_direction event.stopPropagation(); event.preventDefault(); } return; } if (event.altKey) { switch (key) { case "ArrowDown": { // select next sheet options.onNextSheet(); event.stopPropagation(); event.preventDefault(); break; } case "ArrowUp": { // select previous sheet options.onPreviousSheet(); event.stopPropagation(); event.preventDefault(); break; } } } if (key === "F2") { options.onCellEditStart(); event.stopPropagation(); event.preventDefault(); return; } if (isEditingKey(key) || key === "Backspace") { const initText = key === "Backspace" ? "" : key; options.onEditKeyPressStart(initText); event.stopPropagation(); event.preventDefault(); return; } // Worksheet Navigation if (event.shiftKey) { if ( key === "ArrowRight" || key === "ArrowLeft" || key === "ArrowUp" || key === "ArrowDown" ) { options.onExpandAreaSelectedKeyboard(key); } else if (key === "Tab") { options.onArrowLeft(); event.stopPropagation(); event.preventDefault(); } return; } switch (key) { case "ArrowRight": case "Tab": { options.onArrowRight(); break; } case "ArrowLeft": { options.onArrowLeft(); break; } case "ArrowDown": case "Enter": { options.onArrowDown(); break; } case "ArrowUp": { options.onArrowUp(); break; } case "End": { options.onKeyEnd(); break; } case "Home": { options.onKeyHome(); break; } case "Delete": { options.onCellsDeleted(); break; } case "PageDown": { options.onPageDown(); break; } case "PageUp": { options.onPageUp(); break; } case "Escape": { options.onEscape(); } // No default } event.stopPropagation(); event.preventDefault(); }, [options], ); return { onKeyDown }; };
// # IronCalc Keyboard accessibility:
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/useKeyboardNavigation.ts#L60-L235
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
hexToRGBA10Percent
function hexToRGBA10Percent(colorHex: string): string { // Remove the leading hash (#) if present const hex = colorHex.replace(/^#/, ""); // Parse the hex color const red = Number.parseInt(hex.substring(0, 2), 16); const green = Number.parseInt(hex.substring(2, 4), 16); const blue = Number.parseInt(hex.substring(4, 6), 16); // Set the alpha (opacity) to 0.1 (10%) const alpha = 0.1; // Return the RGBA color string return `rgba(${red}, ${green}, ${blue}, ${alpha})`; }
// Get a 10% transparency of an hex color
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L56-L70
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getFrozenRowsHeight
getFrozenRowsHeight(): number { const frozenRows = this.model.getFrozenRowsCount( this.model.getSelectedSheet(), ); if (frozenRows === 0) { return 0; } let frozenRowsHeight = 0; for (let row = 1; row <= frozenRows; row += 1) { frozenRowsHeight += this.getRowHeight(this.model.getSelectedSheet(), row); } return frozenRowsHeight + frozenSeparatorWidth; }
/** * This is the height of the frozen rows including the width of the separator * It returns 0 if the are no frozen rows */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L187-L199
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getFrozenColumnsWidth
getFrozenColumnsWidth(): number { const frozenColumns = this.model.getFrozenColumnsCount( this.model.getSelectedSheet(), ); if (frozenColumns === 0) { return 0; } let frozenColumnsWidth = 0; for (let column = 1; column <= frozenColumns; column += 1) { frozenColumnsWidth += this.getColumnWidth( this.model.getSelectedSheet(), column, ); } return frozenColumnsWidth + frozenSeparatorWidth; }
/** * This is the width of the frozen columns including the width of the separator * It returns 0 if the are no frozen columns */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L205-L220
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getVisibleCells
getVisibleCells(): { topLeftCell: Cell; bottomRightCell: Cell; } { const view = this.model.getSelectedView(); const selectedSheet = view.sheet; const frozenRows = this.model.getFrozenRowsCount(selectedSheet); const frozenColumns = this.model.getFrozenColumnsCount(selectedSheet); const rowTop = Math.max(frozenRows + 1, view.top_row); let rowBottom = rowTop; const columnLeft = Math.max(frozenColumns + 1, view.left_column); let columnRight = columnLeft; const frozenColumnsWidth = this.getFrozenColumnsWidth(); const frozenRowsHeight = this.getFrozenRowsHeight(); let y = headerRowHeight + frozenRowsHeight; for (let row = rowTop; row <= LAST_ROW; row += 1) { const rowHeight = this.getRowHeight(selectedSheet, row); if (y >= this.height - rowHeight || row === LAST_ROW) { rowBottom = row; break; } y += rowHeight; } let x = headerColumnWidth + frozenColumnsWidth; for (let column = columnLeft; column <= LAST_COLUMN; column += 1) { const columnWidth = this.getColumnWidth(selectedSheet, column); if (x >= this.width - columnWidth || column === LAST_COLUMN) { columnRight = column; break; } x += columnWidth; } const cells = { topLeftCell: { row: rowTop, column: columnLeft }, bottomRightCell: { row: rowBottom, column: columnRight }, }; return cells; }
// Get the visible cells (aside from the frozen rows and columns)
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L223-L263
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getBoundedRow
getBoundedRow(maxTop: number): { row: number; top: number } { const selectedSheet = this.model.getSelectedSheet(); let top = 0; let row = 1 + this.model.getFrozenRowsCount(selectedSheet); while (row <= LAST_ROW && top <= maxTop) { const height = this.getRowHeight(selectedSheet, row); if (top + height <= maxTop) { top += height; } else { break; } row += 1; } return { row, top }; }
/** * Returns the {row, top} of the row whose upper y coordinate (top) is maximum and less or equal than maxTop * Both top and maxTop are absolute coordinates */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L269-L283
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getMinScrollLeft
getMinScrollLeft(targetColumn: number): number { const columnStart = 1 + this.model.getFrozenColumnsCount(this.model.getSelectedSheet()); /** Distance from the first non frozen cell to the right border of column*/ let distance = 0; for (let column = columnStart; column <= targetColumn; column += 1) { const width = this.getColumnWidth(this.model.getSelectedSheet(), column); distance += width; } /** Minimum we need to scroll so that `column` is visible */ const minLeft = distance - this.width + this.getFrozenColumnsWidth() + headerColumnWidth; // Because scrolling is quantified, we only scroll whole columns, // we need to find the minimum quantum that is larger than minLeft let left = 0; for (let column = columnStart; column <= LAST_COLUMN; column += 1) { const width = this.getColumnWidth(this.model.getSelectedSheet(), column); if (left < minLeft) { left += width; } else { break; } } return left; }
/** * Returns the minimum we can scroll to the left so that * targetColumn is fully visible. * Returns the the first visible column and the scrollLeft position */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L306-L331
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.addColumnResizeHandle
private addColumnResizeHandle( x: number, column: number, columnWidth: number, ): void { const div = document.createElement("div"); div.className = "column-resize-handle"; div.style.left = `${x - 1}px`; div.style.height = `${headerRowHeight}px`; this.columnHeaders.insertBefore(div, null); let initPageX = 0; const resizeHandleMove = (event: MouseEvent): void => { if (columnWidth + event.pageX - initPageX > 0) { div.style.left = `${x + event.pageX - initPageX - 1}px`; this.columnGuide.style.left = `${ headerColumnWidth + x + event.pageX - initPageX }px`; } }; let resizeHandleUp = (event: MouseEvent): void => { div.style.opacity = "0"; this.columnGuide.style.display = "none"; document.removeEventListener("mousemove", resizeHandleMove); document.removeEventListener("mouseup", resizeHandleUp); const newColumnWidth = columnWidth + event.pageX - initPageX; this.onColumnWidthChanges( this.model.getSelectedSheet(), column, newColumnWidth, ); }; resizeHandleUp = resizeHandleUp.bind(this); div.addEventListener("mousedown", (event) => { div.style.opacity = "1"; this.columnGuide.style.display = "block"; this.columnGuide.style.left = `${headerColumnWidth + x}px`; initPageX = event.pageX; document.addEventListener("mousemove", resizeHandleMove); document.addEventListener("mouseup", resizeHandleUp); }); }
// Column and row headers with their handles
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L557-L598
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
resizeHandleMove
const resizeHandleMove = (event: MouseEvent): void => { if (rowHeight + event.pageY - initPageY > 0) { div.style.top = `${y + event.pageY - initPageY - 1}px`; this.rowGuide.style.top = `${y + event.pageY - initPageY}px`; } };
/* istanbul ignore next */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L609-L614
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getClipCSS
private getClipCSS( x: number, y: number, width: number, height: number, includeFrozenRows: boolean, includeFrozenColumns: boolean, ): string { if (!includeFrozenRows && !includeFrozenColumns) { return ""; } const frozenColumnsWidth = includeFrozenColumns ? this.getFrozenColumnsWidth() : 0; const frozenRowsHeight = includeFrozenRows ? this.getFrozenRowsHeight() : 0; const yMinCanvas = headerRowHeight + frozenRowsHeight; const xMinCanvas = headerColumnWidth + frozenColumnsWidth; const xMaxCanvas = xMinCanvas + this.width - headerColumnWidth - frozenColumnsWidth; const yMaxCanvas = yMinCanvas + this.height - headerRowHeight - frozenRowsHeight; const topClip = y < yMinCanvas ? yMinCanvas - y : 0; const leftClip = x < xMinCanvas ? xMinCanvas - x : 0; // We don't strictly need to clip on the right and bottom edges because // text is hidden anyway const rightClip = x + width > xMaxCanvas ? xMaxCanvas - x : width + 4; const bottomClip = y + height > yMaxCanvas ? yMaxCanvas - y : height + 4; return `rect(${topClip}px ${rightClip}px ${bottomClip}px ${leftClip}px)`; }
/** * Returns the css clip in the canvas of an html element * This is used so we do not see the outlines in the row and column headers * NB: A _different_ (better!) approach would be to have separate canvases for the headers * Then the sheet canvas would have it's own bounding box. * That's tomorrows problem. * PS: Please, do not use this function. If at all we can use the clip-path property */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L816-L847
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getCoordinatesByCell
getCoordinatesByCell(row: number, column: number): [number, number] { const selectedSheet = this.model.getSelectedSheet(); const frozenColumns = this.model.getFrozenColumnsCount(selectedSheet); const frozenColumnsWidth = this.getFrozenColumnsWidth(); const frozenRows = this.model.getFrozenRowsCount(selectedSheet); const frozenRowsHeight = this.getFrozenRowsHeight(); const { topLeftCell } = this.getVisibleCells(); let x: number; let y: number; if (row <= frozenRows) { // row is one of the frozen rows y = headerRowHeight; for (let r = 1; r < row; r += 1) { y += this.getRowHeight(selectedSheet, r); } } else if (row >= topLeftCell.row) { // row is bellow the frozen rows y = headerRowHeight + frozenRowsHeight; for (let r = topLeftCell.row; r < row; r += 1) { y += this.getRowHeight(selectedSheet, r); } } else { // row is _above_ the frozen rows y = headerRowHeight + frozenRowsHeight; for (let r = topLeftCell.row; r > row; r -= 1) { y -= this.getRowHeight(selectedSheet, r - 1); } } if (column <= frozenColumns) { // It is one of the frozen columns x = headerColumnWidth; for (let c = 1; c < column; c += 1) { x += this.getColumnWidth(selectedSheet, c); } } else if (column >= topLeftCell.column) { // column is to the right of the frozen columns x = headerColumnWidth + frozenColumnsWidth; for (let c = topLeftCell.column; c < column; c += 1) { x += this.getColumnWidth(selectedSheet, c); } } else { // column is to the left of the frozen columns x = headerColumnWidth + frozenColumnsWidth; for (let c = topLeftCell.column; c > column; c -= 1) { x -= this.getColumnWidth(selectedSheet, c - 1); } } return [Math.floor(x), Math.floor(y)]; }
/** * Returns the coordinates relative to the canvas. * (headerColumnWidth, headerRowHeight) being the coordinates * for the top left corner of the first visible cell */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L897-L945
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
WorksheetCanvas.getCellByCoordinates
getCellByCoordinates( x: number, y: number, ): { row: number; column: number } | null { const frozenColumns = this.model.getFrozenColumnsCount( this.model.getSelectedSheet(), ); const frozenColumnsWidth = this.getFrozenColumnsWidth(); const frozenRows = this.model.getFrozenRowsCount( this.model.getSelectedSheet(), ); const frozenRowsHeight = this.getFrozenRowsHeight(); let column = 0; let cellX = headerColumnWidth; const { topLeftCell } = this.getVisibleCells(); if (x < headerColumnWidth) { column = topLeftCell.column; while (cellX >= x) { column -= 1; if (column < 1) { column = 1; break; } cellX -= this.getColumnWidth(this.model.getSelectedSheet(), column); } } else if (x < headerColumnWidth + frozenColumnsWidth) { while (cellX <= x) { column += 1; cellX += this.getColumnWidth(this.model.getSelectedSheet(), column); // This cannot happen (would mean cellX > headerColumnWidth + frozenColumnsWidth) if (column > frozenColumns) { /* istanbul ignore next */ return null; } } } else { cellX = headerColumnWidth + frozenColumnsWidth; column = topLeftCell.column - 1; while (cellX <= x) { column += 1; if (column > LAST_COLUMN) { return null; } cellX += this.getColumnWidth(this.model.getSelectedSheet(), column); } } let cellY = headerRowHeight; let row = 0; if (y < headerRowHeight) { row = topLeftCell.row; while (cellY >= y) { row -= 1; if (row < 1) { row = 1; break; } cellY -= this.getRowHeight(this.model.getSelectedSheet(), row); } } else if (y < headerRowHeight + frozenRowsHeight) { while (cellY <= y) { row += 1; cellY += this.getRowHeight(this.model.getSelectedSheet(), row); // This cannot happen (would mean cellY > headerRowHeight + frozenRowsHeight) if (row > frozenRows) { /* istanbul ignore next */ return null; } } } else { cellY = headerRowHeight + frozenRowsHeight; row = topLeftCell.row - 1; while (cellY <= y) { row += 1; if (row > LAST_ROW) { row = LAST_ROW; break; } cellY += this.getRowHeight(this.model.getSelectedSheet(), row); } } if (row < 1) row = 1; if (column < 1) column = 1; return { row, column }; }
/** * (x, y) are the relative coordinates of a cell WRT the canvas * getCellByCoordinates(headerColumnWidth, headerRowHeight) will return the first visible cell. * Note: If there are frozen rows/columns for some particular coordinates (x, y) * there might be two cells. This method returns the visible one. */
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/IronCalc/src/components/WorksheetCanvas/worksheetCanvas.ts#L953-L1036
99125f1fea1c8c72c61f8cba94d847ed3471a4af
IronCalc
github_2023
ironcalc
typescript
getNewName
function getNewName(existingNames: string[]): string { const baseName = "Workbook"; let index = 1; while (index < MAX_WORKBOOKS) { const name = `${baseName}${index}`; index += 1; if (!existingNames.includes(name)) { return name; } } // FIXME: Too many workbooks? return "Workbook-Infinity"; }
// Pick a different name Workbook{N} where N = 1, 2, 3
https://github.com/ironcalc/IronCalc/blob/99125f1fea1c8c72c61f8cba94d847ed3471a4af/webapp/app.ironcalc.com/frontend/src/components/storage.ts#L35-L47
99125f1fea1c8c72c61f8cba94d847ed3471a4af
DeepBI
github_2023
DeepInsight-AI
typescript
SectionTitle
function SectionTitle({ className, children, ...props }: SectionTitleProps) { if (!children) { return null; } return ( <h4 className={cx("visualization-editor-section-title", className)} {...props}> {children} </h4> ); }
// @ts-expect-error ts-migrate(2700) FIXME: Rest types may only be created from object types.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/components/visualizations/editor/Section.tsx#L14-L24
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
ControlWrapper
function ControlWrapper({ className, id, layout, label, labelProps, disabled, ...props }: any) { const fallbackId = useMemo( () => `visualization-editor-control-${Math.random() .toString(36) .substr(2, 10)}`, [] ); labelProps = { ...labelProps, htmlFor: id || fallbackId, }; return ( <ControlLabel layout={layout} label={label} labelProps={labelProps} disabled={disabled}> {/* @ts-expect-error ts-migrate(2322) FIXME: Type 'Element' is not assignable to type 'null | u... Remove this comment to see the full error message */} <WrappedControl className={cx("visualization-editor-input", className)} id={labelProps.htmlFor} disabled={disabled} {...props} /> </ControlLabel> ); }
// eslint-disable-next-line react/prop-types
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/components/visualizations/editor/withControlLabel.tsx#L61-L85
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
box
function box() { let width = 1, height = 1, duration = 0, domain: any = null, value = Number, whiskers = boxWhiskers, quartiles = boxQuartiles, tickFormat: any = null; // For each small multiple… function box(g: any) { g.each(function(d: any, i: any) { d = d.map(value).sort(d3.ascending); // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message let g = d3.select(this), n = d.length, min = d[0], max = d[n - 1]; // Compute quartiles. Must return exactly 3 elements. const quartileData = (d.quartiles = quartiles(d)); // Compute whiskers. Must return exactly 2 elements, or null. // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message let whiskerIndices = whiskers && whiskers.call(this, d, i), whiskerData = whiskerIndices && whiskerIndices.map(i => d[i]); // Compute outliers. If no whiskers are specified, all data are "outliers". // We compute the outliers as indices, so that we can join across transitions! const outlierIndices = whiskerIndices ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) : d3.range(n); // Compute the new x-scale. // @ts-expect-error ts-migrate(2339) FIXME: Property 'scale' does not exist on type 'typeof im... Remove this comment to see the full error message const x1 = d3.scale .linear() // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message .domain((domain && domain.call(this, d, i)) || [min, max]) .range([height, 0]); // Retrieve the old x-scale, if this is an update. const x0 = // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message this.__chart__ || // @ts-expect-error ts-migrate(2339) FIXME: Property 'scale' does not exist on type 'typeof im... Remove this comment to see the full error message d3.scale .linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message this.__chart__ = x1; // Note: the box, median, and box tick elements are fixed in number, // so we only have to handle enter and update. In contrast, the outliers // and other elements are variable, so we need to exit them! Variable // elements also fade in and out. // Update center line: the vertical line spanning the whiskers. const center = g.selectAll("line.center").data(whiskerData ? [whiskerData] : []); center .enter() .insert("line", "rect") .attr("class", "center") .attr("x1", width / 2) .attr("y1", d => x0(d[0])) .attr("x2", width / 2) .attr("y2", d => x0(d[1])) .style("opacity", 1e-6) .transition() .duration(duration) .style("opacity", 1) .attr("y1", d => x1(d[0])) .attr("y2", d => x1(d[1])); center .transition() .duration(duration) .style("opacity", 1) .attr("y1", d => x1(d[0])) .attr("y2", d => x1(d[1])); center .exit() .transition() .duration(duration) .style("opacity", 1e-6) // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .attr("y1", d => x1(d[0])) // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .attr("y2", d => x1(d[1])) .remove(); // Update innerquartile box. const box = g.selectAll("rect.box").data([quartileData]); box .enter() .append("rect") .attr("class", "box") .attr("x", 0) .attr("y", d => x0(d[2])) .attr("width", width) .attr("height", d => x0(d[0]) - x0(d[2])) .transition() .duration(duration) .attr("y", d => x1(d[2])) .attr("height", d => x1(d[0]) - x1(d[2])); box .transition() .duration(duration) .attr("y", d => x1(d[2])) .attr("height", d => x1(d[0]) - x1(d[2])); box.exit().remove(); // Update median line. const medianLine = g.selectAll("line.median").data([quartileData[1]]); medianLine .enter() .append("line") .attr("class", "median") .attr("x1", 0) .attr("y1", x0) .attr("x2", width) .attr("y2", x0) .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1); medianLine .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1); medianLine.exit().remove(); // Update whiskers. const whisker = g.selectAll("line.whisker").data(whiskerData || []); whisker .enter() .insert("line", "circle, text") .attr("class", "whisker") .attr("x1", 0) .attr("y1", x0) .attr("x2", width) .attr("y2", x0) .style("opacity", 1e-6) .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1); whisker .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1); whisker .exit() .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1e-6) .remove(); // Update outliers. const outlier = g.selectAll("circle.outlier").data(outlierIndices, Number); outlier .enter() .insert("circle", "text") .attr("class", "outlier") .attr("r", 5) .attr("cx", width / 2) .attr("cy", i => x0(d[i])) .style("opacity", 1e-6) .transition() .duration(duration) .attr("cy", i => x1(d[i])) .style("opacity", 1); outlier .transition() .duration(duration) .attr("cy", i => x1(d[i])) .style("opacity", 1); outlier .exit() .transition() .duration(duration) // @ts-expect-error ts-migrate(2538) FIXME: Type 'unknown' cannot be used as an index type. .attr("cy", i => x1(d[i])) .style("opacity", 1e-6) .remove(); // Compute the tick format. const format = tickFormat || x1.tickFormat(8); // Update box ticks. const boxTick = g.selectAll("text.box").data(quartileData); boxTick .enter() .append("text") .attr("class", "box") .attr("dy", ".3em") .attr("dx", (d, i) => (i & 1 ? 6 : -6)) .attr("x", (d, i) => (i & 1 ? width : 0)) .attr("y", x0) .attr("text-anchor", (d, i) => (i & 1 ? "start" : "end")) .text(format) .transition() .duration(duration) .attr("y", x1); boxTick .transition() .duration(duration) .text(format) .attr("y", x1); boxTick.exit().remove(); // Update whisker ticks. These are handled separately from the box // ticks because they may or may not exist, and we want don't want // to join box ticks pre-transition with whisker ticks post-. const whiskerTick = g.selectAll("text.whisker").data(whiskerData || []); whiskerTick .enter() .append("text") .attr("class", "whisker") .attr("dy", ".3em") .attr("dx", 6) .attr("x", width) .attr("y", x0) .text(format) .style("opacity", 1e-6) .transition() .duration(duration) .attr("y", x1) .style("opacity", 1); whiskerTick .transition() .duration(duration) .text(format) .attr("y", x1) .style("opacity", 1); whiskerTick .exit() .transition() .duration(duration) .attr("y", x1) .style("opacity", 1e-6) .remove(); }); // @ts-expect-error ts-migrate(2339) FIXME: Property 'flush' does not exist on type '(callback... Remove this comment to see the full error message d3.timer.flush(); } box.width = function(x: any) { if (!arguments.length) return width; width = x; return box; }; box.height = function(x: any) { if (!arguments.length) return height; height = x; return box; }; box.tickFormat = function(x: any) { if (!arguments.length) return tickFormat; tickFormat = x; return box; }; box.duration = function(x: any) { if (!arguments.length) return duration; duration = x; return box; }; box.domain = function(x: any) { if (!arguments.length) return domain; // @ts-expect-error ts-migrate(2339) FIXME: Property 'functor' does not exist on type 'typeof ... Remove this comment to see the full error message domain = x == null ? x : d3.functor(x); return box; }; box.value = function(x: any) { if (!arguments.length) return value; value = x; return box; }; box.whiskers = function(x: any) { if (!arguments.length) return whiskers; whiskers = x; return box; }; box.quartiles = function(x: any) { if (!arguments.length) return quartiles; quartiles = x; return box; }; return box; }
/* eslint-disable */
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/box-plot/d3box.ts#L3-L330
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
box
function box(g: any) { g.each(function(d: any, i: any) { d = d.map(value).sort(d3.ascending); // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message let g = d3.select(this), n = d.length, min = d[0], max = d[n - 1]; // Compute quartiles. Must return exactly 3 elements. const quartileData = (d.quartiles = quartiles(d)); // Compute whiskers. Must return exactly 2 elements, or null. // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message let whiskerIndices = whiskers && whiskers.call(this, d, i), whiskerData = whiskerIndices && whiskerIndices.map(i => d[i]); // Compute outliers. If no whiskers are specified, all data are "outliers". // We compute the outliers as indices, so that we can join across transitions! const outlierIndices = whiskerIndices ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) : d3.range(n); // Compute the new x-scale. // @ts-expect-error ts-migrate(2339) FIXME: Property 'scale' does not exist on type 'typeof im... Remove this comment to see the full error message const x1 = d3.scale .linear() // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message .domain((domain && domain.call(this, d, i)) || [min, max]) .range([height, 0]); // Retrieve the old x-scale, if this is an update. const x0 = // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message this.__chart__ || // @ts-expect-error ts-migrate(2339) FIXME: Property 'scale' does not exist on type 'typeof im... Remove this comment to see the full error message d3.scale .linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message this.__chart__ = x1; // Note: the box, median, and box tick elements are fixed in number, // so we only have to handle enter and update. In contrast, the outliers // and other elements are variable, so we need to exit them! Variable // elements also fade in and out. // Update center line: the vertical line spanning the whiskers. const center = g.selectAll("line.center").data(whiskerData ? [whiskerData] : []); center .enter() .insert("line", "rect") .attr("class", "center") .attr("x1", width / 2) .attr("y1", d => x0(d[0])) .attr("x2", width / 2) .attr("y2", d => x0(d[1])) .style("opacity", 1e-6) .transition() .duration(duration) .style("opacity", 1) .attr("y1", d => x1(d[0])) .attr("y2", d => x1(d[1])); center .transition() .duration(duration) .style("opacity", 1) .attr("y1", d => x1(d[0])) .attr("y2", d => x1(d[1])); center .exit() .transition() .duration(duration) .style("opacity", 1e-6) // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .attr("y1", d => x1(d[0])) // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .attr("y2", d => x1(d[1])) .remove(); // Update innerquartile box. const box = g.selectAll("rect.box").data([quartileData]); box .enter() .append("rect") .attr("class", "box") .attr("x", 0) .attr("y", d => x0(d[2])) .attr("width", width) .attr("height", d => x0(d[0]) - x0(d[2])) .transition() .duration(duration) .attr("y", d => x1(d[2])) .attr("height", d => x1(d[0]) - x1(d[2])); box .transition() .duration(duration) .attr("y", d => x1(d[2])) .attr("height", d => x1(d[0]) - x1(d[2])); box.exit().remove(); // Update median line. const medianLine = g.selectAll("line.median").data([quartileData[1]]); medianLine .enter() .append("line") .attr("class", "median") .attr("x1", 0) .attr("y1", x0) .attr("x2", width) .attr("y2", x0) .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1); medianLine .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1); medianLine.exit().remove(); // Update whiskers. const whisker = g.selectAll("line.whisker").data(whiskerData || []); whisker .enter() .insert("line", "circle, text") .attr("class", "whisker") .attr("x1", 0) .attr("y1", x0) .attr("x2", width) .attr("y2", x0) .style("opacity", 1e-6) .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1); whisker .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1); whisker .exit() .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1e-6) .remove(); // Update outliers. const outlier = g.selectAll("circle.outlier").data(outlierIndices, Number); outlier .enter() .insert("circle", "text") .attr("class", "outlier") .attr("r", 5) .attr("cx", width / 2) .attr("cy", i => x0(d[i])) .style("opacity", 1e-6) .transition() .duration(duration) .attr("cy", i => x1(d[i])) .style("opacity", 1); outlier .transition() .duration(duration) .attr("cy", i => x1(d[i])) .style("opacity", 1); outlier .exit() .transition() .duration(duration) // @ts-expect-error ts-migrate(2538) FIXME: Type 'unknown' cannot be used as an index type. .attr("cy", i => x1(d[i])) .style("opacity", 1e-6) .remove(); // Compute the tick format. const format = tickFormat || x1.tickFormat(8); // Update box ticks. const boxTick = g.selectAll("text.box").data(quartileData); boxTick .enter() .append("text") .attr("class", "box") .attr("dy", ".3em") .attr("dx", (d, i) => (i & 1 ? 6 : -6)) .attr("x", (d, i) => (i & 1 ? width : 0)) .attr("y", x0) .attr("text-anchor", (d, i) => (i & 1 ? "start" : "end")) .text(format) .transition() .duration(duration) .attr("y", x1); boxTick .transition() .duration(duration) .text(format) .attr("y", x1); boxTick.exit().remove(); // Update whisker ticks. These are handled separately from the box // ticks because they may or may not exist, and we want don't want // to join box ticks pre-transition with whisker ticks post-. const whiskerTick = g.selectAll("text.whisker").data(whiskerData || []); whiskerTick .enter() .append("text") .attr("class", "whisker") .attr("dy", ".3em") .attr("dx", 6) .attr("x", width) .attr("y", x0) .text(format) .style("opacity", 1e-6) .transition() .duration(duration) .attr("y", x1) .style("opacity", 1); whiskerTick .transition() .duration(duration) .text(format) .attr("y", x1) .style("opacity", 1); whiskerTick .exit() .transition() .duration(duration) .attr("y", x1) .style("opacity", 1e-6) .remove(); }); // @ts-expect-error ts-migrate(2339) FIXME: Property 'flush' does not exist on type '(callback... Remove this comment to see the full error message d3.timer.flush(); }
// For each small multiple…
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/box-plot/d3box.ts#L14-L278
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
initPlotUpdater
function initPlotUpdater() { let actions: any = []; const updater = { append(action: any) { if (isArray(action) && isObject(action[0])) { actions.push(action); } return updater; }, // @ts-expect-error ts-migrate(7023) FIXME: 'process' implicitly has return type 'any' because... Remove this comment to see the full error message process(plotlyElement: any) { if (actions.length > 0) { const updates = reduce(actions, (updates, action) => merge(updates, action[0]), {}); const handlers = map(actions, action => (isFunction(action[1]) ? action[1] : () => null)); actions = []; return Plotly.relayout(plotlyElement, updates).then(() => { each(handlers, handler => updater.append(handler())); return updater.process(plotlyElement); }); } else { return Promise.resolve(); } }, }; return updater; }
// This utility is intended to reduce amount of plot updates when multiple Plotly.relayout
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/chart/Renderer/initChart.ts#L23-L50
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
render
let render = () => {};
// Create a function from custom code; catch syntax errors
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/chart/plotly/customChartUtils.ts#L24-L24
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
numberFormat
function numberFormat(value: any, decimalPoints: any, decimalDelimiter: any, thousandsDelimiter: any) { // Temporarily update locale data (restore defaults after formatting) const locale = numeral.localeData(); const savedDelimiters = locale.delimiters; // Mimic old behavior - AngularJS `number` filter defaults: // - `,` as thousands delimiter // - `.` as decimal delimiter // - three decimal points locale.delimiters = { thousands: ",", decimal: ".", }; let formatString = "0,0.000"; if ((Number.isFinite(decimalPoints) && decimalPoints >= 0) || decimalDelimiter || thousandsDelimiter) { locale.delimiters = { thousands: thousandsDelimiter, decimal: decimalDelimiter || ".", }; formatString = "0,0"; if (decimalPoints > 0) { formatString += "."; while (decimalPoints > 0) { formatString += "0"; decimalPoints -= 1; } } } const result = numeral(value).format(formatString); locale.delimiters = savedDelimiters; return result; }
// TODO: allow user to specify number format string instead of delimiters only
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/counter/utils.ts#L7-L40
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
getRowNumber
function getRowNumber(index: any, rowsCount: any) { index = parseInt(index, 10) || 0; if (index === 0) { return index; } const wrappedIndex = (Math.abs(index) - 1) % rowsCount; return index > 0 ? wrappedIndex : rowsCount - wrappedIndex - 1; }
// 0 - special case, use first record
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/counter/utils.ts#L45-L52
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
computeNodeLinks
function computeNodeLinks() { nodes.forEach(node => { node.sourceLinks = []; node.targetLinks = []; }); links.forEach(link => { let source = link.source; let target = link.target; if (typeof source === "number") source = link.source = nodes[link.source]; if (typeof target === "number") target = link.target = nodes[link.target]; source.sourceLinks.push(link); target.targetLinks.push(link); }); }
// Populate the sourceLinks and targetLinks for each node.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sankey/d3sankey.ts#L55-L68
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
computeNodeValues
function computeNodeValues() { nodes.forEach(node => { node.value = Math.max(d3.sum(node.sourceLinks, value), d3.sum(node.targetLinks, value)); }); }
// Compute the value (size) of each node by summing the associated links.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sankey/d3sankey.ts#L71-L75
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
computeNodeBreadths
function computeNodeBreadths() { let remainingNodes = nodes; let nextNodes: any; let x = 0; function assignBreadth(node: any) { node.x = x; node.dx = nodeWidth; node.sourceLinks.forEach((link: any) => { if (nextNodes.indexOf(link.target) < 0) { nextNodes.push(link.target); } }); } while (remainingNodes.length) { nextNodes = []; remainingNodes.forEach(assignBreadth); remainingNodes = nextNodes; x += 1; } moveSinksRight(x); x = Math.max( d3.max(nodes, n => n.x), 2 ); // get new maximum x value (min 2) scaleNodeBreadths((size[0] - nodeWidth) / (x - 1)); }
// Iteratively assign the breadth (x-position) for each node.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sankey/d3sankey.ts#L95-L123
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
prepareDataRows
function prepareDataRows(rows: ExtendedSankeyDataType["rows"]) { return map(rows, row => mapValues(row, v => { if (!v || isNumber(v)) { return v; } return isNaN(parseFloat(v)) ? v : parseFloat(v); }) ); }
// will coerce number strings into valid numbers
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sankey/initSankey.ts#L158-L167
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
format
const format = (d: DType) => d3.format(",.0f")(d);
// @ts-expect-error
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sankey/initSankey.ts
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
colorMap
function colorMap(d: any) { return colors(d.name); }
// helper function colorMap - color gray if "end" is detected
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sunburst/initSunburst.ts#L13-L15
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
getAncestors
function getAncestors(node: any) { const path = []; let current = node; while (current.parent) { path.unshift(current); current = current.parent; } return path; }
// Return array of ancestors of nodes, highest first, but excluding the root.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sunburst/initSunburst.ts#L18-L27
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
breadcrumbPoints
function breadcrumbPoints(d: any, i: any) { const points = []; points.push("0,0"); points.push(`${b.w},0`); points.push(`${b.w + b.t},${b.h / 2}`); points.push(`${b.w},${b.h}`); points.push(`0,${b.h}`); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. points.push(`${b.t},${b.h / 2}`); } return points.join(" "); }
// Generate a string representation for drawing a breadcrumb polygon.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sunburst/initSunburst.ts#L228-L241
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
updateBreadcrumbs
function updateBreadcrumbs(ancestors: any, percentageString: any) { // Data join, where primary key = name + depth. // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. const g = breadcrumbs.selectAll("g").data(ancestors, d => d.name + d.depth); // Add breadcrumb and label for entering nodes. const breadcrumb = g.enter().append("g"); breadcrumb .append("polygon") .classed("breadcrumbs-shape", true) .attr("points", breadcrumbPoints) .attr("fill", colorMap); breadcrumb .append("text") .classed("breadcrumbs-text", true) .attr("x", (b.w + b.t) / 2) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("font-size", "10px") .attr("text-anchor", "middle") // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .text(d => d.name); // Set position for entering and updating nodes. g.attr("transform", (d, i) => `translate(${i * (b.w + b.s)}, 0)`); // Remove exiting nodes. g.exit().remove(); // Update percentage at the lastCrumb. lastCrumb .attr("x", (ancestors.length + 0.5) * (b.w + b.s)) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .attr("fill", "black") .attr("font-weight", 600) .text(percentageString); }
// Update the breadcrumb breadcrumbs to show the current sequence and percentage.
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sunburst/initSunburst.ts#L244-L284
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
mouseover
function mouseover(d: any) { // build percentage string const percentage = ((100 * d.value) / totalSize).toPrecision(3); let percentageString = `${percentage}%`; // @ts-expect-error ts-migrate(2365) FIXME: Operator '<' cannot be applied to types 'string' a... Remove this comment to see the full error message if (percentage < 1) { percentageString = "< 1.0%"; } // update breadcrumbs (get all ancestors) const ancestors = getAncestors(d); updateBreadcrumbs(ancestors, percentageString); // update sunburst (Fade all the segments and highlight only ancestors of current segment) sunburst.selectAll("path").attr("opacity", 0.3); sunburst .selectAll("path") .filter(node => ancestors.indexOf(node) >= 0) .attr("opacity", 1); // update summary summary.html(` <span>层级:${d.depth}</span> <span class='percentage' style='font-size: 2em;'>${percentageString}</span> <span>${d.value} / ${totalSize}</span> `); // display summary and breadcrumbs if hidden summary.style("visibility", ""); breadcrumbs.style("visibility", ""); }
// helper function mouseover to handle mouseover events/animations and calculation
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sunburst/initSunburst.ts#L288-L318
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
click
function click() { // Deactivate all segments then retransition each segment to full opacity. sunburst.selectAll("path").on("mouseover", null); sunburst .selectAll("path") .transition() .duration(1000) .attr("opacity", 1) // @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 2. .each("end", function endClick() { // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message d3.select(this).on("mouseover", mouseover); }); // hide summary and breadcrumbs if visible breadcrumbs.style("visibility", "hidden"); summary.style("visibility", "hidden"); }
// helper function click to handle mouseleave events/animations
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/chart/visualizations/sunburst/initSunburst.ts#L321-L338
4e460d7d124917653cbae87e5545e78231a31600
DeepBI
github_2023
DeepInsight-AI
typescript
ItemsListWrapper.getState
getState({ isLoaded, totalCount, pageItems, params, ...rest }: ItemsListWrapperState<I, P>): ItemsListWrapperState<I, P> { return { ...rest, params: { ...params, // custom params from items source ...omit(this.props, ["onError", "children"]), // add all props except of own ones }, isLoaded, isEmpty: !isLoaded || totalCount === 0, totalItemsCount: totalCount || 0, pageSizeOptions: (clientConfig as any).pageSizeOptions, // TODO: Type auth.js pageItems: pageItems || [], }; }
// eslint-disable-next-line class-methods-use-this
https://github.com/DeepInsight-AI/DeepBI/blob/4e460d7d124917653cbae87e5545e78231a31600/client/app/components/items-list/ItemsList.tsx#L168-L189
4e460d7d124917653cbae87e5545e78231a31600
llama-coder
github_2023
ex3ndr
typescript
Config.inference
get inference() { let config = this.#config; // Load endpoint let endpoint = (config.get('endpoint') as string).trim(); if (endpoint.endsWith('/')) { endpoint = endpoint.slice(0, endpoint.length - 1).trim(); } if (endpoint === '') { endpoint = 'http://127.0.0.1:11434'; } let bearerToken = config.get('bearerToken') as string; // Load general paremeters let maxLines = config.get('maxLines') as number; let maxTokens = config.get('maxTokens') as number; let temperature = config.get('temperature') as number; // Load model let modelName = config.get('model') as string; let modelFormat: ModelFormat = 'codellama'; if (modelName === 'custom') { modelName = config.get('custom.model') as string; modelFormat = config.get('cutom.format') as ModelFormat; } else { if (modelName.startsWith('deepseek-coder')) { modelFormat = 'deepseek'; } else if (modelName.startsWith('stable-code')) { modelFormat = 'stable-code'; } } let delay = config.get('delay') as number; return { endpoint, bearerToken, maxLines, maxTokens, temperature, modelName, modelFormat, delay }; }
// Inference
https://github.com/ex3ndr/llama-coder/blob/d4b65d6737e2c5d4b5797fd77e18e740dd9355df/src/config.ts#L7-L51
d4b65d6737e2c5d4b5797fd77e18e740dd9355df
llama-coder
github_2023
ex3ndr
typescript
Config.notebook
get notebook() { let config = vscode.workspace.getConfiguration('notebook'); let includeMarkup = config.get('includeMarkup') as boolean; let includeCellOutputs = config.get('includeCellOutputs') as boolean; let cellOutputLimit = config.get('cellOutputLimit') as number; return { includeMarkup, includeCellOutputs, cellOutputLimit, }; }
// Notebook
https://github.com/ex3ndr/llama-coder/blob/d4b65d6737e2c5d4b5797fd77e18e740dd9355df/src/config.ts#L54-L65
d4b65d6737e2c5d4b5797fd77e18e740dd9355df