repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
pigment-css
github_2023
mui
typescript
StyledProcessor.processStyle
processStyle( values: ValueCache, styleArg: ExpressionValue, variantsAccumulator?: VariantData[], themeImportIdentifier?: string, ) { if (styleArg.kind === ValueType.CONST) { if (typeof styleArg.value === 'string') { this.collectedStyles.push([this.getClassName(), styleArg.value, styleArg]); } } else { const styleObjOrFn = values.get(styleArg.ex.name); const finalStyle = this.processCss( styleObjOrFn as object | (() => void), styleArg, variantsAccumulator, themeImportIdentifier, ); const className = this.getClassName(); this.baseClasses.push(className); this.collectedStyles.push([className, finalStyle, styleArg]); } }
/** * Generates css for object directly provided as arguments in the styled call. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L516-L538
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.processOverrides
processOverrides(values: ValueCache, variantsAccumulator?: VariantData[]) { if (!this.componentMetaArg) { return; } const value = values.get(this.componentMetaArg.ex.name) as ComponentMeta; const { themeArgs: { theme } = {} } = this.options as IOptions; if (!value.name || !value.slot || !theme) { return; } const componentData = theme.components?.[value.name]; if (!componentData) { return; } if ('styleOverrides' in componentData) { const overrides = componentData.styleOverrides as Record<string, CSSObject>; if (!overrides) { return; } const overrideStyle = (overrides[lowercaseFirstLetter(value.slot)] || overrides[value.slot]) as string | CSSObject; const className = this.getClassName(); if (typeof overrideStyle === 'string') { this.collectedStyles.push([className, overrideStyle, null]); return; } const finalStyle = this.processCss(overrideStyle, null, variantsAccumulator); this.baseClasses.push(className); this.collectedStyles.push([className, finalStyle, null]); } if (!variantsAccumulator) { return; } if ( 'variants' in componentData && componentData.variants && lowercaseFirstLetter(value.slot) === 'root' ) { variantsAccumulator.push(...(componentData.variants as unknown as VariantData[])); } }
/** * Generates css for styleOverride objects in the theme object. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L543-L585
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
StyledProcessor.processVariant
processVariant(variant: VariantData) { const { displayName } = this.options; const className = this.getClassName(displayName ? 'variant' : undefined); const styleObjOrFn = variant.style; const originalExpression = variant.originalExpression; const finalStyle = this.processCss(styleObjOrFn, originalExpression ?? null); this.collectedStyles.push([className, finalStyle, null]); this.collectedVariants.push({ props: variant.props, className, }); }
/** * Generates css for all the variants collected after processing direct css and styleOverride css. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/processors/styled.ts#L590-L601
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
parseAndWrapExpression
function parseAndWrapExpression( functionString: string, expressionValue?: FunctionValue, themeImportIdentifier?: string, ) { if (!expressionValue) { return parseExpression(functionString); } const expression = parseExpression(functionString); if (expression.type === 'FunctionExpression' || expression.type === 'ArrowFunctionExpression') { // let parsedParentExpression = expressionCache.get(expressionValue); // if (!parsedParentExpression) { // parsedParentExpression = parseExpression(expressionValue.source); // if (!parsedParentExpression) { // throw new Error("MUI: Could not parse styled function's source."); // } // } expression.params.push( t.assignmentPattern(t.identifier('theme'), t.identifier(themeImportIdentifier ?? 'theme')), ); } return expression; }
// @TODO - Implement default theme argument for non-theme config as well.
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-react/src/utils/cssFnValueToVariable.ts#L78-L100
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
getCss
function getCss( style: string | BaseStyleObject, { getClassName, getVariableName }: ProcessStyleObjectsOptions, ): ProcessStyleObjectsReturn { const result: ProcessStyleObjectsReturn = { base: [], variants: [], compoundVariants: [], }; if (typeof style === 'string') { result.base.push({ cssText: serializeStyles([style]).styles, className: cssesc(getClassName()), variables: {}, serializables: {}, }); return result; } const { variants, compoundVariants } = style; delete style.variants; delete style.compoundVariants; delete style.defaultVariants; const { result: baseObj, variables } = processStyle(style, { getVariableName }); const cssText = serializeStyles([baseObj as any]).styles; result.base.push({ className: getClassName(), cssText, variables, serializables: {}, }); if (variants) { Object.keys(variants).forEach((variantName) => { const variantData = variants[variantName]; Object.keys(variantData).forEach((variantValue) => { const cssObjOrStr = variantData[variantValue]; const className = getClassName({ variantName, variantValue, }); const serializables = { [variantName]: variantValue, }; if (typeof cssObjOrStr === 'string') { result.variants.push({ className, cssText: serializeStyles([cssObjOrStr]).styles, variables: {}, serializables, }); } else { const { result: cssObj, variables: variantVariables } = processStyle(cssObjOrStr, { getVariableName, }); result.variants.push({ className, serializables, variables: variantVariables, cssText: serializeStyles([cssObj as any]).styles, }); } }); }); } if (compoundVariants && compoundVariants.length > 0) { compoundVariants.forEach(({ css, ...rest }, cvIndex) => { const className = `${getClassName({ isCv: true })}${cvIndex ? `-${cvIndex}` : ''}`; const serializables = rest; if (typeof css === 'string') { result.compoundVariants.push({ className, cssText: serializeStyles([css]).styles, variables: {}, serializables, }); } else { const { result: cssObj, variables: variantVariables } = processStyle(css, { getVariableName, }); result.compoundVariants.push({ className, serializables, variables: variantVariables, cssText: serializeStyles([cssObj as any]).styles, }); } }); } return result; }
/** * Actual transformation call to be done by either `css()` or `styled()` APIs to convert the passed * style object to css string. It handles all the variant transformations as well. */
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/packages/pigment-css-utils/src/utils/processStyle.ts#L134-L224
65364cab373927119abcbebad2edee6e59a8ee12
pigment-css
github_2023
mui
typescript
getSortLiteralUnions
const getSortLiteralUnions: InjectPropTypesInFileOptions['getSortLiteralUnions'] = ( component, propType, ) => { if (propType.name === 'size') { return sortSizeByScaleAscending; } return undefined; };
// Custom order of literal unions by component
https://github.com/mui/pigment-css/blob/65364cab373927119abcbebad2edee6e59a8ee12/scripts/generateProptypes.ts#L47-L56
65364cab373927119abcbebad2edee6e59a8ee12
slink
github_2023
andrii-kryvoviaz
typescript
injectAlphaPlaceholder
function injectAlphaPlaceholder(object: any): any { return Object.keys(object).reduce( (newObj: any, key: string) => { const value = object[key]; if (typeof value === 'string') { newObj[key] = value.replace( /^var\(--(.+?)\)$/, 'rgb(var(--$1) / <alpha-value>)', ); } else if (typeof value === 'object' && value !== null) { newObj[key] = injectAlphaPlaceholder(value); // Recurse for nested objects } else { newObj[key] = value; } return newObj; }, Array.isArray(object) ? [] : {}, ); }
// go recursively through the object and replace the values
https://github.com/andrii-kryvoviaz/slink/blob/f6fce183428e1fc617a4dca4c263b092fbb29eb2/client/src/theme.default.ts#L222-L240
f6fce183428e1fc617a4dca4c263b092fbb29eb2
translation-starter
github_2023
synchronicity-labs
typescript
handleBeforeUnload
const handleBeforeUnload = (event: BeforeUnloadEvent): string | void => { const message: string = 'Are you sure you want to leave this page? Any jobs that are uploading will not be saved.'; event.returnValue = message; return message; };
// This function will be called when the component is mounted
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/components/feature-playground/ui/MediaInput/MediaInput.tsx#L85-L90
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
SynchronicityLogger.log
log(message: any, ...meta: any[]) { if (!this.shouldLog(this.level, LogLevel.Info)) { return; } this.logger.info(message, ...meta); }
/** * Logs general information. * This method is typically used for informative messages that denote routine operations. * @param message - The main content of the log. * @param meta - Additional metadata for the log. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/lib/SynchronicityLogger.ts#L106-L111
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
SynchronicityLogger.error
error(message: any, ...meta: any[]) { if (!this.shouldLog(this.level, LogLevel.Error)) { return; } this.logger.info(message, ...meta); }
/** * Logs error messages. * This method is used to log error messages that occur during the application's execution. * @param message - Description of the error. * @param trace - Stack trace or error trace information. * @param meta - Additional metadata about the error. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/lib/SynchronicityLogger.ts#L120-L125
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
SynchronicityLogger.warn
warn(message: any, ...meta: any[]) { if (!this.shouldLog(this.level, LogLevel.Warn)) { return; } this.logger.info(message, ...meta); }
/** * Logs warning messages. * Warning messages are typically used to log issues that aren’t critical but deserve attention. * @param message - Description of the warning. * @param meta - Additional metadata about the warning. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/lib/SynchronicityLogger.ts#L133-L138
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
SynchronicityLogger.debug
debug(message: any, ...meta: any[]) { if (!this.shouldLog(this.level, LogLevel.Debug)) { return; } this.logger.info(message, ...meta); }
/** * Logs debug messages. * Debug messages provide detailed information during the development phase for debugging purposes. * @param message - Description of the debug information. * @param meta - Additional debug data. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/lib/SynchronicityLogger.ts#L146-L151
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
SynchronicityLogger.verbose
verbose(message: any, ...meta: any[]) { if (!this.shouldLog(this.level, LogLevel.Debug)) { return; } this.logger.info(message, ...meta); }
/** * Logs verbose messages. * Verbose messages contain additional contextual information for understanding the flow through the system. * @param message - Description of the verbose information. * @param meta - Additional contextual data. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/lib/SynchronicityLogger.ts#L159-L164
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
SynchronicityLogger.profile
profile(message: string) { if (!this.shouldLog(this.level, LogLevel.Debug)) { return; } const currentTimestamp = Date.now(); if (this.lastTimestamp !== null) { const timeSinceLastCall = currentTimestamp - this.lastTimestamp; this.debug( `${message} - Time since last profile call: ${timeSinceLastCall} ms` ); } else { this.debug(`${message} - Profile started`); } this.lastTimestamp = currentTimestamp; }
/** * Logs the time elapsed since the last call to this method. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/lib/SynchronicityLogger.ts#L173-L188
6920395d3643edcdfa51e4545a7bbcf920bfe910
translation-starter
github_2023
synchronicity-labs
typescript
copyBillingDetailsToCustomer
const copyBillingDetailsToCustomer = async ( uuid: string, payment_method: Stripe.PaymentMethod ) => { //Todo: check this assertion const customer = payment_method.customer as string; const { name, phone, address } = payment_method.billing_details; if (!name || !phone || !address) return; //@ts-ignore await stripe.customers.update(customer, { name, phone, address }); const { error } = await supabaseAdmin .from('users') .update({ billing_address: { ...address }, payment_method: { ...payment_method[payment_method.type] } }) .eq('id', uuid); if (error) throw error; };
/** * Copies the billing details from the payment method to the customer object. */
https://github.com/synchronicity-labs/translation-starter/blob/6920395d3643edcdfa51e4545a7bbcf920bfe910/utils/supabase-admin.ts#L86-L104
6920395d3643edcdfa51e4545a7bbcf920bfe910
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/ai-hero/src/app/api/trpc/[trpc]/route.ts#L11-L15
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
addDiscordRole
async function addDiscordRole(accessToken: string, roleId: string) { await fetch( `https://discord.com/api/guilds/${env.DISCORD_GUILD_ID}/members/@me/roles/${roleId}`, { method: 'PUT', headers: { Authorization: `Bot ${env.DISCORD_BOT_TOKEN}`, 'Content-Type': 'application/json', }, }, ) }
/** * Add a Discord role to a user * @param accessToken - The access token for the user * @param roleId - The ID of the role to add */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/ai-hero/src/lib/cohorts-query.ts#L176-L187
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
getNewState
const getNewState = ( action: PostAction, ): 'draft' | 'published' | 'archived' | 'deleted' => { switch (action) { case 'publish': return 'published' case 'unpublish': return 'draft' case 'archive': return 'archived' default: return originalPost.fields.state } }
// Handle state transitions for all actions
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/ai-hero/src/lib/posts/posts.service.ts#L232-L245
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
defaultText
async function defaultText( { url, host, email }: HTMLEmailParams, theme?: Theme, ) { return await render( PurchaseTransferEmail( { url, host, email, siteName: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || '', previewText: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || 'login link', }, theme, ), { plainText: true, }, ) }
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/ai-hero/src/purchase-transfer/purchase-transfer-actions.tsx#L351-L376
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/astro-party/src/app/api/trpc/[trpc]/route.ts#L11-L15
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
defaultText
async function defaultText( { url, host, email }: HTMLEmailParams, theme?: Theme, ) { return await render( PurchaseTransferEmail( { url, host, email, siteName: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || '', previewText: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || 'login link', }, theme, ), { plainText: true, }, ) }
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/astro-party/src/purchase-transfer/purchase-transfer-actions.tsx#L368-L393
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/course-builder-web/src/app/api/trpc/[trpc]/route.ts#L11-L15
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
defaultText
async function defaultText( { url, host, email }: HTMLEmailParams, theme?: Theme, ) { return await render( PurchaseTransferEmail( { url, host, email, siteName: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || '', previewText: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || 'login link', }, theme, ), { plainText: true, }, ) }
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/course-builder-web/src/purchase-transfer/purchase-transfer-actions.tsx#L368-L393
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
handleRefinementListChange
function handleRefinementListChange( attribute: string, setState: (value: any) => void, ) { const refinementList = uiState[TYPESENSE_COLLECTION_NAME]?.refinementList?.[attribute] if (refinementList && refinementList.length > 0) { setState(refinementList) } else { setState(null) } }
// TODO: implement url params per https://github.com/skillrecordings/egghead-next/blob/main/src/pages/q/%5B%5B...all%5D%5D.tsx#L96
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/egghead/src/app/(search)/q/_components/search.tsx#L41-L52
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/egghead/src/app/api/trpc/[trpc]/route.ts#L11-L15
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/epic-react/src/app/api/trpc/[trpc]/route.ts#L11-L15
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/go-local-first/src/app/api/trpc/[trpc]/route.ts#L11-L15
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
MDX
const MDX = ({ contents, components, }: { contents: MDXRemoteSerializeResult components?: MDXRemoteProps['components'] }) => { return ( <MDXRemote components={{ ...defaultComponents, ...components }} {...contents} /> ) }
/** * Renders compiled source from @skillrecordings/skill-lesson/markdown/serialize-mdx * with syntax highlighting and code-hike components. * @param {MDXRemoteSerializeResult} contents * @returns <MDXRemote components={components} {...contents} /> */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/go-local-first/src/markdown/mdx.tsx#L24-L37
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
defaultText
async function defaultText( { url, host, email }: HTMLEmailParams, theme?: Theme, ) { return await render( PurchaseTransferEmail( { url, host, email, siteName: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || '', previewText: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || 'login link', }, theme, ), { plainText: true, }, ) }
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/apps/go-local-first/src/purchase-transfer/purchase-transfer-actions.tsx#L351-L376
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
getDefaultBranch
const getDefaultBranch = () => { const stdout = execSync('git config --global init.defaultBranch || echo main') .toString() .trim() return stdout }
/** @returns The git config value of "init.defaultBranch". If it is not set, returns "main". */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/cli/src/helpers/git.ts#L49-L55
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createContext
const createContext = async (req: NextRequest) => { return createTRPCContext({ headers: req.headers, }) }
/** * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when * handling a HTTP request (e.g. when you make requests from Client Components). */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/cli/template/extras/src/app/api/trpc/[trpc]/route.ts#L12-L16
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createInnerTRPCContext
const createInnerTRPCContext = (_opts: CreateContextOptions) => { return {} }
/** * This helper generates the "internals" for a tRPC context. If you need to use it, you can export * it from here. * * Examples of things you may need it for: * - testing, so we don't have to mock Next.js' req/res * - tRPC's `createSSGHelpers`, where we don't have req/res * * @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/cli/template/extras/src/server/api/trpc-pages/base.ts#L35-L37
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createInnerTRPCContext
const createInnerTRPCContext = (opts: CreateContextOptions) => { return { session: opts.session, db, } }
/** * This helper generates the "internals" for a tRPC context. If you need to use it, you can export * it from here. * * Examples of things you may need it for: * - testing, so we don't have to mock Next.js' req/res * - tRPC's `createSSGHelpers`, where we don't have req/res * * @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/cli/template/extras/src/server/api/trpc-pages/with-auth-db.ts#L41-L46
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createInnerTRPCContext
const createInnerTRPCContext = ({ session }: CreateContextOptions) => { return { session, } }
/** * This helper generates the "internals" for a tRPC context. If you need to use it, you can export * it from here. * * Examples of things you may need it for: * - testing, so we don't have to mock Next.js' req/res * - tRPC's `createSSGHelpers`, where we don't have req/res * * @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/cli/template/extras/src/server/api/trpc-pages/with-auth.ts#L39-L43
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
createInnerTRPCContext
const createInnerTRPCContext = (_opts: CreateContextOptions) => { return { db, } }
/** * This helper generates the "internals" for a tRPC context. If you need to use it, you can export * it from here. * * Examples of things you may need it for: * - testing, so we don't have to mock Next.js' req/res * - tRPC's `createSSGHelpers`, where we don't have req/res * * @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/cli/template/extras/src/server/api/trpc-pages/with-db.ts#L36-L40
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
mysqlDatetimeUtcToDate
function mysqlDatetimeUtcToDate(mysqlDatetimeUtc: string) { return new Date(mysqlDatetimeUtc.replace(' ', 'T') + 'Z') }
// Use this function instead of new Date() when converting a MySQL datetime to a
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/adapter-drizzle/src/lib/mysql/utils.ts#L21-L23
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
defaultText
async function defaultText( { url, host, email, merchantChargeId }: HTMLEmailParams, theme?: Theme, ) { return await render( PostPurchaseLoginEmail( { url, host, email, siteName: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || '', ...(merchantChargeId && { invoiceUrl: `${process.env.COURSEBUILDER_URL}/invoices/${merchantChargeId}`, }), previewText: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || 'login link', }, theme, ), { plainText: true, }, ) }
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/src/lib/send-verification-request.ts#L181-L209
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
signUpText
async function signUpText( { url, host, email }: HTMLEmailParams, theme?: Theme, ) { return await render( NewMemberEmail({ url, host, email, siteName: process.env.NEXT_PUBLIC_PRODUCT_NAME || process.env.NEXT_PUBLIC_SITE_TITLE || '', }), { plainText: true, }, ) }
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/src/lib/send-verification-request.ts#L229-L247
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
lookupApplicablePPPMerchantCoupon
const lookupApplicablePPPMerchantCoupon = async ( params: LookupApplicablePPPMerchantCouponParams, ) => { const { prismaCtx, pppDiscountPercent } = LookupApplicablePPPMerchantCouponParamsSchema.parse(params) const { getMerchantCouponForTypeAndPercent } = prismaCtx const pppMerchantCoupon = await getMerchantCouponForTypeAndPercent({ type: PPP_TYPE, percentageDiscount: pppDiscountPercent, }) // early return if there is no PPP coupon that fits the bill // report this to Sentry? Seems like a bug if we aren't able to find one. if (pppMerchantCoupon === null) return null return pppMerchantCoupon }
// TODO: Should we cross-check the incoming `pppDiscountPercent` with
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/src/lib/pricing/determine-coupon-to-apply.ts#L273-L290
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
findOrCreateStripeCustomerId
async function findOrCreateStripeCustomerId( userId: string, adapter: CourseBuilderAdapter, paymentsAdapter: PaymentsAdapter, ) { const user = await adapter.getUser?.(userId) if (user) { const merchantCustomer = await adapter.getMerchantCustomerForUserId(user.id) const customerId = user && merchantCustomer ? merchantCustomer.identifier : false if (customerId) { return customerId } else { const merchantAccount = await adapter.getMerchantAccount({ provider: 'stripe', }) if (merchantAccount) { const customerId = await paymentsAdapter.createCustomer({ email: user.email, metadata: { userId: user.id, }, }) await adapter.createMerchantCustomer({ identifier: customerId, merchantAccountId: merchantAccount.id, userId, }) return customerId } } } return false }
/** * Given a specific user we want to lookup their Stripe * customer ID and if one doesn't exist we will * create it. * @param userId * @param adapter * @param paymentsAdapter */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/src/lib/pricing/stripe-checkout.ts#L59-L94
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
match
const match = ( value1: string | number | undefined, value2: string | number | undefined, ) => { return Boolean(value1 && value2 && value1 === value2) }
/** * Check that two values match without matching on two undefined values * * This is helpful when you find yourself doing a comparison like * `obj?.a === obj?.b`. If both values are undefined, then it resolves to * true. If you don't want that, then you have to guard the comparison, * `obj?.a && obj?.b && obj?.a === obj?.b`. This function takes care of that. */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/src/lib/pricing/stripe-purchase-utils.ts#L230-L235
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
isObject
function isObject(item: any): boolean { return item && typeof item === 'object' && !Array.isArray(item) }
// Source: https://stackoverflow.com/a/34749873/5364135
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/src/lib/utils/merge.ts#L4-L6
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
makeid
function makeid(length: number) { let result = '' const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' // Build a string of the specified length by randomly selecting // characters from the alphabet at each iteration. for (let i = 0; i < length; i++) { const randomIndex = Math.floor(Math.random() * alphabet.length) result += alphabet.charAt(randomIndex) } return result }
/** * Generates a random string of the specified length. * @param length The length of the generated string. * @returns The randomly generated string. */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/core/test/memory-adapter.ts#L224-L237
a78eefd64f7d896032f93dba2accd9dd84ce80ea
course-builder
github_2023
badass-courses
typescript
useCodemirror
const useCodemirror = ({ roomName, value, onChange, partykitUrl, user, theme = 'dark', }: { roomName: string value: string onChange: (data: any) => void partykitUrl?: string user?: User | null theme?: string }) => { const [element, setElement] = useState<HTMLElement>() const [yUndoManager, setYUndoManager] = useState<Y.UndoManager>() const [currentText, setCurrentText] = useState<string>(value) let updateListenerExtension = EditorView.updateListener.of(async (update) => { if (update.docChanged) { const docText = update.state.doc.toString() const hash = await generateHash(docText) if (hash !== currentText) { onChange(docText) setCurrentText(hash) } } }) useEffect(() => { let view: EditorView if (!element) { return } const ytext = new Y.Doc().getText('codemirror') const undoManager = new Y.UndoManager(ytext) setYUndoManager(undoManager) // Set up CodeMirror and extensions const state = EditorState.create({ doc: value, extensions: [ basicSetup, updateListenerExtension, theme === 'dark' ? CourseBuilderEditorThemeDark : CourseBuilderEditorThemeLight, markdown({ codeLanguages: languages, }), ...styles, ], }) // Attach CodeMirror to element view = new EditorView({ state, parent: element, }) // Set up awareness return () => { // provider?.doc?.destroy() // provider?.destroy() view?.destroy() } }, [roomName, value, user, theme]) return { codemirrorElementRef: useCallback((node: HTMLElement | null) => { if (!node) return setElement(node) }, []), } }
/** * @see {@link https://codemirror.net/docs/ref/#codemirror.basicSetup Code Mirror Basic Setup} * @param options * @constructor */
https://github.com/badass-courses/course-builder/blob/a78eefd64f7d896032f93dba2accd9dd84ce80ea/packages/ui/codemirror/editor.tsx#L107-L186
a78eefd64f7d896032f93dba2accd9dd84ce80ea
effects-runtime
github_2023
galacean
typescript
AssetLoader.loadGUIDAsync
async loadGUIDAsync<T> (guid: string): Promise<T> { if (this.engine.objectInstance[guid]) { return this.engine.objectInstance[guid] as T; } const effectsObjectData = this.findData(guid); let effectsObject: EffectsObject | undefined; if (!effectsObjectData) { if (!this.engine.database) { console.error(`Object data with uuid: ${guid} not found.`); return undefined as T; } effectsObject = await this.engine.database.loadGUID(guid); if (!effectsObject) { console.error(`Disk data with uuid: ${guid} not found.`); return undefined as T; } this.engine.addInstance(effectsObject); return effectsObject as T; } switch (effectsObjectData.dataType) { case spec.DataType.Material: effectsObject = Material.create(this.engine); break; case spec.DataType.Geometry: effectsObject = Geometry.create(this.engine); break; case spec.DataType.Texture: effectsObject = Texture.create(this.engine); break; default: { const classConstructor = AssetLoader.getClass(effectsObjectData.dataType); if (classConstructor) { effectsObject = new classConstructor(this.engine); } } } if (!effectsObject) { console.error(`Constructor for DataType: ${effectsObjectData.dataType} not found.`); return undefined as T; } effectsObject.setInstanceId(effectsObjectData.id); this.engine.addInstance(effectsObject); await SerializationHelper.deserializeAsync(effectsObjectData, effectsObject); return effectsObject as T; }
// 加载本地文件资产
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/asset-loader.ts#L68-L129
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
AssetManager.constructor
constructor ( public options: Omit<SceneLoadOptions, 'speed' | 'autoplay' | 'reusable'> = {}, private readonly downloader = new Downloader(), ) { this.updateOptions(options); }
/** * 构造函数 * @param options - 场景加载参数 * @param downloader - 资源下载对象 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/asset-manager.ts#L61-L66
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
AssetManager.loadScene
async loadScene ( url: Scene.LoadType, renderer?: Renderer, options?: { env: string }, ): Promise<Scene> { let rawJSON: Scene.LoadType; const assetUrl = isString(url) ? url : this.id; const startTime = performance.now(); const timeInfoMessages: string[] = []; const gpuInstance = renderer?.engine.gpuCapability; const compressedTexture = gpuInstance?.detail.compressedTexture ?? COMPRESSED_TEXTURE.NONE; const timeInfos: Record<string, number> = {}; let loadTimer: number; let cancelLoading = false; const waitPromise = new Promise<Scene>((resolve, reject) => { loadTimer = window.setTimeout(() => { cancelLoading = true; this.removeTimer(loadTimer); const totalTime = performance.now() - startTime; reject(new Error(`Load time out: totalTime: ${totalTime.toFixed(4)}ms ${timeInfoMessages.join(' ')}, url: ${assetUrl}.`)); }, this.timeout * 1000); this.timers.push(loadTimer); }); const hookTimeInfo = async<T> (label: string, func: () => Promise<T>) => { if (!cancelLoading) { const st = performance.now(); try { const result = await func(); const time = performance.now() - st; timeInfoMessages.push(`[${label}: ${time.toFixed(2)}]`); timeInfos[label] = time; return result; } catch (e) { throw new Error(`Load error in ${label}, ${e}.`); } } throw new Error('Load canceled.'); }; const loadResourcePromise = async () => { let scene: Scene; if (isString(url)) { // 兼容相对路径 const link = new URL(url, location.href).href; this.baseUrl = link; rawJSON = await hookTimeInfo('loadJSON', () => this.loadJSON(link) as unknown as Promise<spec.JSONScene>); } else { // url 为 spec.JSONScene 或 Scene 对象 rawJSON = url; this.baseUrl = location.href; } if (Scene.isJSONObject(rawJSON)) { // 已经加载过的 可能需要更新数据模板 scene = { ...rawJSON, }; const { jsonScene, pluginSystem, images: loadedImages } = scene; const { compositions, images } = jsonScene; this.assignImagesToAssets(images, loadedImages); await Promise.all([ hookTimeInfo('plugin:processAssets', () => this.processPluginAssets(jsonScene, pluginSystem, options)), hookTimeInfo('plugin:precompile', () => this.precompile(compositions, pluginSystem, renderer, options)), ]); } else { // TODO: JSONScene 中 bins 的类型可能为 ArrayBuffer[] const { jsonScene, pluginSystem } = await hookTimeInfo('processJSON', () => this.processJSON(rawJSON as JSONValue)); const { bins = [], images, compositions, fonts } = jsonScene; const [loadedBins, loadedImages] = await Promise.all([ hookTimeInfo('processBins', () => this.processBins(bins)), hookTimeInfo('processImages', () => this.processImages(images, compressedTexture)), hookTimeInfo('plugin:processAssets', () => this.processPluginAssets(jsonScene, pluginSystem, options)), hookTimeInfo('plugin:precompile', () => this.precompile(compositions, pluginSystem, renderer, options)), hookTimeInfo('processFontURL', () => this.processFontURL(fonts as spec.FontDefine[])), ]); const loadedTextures = await hookTimeInfo('processTextures', () => this.processTextures(loadedImages, loadedBins, jsonScene)); scene = { timeInfos, url, renderLevel: this.options.renderLevel, storage: {}, pluginSystem, jsonScene, bins: loadedBins, images: loadedImages, textureOptions: loadedTextures, }; // 触发插件系统 pluginSystem 的回调 prepareResource await hookTimeInfo('plugin:prepareResource', () => pluginSystem.loadResources(scene, this.options)); } await hookTimeInfo('prepareAssets', () => this.prepareAssets(renderer?.engine)); const totalTime = performance.now() - startTime; logger.info(`Load asset: totalTime: ${totalTime.toFixed(4)}ms ${timeInfoMessages.join(' ')}, url: ${assetUrl}.`); window.clearTimeout(loadTimer); this.removeTimer(loadTimer); scene.totalTime = totalTime; scene.startTime = startTime; // 各部分分段时长 scene.timeInfos = timeInfos; return scene; }; return Promise.race([waitPromise, loadResourcePromise()]); }
/** * 场景创建,通过 json 创建出场景对象,并进行提前编译等工作 * @param url - json 的 URL 链接或者 json 对象 * @param renderer - renderer 对象,用于获取管理、编译 shader 及 GPU 上下文的参数 * @param options - 扩展参数 * @returns */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/asset-manager.ts#L85-L204
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
AssetManager.dispose
dispose (): void { if (this.timers.length) { this.timers.map(id => window.clearTimeout(id)); } this.assets = {}; this.sourceFrom = {}; this.timers = []; }
/** * 销毁方法 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/asset-manager.ts#L484-L491
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.constructor
constructor ( public name: string, options: Partial<CameraOptions> = {}, ) { const { near = 0.1, far = 20, fov = 60, aspect = 1, clipMode = spec.CameraClipMode.portrait, position = [0, 0, 8], rotation = [0, 0, 0], } = options; this.options = { near, far, fov, aspect, clipMode, position: Vector3.fromArray(position), rotation: Euler.fromArray(rotation), }; this.dirty = true; this.updateMatrix(); }
/** * * @param name - 相机名称 * @param options */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L89-L110
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.near
set near (near: number) { if (this.options.near !== near) { this.options.near = near; this.dirty = true; } }
/** * 设置相机近平面 * @param near */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L116-L121
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.far
set far (far: number) { if (this.options.far !== far) { this.options.far = far; this.dirty = true; } }
/** * 设置相机远平面 * @param far */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L130-L135
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.fov
set fov (fov: number) { if (this.options.fov !== fov) { this.options.fov = fov; this.dirty = true; } }
/** * 设置相机视锥体垂直视野角度 * @param fov */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L144-L149
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.aspect
set aspect (aspect: number) { if (this.options.aspect !== aspect) { this.options.aspect = aspect; this.dirty = true; } }
/** * 设置相机视锥体的长宽比 * @param aspect */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L158-L163
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.clipMode
set clipMode (clipMode: spec.CameraClipMode | undefined) { if (clipMode !== undefined && this.options.clipMode !== clipMode) { this.options.clipMode = clipMode; this.dirty = true; } }
/** * 相机的裁剪模式 * @param clipMode */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L172-L178
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.position
set position (value: Vector3) { if (!this.options.position.equals(value)) { this.options.position.copyFrom(value); this.dirty = true; } }
/** * 设置相机的位置 * @param value */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L187-L192
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.rotation
set rotation (value: Euler) { if (!this.options.rotation.equals(value)) { this.options.rotation.copyFrom(value); this.dirty = true; this.options.quat = undefined; } }
/** * 设置相机的旋转角度 * @param value */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L201-L207
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getViewMatrix
getViewMatrix (): Matrix4 { this.updateMatrix(); return this.viewMatrix.clone(); }
/** * 获取相机的视图变换矩阵 * @return */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L225-L229
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getInverseViewMatrix
getInverseViewMatrix (): Matrix4 { this.updateMatrix(); return this.inverseViewMatrix.clone(); }
/** * 获取视图变换的逆矩阵 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L234-L238
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getProjectionMatrix
getProjectionMatrix (): Matrix4 { this.updateMatrix(); return this.projectionMatrix.clone(); }
/** * 获取相机的投影矩阵 * @return */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L244-L248
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getInverseProjectionMatrix
getInverseProjectionMatrix (): Matrix4 { this.updateMatrix(); return this.inverseProjectionMatrix?.clone() as Matrix4; }
/** * 获取相机投影矩阵的逆矩阵 * @return */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L254-L258
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getViewProjectionMatrix
getViewProjectionMatrix (): Matrix4 { this.updateMatrix(); return this.viewProjectionMatrix.clone(); }
/** * 获取相机的 VP 矩阵 * @return */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L264-L268
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getInverseViewProjectionMatrix
getInverseViewProjectionMatrix (): Matrix4 { this.updateMatrix(); if (!this.inverseViewProjectionMatrix) { this.inverseViewProjectionMatrix = this.viewProjectionMatrix.clone(); this.inverseViewProjectionMatrix.invert(); } return this.inverseViewProjectionMatrix.clone(); }
/** * 获取相机 VP 矩阵的逆矩阵 * @return */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L274-L282
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getModelViewProjection
getModelViewProjection (out: Matrix4, model: Matrix4) { return out.multiplyMatrices(this.viewProjectionMatrix, model); }
/** * 根据相机的视图投影矩阵对指定模型矩阵做变换 * @param out - 结果矩阵 * @param model - 模型变换矩阵 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L289-L291
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getInverseVPRatio
getInverseVPRatio (z: number) { const pos = new Vector3(this.position.x, this.position.y, z); const mat = this.getViewProjectionMatrix(); const inverseMat = this.getInverseViewProjectionMatrix(); if (!this.viewportMatrix.isIdentity()) { const viewportMatrix = this.viewportMatrix.clone(); inverseMat.premultiply(viewportMatrix); mat.multiply(viewportMatrix.invert()); } const { z: nz } = mat.projectPoint(pos); const { x: xMax, y: yMax } = inverseMat.projectPoint(new Vector3(1, 1, nz)); const { x: xMin, y: yMin } = inverseMat.projectPoint(new Vector3(-1, -1, nz)); return new Vector3((xMax - xMin) / 2, (yMax - yMin) / 2, 0); }
/** * 获取归一化坐标和 3D 世界坐标的换算比例,使用 ViewProjection 矩阵 * @param z - 当前的位置 z */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L297-L314
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.setQuat
setQuat (value: Quaternion) { if (this.options.quat === undefined) { this.options.quat = value.clone(); this.dirty = true; } else { if (!this.options.quat.equals(value)) { this.options.quat.copyFrom(value); this.dirty = true; } } if (this.dirty) { this.setRotationByQuat(value); } }
/** * 设置相机的旋转四元数 * @param value - 旋转四元数 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L320-L333
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getQuat
getQuat (): Quaternion { let quat = this.options.quat; if (quat === undefined) { quat = new Quaternion(); const { rotation } = this.options; if (rotation) { quat.setFromEuler(rotation); } this.options.quat = quat; } return quat; }
/** * 获取相机旋转对应的四元数 * @returns */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L339-L354
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.getOptions
getOptions (): CameraOptionsEx { return this.options; }
/** * 获取相机内部的 options * @returns 相机 options */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L360-L362
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.copy
copy (camera: Camera) { const { near, far, fov, clipMode, aspect, position, rotation, } = camera; this.near = near; this.far = far; this.fov = fov; this.clipMode = clipMode; this.aspect = aspect; this.position = position; this.rotation = rotation; this.updateMatrix(); }
/** * 复制指定相机元素的属性到当前相机 * @param camera */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L368-L387
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Camera.updateMatrix
updateMatrix () { if (this.dirty) { const { fov, aspect, near, far, clipMode, position } = this.options; this.projectionMatrix.perspective( fov * DEG2RAD, aspect, near, far, clipMode === spec.CameraClipMode.portrait ); this.projectionMatrix.premultiply(this.viewportMatrix); this.inverseViewMatrix.compose(position, this.getQuat(), tmpScale); this.viewMatrix.copyFrom(this.inverseViewMatrix).invert(); this.viewProjectionMatrix.multiplyMatrices(this.projectionMatrix, this.viewMatrix); this.inverseViewProjectionMatrix = null; this.dirty = false; } }
/** * 更新相机相关的矩阵,获取矩阵前会自动调用 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/camera.ts#L392-L408
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
CompositionComponent.setChildrenRenderOrder
setChildrenRenderOrder (startOrder: number): number { for (const item of this.items) { item.renderOrder = startOrder++; const subCompositionComponent = item.getComponent(CompositionComponent); if (subCompositionComponent) { startOrder = subCompositionComponent.setChildrenRenderOrder(startOrder); } } return startOrder; }
/** * 设置当前合成子元素的渲染顺序 * @internal */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/comp-vfx-item.ts#L231-L243
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
CompositionSourceManager.processMask
private processMask (renderer: RendererOptionsWithMask) { const maskMode = renderer.maskMode; if (maskMode === spec.MaskMode.NONE) { return; } if (!renderer.mask) { if (maskMode === spec.MaskMode.MASK) { renderer.mask = ++this.mask; } else if ( maskMode === spec.MaskMode.OBSCURED || maskMode === spec.MaskMode.REVERSE_OBSCURED ) { renderer.mask = this.mask; } } }
/** * 处理蒙版和遮挡关系写入 stencil 的 ref 值 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition-source-manager.ts#L216-L232
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.constructor
constructor ( props: CompositionProps, scene: Scene, ) { super(); const { reusable = false, speed = 1, baseRenderOrder = 0, renderer, event, width, height, handleItemMessage, } = props; this.compositionSourceManager = new CompositionSourceManager(scene, renderer.engine); if (reusable) { this.keepResource = true; scene.textures = undefined; scene.consumed = true; } const { sourceContent, pluginSystem, imgUsage, totalTime, refCompositionProps } = this.compositionSourceManager; this.postProcessingEnabled = scene.jsonScene.renderSettings?.postProcessingEnabled ?? false; assertExist(sourceContent); this.renderer = renderer; this.refCompositionProps = refCompositionProps; // Instantiate composition rootItem this.rootItem = new VFXItem(this.getEngine()); this.rootItem.name = 'rootItem'; this.rootItem.duration = sourceContent.duration; this.rootItem.endBehavior = sourceContent.endBehavior; this.rootItem.composition = this; // Create rootCompositionComponent this.rootComposition = this.rootItem.addComponent(CompositionComponent); this.width = width; this.height = height; this.renderOrder = baseRenderOrder; this.id = sourceContent.id; this.renderer = renderer; this.texInfo = !reusable ? imgUsage : {}; this.event = event; this.statistic = { loadStart: scene.startTime ?? 0, loadTime: totalTime ?? 0, compileTime: 0, firstFrameTime: 0, }; this.reusable = reusable; this.speed = speed; this.autoRefTex = !this.keepResource && this.texInfo && this.rootItem.endBehavior !== spec.EndBehavior.restart; this.name = sourceContent.name; this.pluginSystem = pluginSystem as PluginSystem; this.pluginSystem.initializeComposition(this, scene); this.camera = new Camera(this.name, { ...sourceContent?.camera, aspect: width / height, }); this.url = scene.url; this.assigned = true; this.interactive = true; this.handleItemMessage = handleItemMessage; this.createRenderFrame(); this.rendererOptions = null; SerializationHelper.deserialize(sourceContent as unknown as spec.EffectsObjectData, this.rootComposition); this.rootComposition.createContent(); this.buildItemTree(this.rootItem); this.rootComposition.setChildrenRenderOrder(0); this.pluginSystem.resetComposition(this, this.renderFrame); }
/** * Composition 构造函数 * @param props - composition 的创建参数 * @param scene * @param compositionSourceManager */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L223-L297
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.transform
get transform () { return this.rootItem.transform; }
/** * 所有合成 Item 的根变换 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L302-L304
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.textures
get textures () { return this.compositionSourceManager.textures; }
/** * 获取场景中的纹理数组 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L309-L311
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.items
get items (): VFXItem[] { return this.rootComposition.items; }
/** * 获取合成中所有元素 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L316-L318
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.startTime
get startTime () { return this.rootComposition.startTime; }
/** * 获取合成开始渲染的时间 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L323-L325
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.time
get time () { return this.rootComposition.time; }
/** * 获取合成当前时间 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L330-L332
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.isDestroyed
get isDestroyed (): boolean { return this.destroyed; }
/** * 获取销毁状态 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L337-L339
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.getDuration
getDuration () { return this.rootItem.duration; }
/** * 获取合成的时长 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L351-L353
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.restart
restart () { this.reset(); this.forwardTime(this.startTime); }
/** * 重新开始合成 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L358-L361
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.setIndex
setIndex (index: number) { this.renderOrder = index; }
/** * 设置当前合成的渲染顺序 * @param index - 序号,大的后绘制 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L367-L369
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.getIndex
getIndex (): number { return this.renderOrder; }
/** * 获取当前合成的渲染顺序 * @returns */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L375-L377
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.setSpeed
setSpeed (speed: number) { this.speed = speed; }
/** * 设置合成的动画速度 * @param speed - 速度 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L383-L385
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.setVisible
setVisible (visible: boolean) { this.rootItem.setVisible(visible); }
/** * 设置合成的可见性 * @since 2.0.0 * @param visible - 是否可见 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L392-L394
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.getSpeed
getSpeed () { return this.speed; }
/** * 获取合成的动画速度 * @returns */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L400-L402
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.pause
pause () { this.paused = true; }
/** * 暂停合成的播放 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L418-L420
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.resume
resume () { this.paused = false; }
/** * 恢复合成的播放 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L429-L431
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.gotoAndPlay
gotoAndPlay (time: number) { this.setTime(time); this.resume(); }
/** * 跳转合成到指定时间播放 * @param time - 相对 startTime 的时间 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L437-L440
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.gotoAndStop
gotoAndStop (time: number) { this.setTime(time); this.pause(); }
/** * 跳转合成到指定时间并暂停 * @param time - 相对 startTime 的时间 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L446-L449
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.createRenderFrame
createRenderFrame () { this.renderFrame = new RenderFrame({ camera: this.camera, renderer: this.renderer, keepColorBuffer: this.keepColorBuffer, globalVolume: this.globalVolume, postProcessingEnabled: this.postProcessingEnabled, }); // TODO 考虑放到构造函数 this.renderFrame.cachedTextures = this.textures; }
/** * */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L454-L464
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.setTime
setTime (time: number) { const speed = this.speed; const pause = this.paused; if (pause) { this.resume(); } this.setSpeed(1); this.forwardTime(time + this.startTime); this.setSpeed(speed); if (pause) { this.pause(); } this.emit('goto', { time }); }
/** * 跳到指定时间点(不做任何播放行为) * @param time - 相对 startTime 的时间 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L470-L484
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.forwardTime
private forwardTime (time: number) { const deltaTime = time * 1000 - this.rootComposition.time * 1000; const reverse = deltaTime < 0; const step = 15; let t = Math.abs(deltaTime); const ss = reverse ? -step : step; for (t; t > step; t -= step) { this.update(ss); } this.update(reverse ? -t : t); }
/** * 前进合成到指定时间 * @param time - 相对0时刻的时间 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L495-L506
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.reset
protected reset () { this.rendererOptions = null; this.isEnded = false; this.isEndCalled = false; this.rootComposition.time = 0; this.pluginSystem.resetComposition(this, this.renderFrame); }
/** * 重置状态函数 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L511-L517
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.update
update (deltaTime: number) { if (!this.assigned || this.paused) { return; } const dt = parseFloat(this.getUpdateTime(deltaTime * this.speed).toFixed(0)); this.updateRootComposition(dt / 1000); this.updateVideo(); // 更新 model-tree-plugin this.updatePluginLoaders(deltaTime); // scene VFXItem components lifetime function. if (!this.rootItem.isDuringPlay) { this.callAwake(this.rootItem); this.rootItem.beginPlay(); } this.sceneTicking.update.tick(dt); this.sceneTicking.lateUpdate.tick(dt); this.updateCamera(); this.prepareRender(); if (this.isEnded && !this.isEndCalled) { this.isEndCalled = true; this.emit('end', { composition: this }); } if (this.shouldDispose()) { this.dispose(); } }
/** * 合成更新,针对所有 item 的更新 * @param deltaTime - 更新的时间步长 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L536-L566
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.buildItemTree
private buildItemTree (compVFXItem: VFXItem) { if (!compVFXItem.composition) { return; } const itemMap = new Map<string, VFXItem>(); const contentItems = compVFXItem.getComponent(CompositionComponent).items; for (const item of contentItems) { itemMap.set(item.id, item); } for (const item of contentItems) { if (item.parentId === undefined) { item.setParent(compVFXItem); } else { const parent = itemMap.get(item.parentId); if (parent) { item.parent = parent; item.transform.parentTransform = parent.transform; parent.children.push(item); } else { throw new Error('The element references a non-existent element, please check the data.'); } } } for (const item of contentItems) { if (VFXItem.isComposition(item)) { this.buildItemTree(item); } } }
/** * 构建父子树,同时保存到 itemCacheMap 中便于查找 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L598-L631
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.updateVideo
updateVideo () { const now = performance.now(); // 视频固定30帧更新 if (now - this.lastVideoUpdateTime > 33) { (this.textures ?? []).forEach(tex => tex?.uploadCurrentVideoFrame()); this.lastVideoUpdateTime = now; } }
/** * 更新视频数据到纹理 * @override */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L637-L645
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.updateCamera
private updateCamera () { this.camera.updateMatrix(); }
/** * 更新相机 * @override */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L651-L653
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.updatePluginLoaders
private updatePluginLoaders (deltaTime: number) { this.pluginSystem.plugins.forEach(loader => loader.onCompositionUpdate(this, deltaTime)); }
/** * 插件更新,来自 CompVFXItem 的更新调用 * @param deltaTime - 更新的时间步长 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L659-L661
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.updateRootComposition
private updateRootComposition (deltaTime: number) { if (this.rootComposition.isActiveAndEnabled) { let localTime = parseFloat((this.time + deltaTime - this.rootItem.start).toFixed(3)); let isEnded = false; const duration = this.rootItem.duration; const endBehavior = this.rootItem.endBehavior; if (localTime - duration > 0.001) { isEnded = true; switch (endBehavior) { case spec.EndBehavior.restart: { localTime = localTime % duration; this.restart(); break; } case spec.EndBehavior.freeze: { localTime = Math.min(duration, localTime); break; } case spec.EndBehavior.forward: { break; } case spec.EndBehavior.destroy: { break; } } } this.rootComposition.time = localTime; // end state changed, handle onEnd flags if (this.isEnded !== isEnded) { if (isEnded) { this.isEnded = true; } else { this.isEnded = false; this.isEndCalled = false; } } } }
/** * 更新主合成组件 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L666-L714
20512f4406e62c400b2b4255576cfa628db74a22
effects-runtime
github_2023
galacean
typescript
Composition.getItemByName
getItemByName (name: string) { return this.rootItem.find(name); }
/** * 通过名称获取元素 * @param name - 元素名称 * @returns 元素对象 */
https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/packages/effects-core/src/composition.ts#L721-L723
20512f4406e62c400b2b4255576cfa628db74a22