repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
aibitat
github_2023
wladpaiva
typescript
AIbitat.getHistory
private getHistory({from, to}: {from?: string; to?: string}) { return this._chats.filter(chat => { const isSuccess = chat.state === 'success' // return all chats to the node if (!from) { return isSuccess && chat.to === to } // get all chats from the node if (!to) { return isSuccess && chat.from === from } // check if the chat is between the two nodes const hasSent = chat.from === from && chat.to === to const hasReceived = chat.from === to && chat.to === from const mutual = hasSent || hasReceived return isSuccess && mutual }) as { from: string to: string content: string state: 'success' }[] }
/** * Get the chat history between two nodes or all chats to/from a node. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L796-L822
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.getProviderForConfig
private getProviderForConfig<T extends Provider>(config: ProviderConfig<T>) { if (typeof config.provider === 'object') { return config.provider } switch (config.provider) { case 'openai': return new Providers.OpenAIProvider({model: config.model}) case 'anthropic': return new Providers.AnthropicProvider({model: config.model}) default: throw new Error( `Unknown provider: ${config.provider}. Please use "openai"`, ) } }
/** * Get provider based on configurations. * If the provider is a string, it will return the default provider for that string. * * @param config The provider configuration. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L830-L846
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.function
public function(functionConfig: AIbitat.FunctionConfig) { this.functions.set(functionConfig.name, functionConfig) return this }
/** * Register a new function to be called by the AIbitat agents. * You are also required to specify the which node can call the function. * @param functionConfig The function configuration. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L853-L856
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
cli
function cli({ simulateStream = true, }: { /** * Simulate streaming by breaking the cached response into chunks. * Helpful to make the conversation more realistic and faster. * @default true */ simulateStream?: boolean } = {}) { return { name: 'cli', setup(aibitat) { let printing: Promise<void>[] = [] aibitat.onError(async error => { console.error(chalk.red(` error: ${(error as Error).message}`)) if (error instanceof RetryError) { console.error(chalk.red(` retrying in 60 seconds...`)) setTimeout(() => { aibitat.retry() }, 60000) return } }) aibitat.onStart(() => { console.log() console.log('πŸš€ starting chat ...\n') console.time('πŸš€ chat finished!') printing = [Promise.resolve()] }) aibitat.onMessage(async message => { const next = new Promise<void>(async resolve => { await Promise.all(printing) await cli.print(message, simulateStream) resolve() }) printing.push(next) }) aibitat.onTerminate(async () => { await Promise.all(printing) console.timeEnd('πŸš€ chat finished') }) aibitat.onInterrupt(async node => { await Promise.all(printing) const feedback = await cli.askForFeedback(node) // Add an extra line after the message console.log() if (feedback === 'exit') { console.timeEnd('πŸš€ chat finished') return process.exit(0) } await aibitat.continue(feedback) }) }, } as AIbitat.Plugin<any> }
/** * Command-line Interface plugin. It prints the messages on the console and asks for feedback * while the conversation is running in the background. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/plugins/cli.ts#L11-L73
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
search
async function search( query: string, options: { /** * `serper.dev` API key. * @default process.env.SERPER_API_KEY */ serperApiKey?: string } = {}, ) { console.log('πŸ”₯ ~ Searching on Google...') const url = 'https://google.serper.dev/search' const payload = JSON.stringify({ q: query, }) const headers = { 'X-API-KEY': options.serperApiKey || (process.env.SERPER_API_KEY as string), 'Content-Type': 'application/json', } const response = await fetch(url, { method: 'POST', headers: headers, body: payload, }) return response.text() }
/** * Use serper.dev to search on Google. * * **Requires an SERPER_API_KEY environment variable**. * * @param query * @param options * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/plugins/web-browsing.ts#L18-L47
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AnthropicProvider.complete
async complete( messages: Provider.Message[], functions?: AIbitat.FunctionDefinition[], ): Promise<Provider.Completion> { // clone messages to avoid mutating the original array const promptMessages = [...messages] if (functions) { const functionPrompt = this.getFunctionPrompt(functions) // add function prompt after the first message promptMessages.splice(1, 0, { content: functionPrompt, role: 'system', }) } const prompt = promptMessages .map(message => { const {content, role} = message switch (role) { case 'system': return content ? `${Anthropic.HUMAN_PROMPT} <admin>${content}</admin>` : '' case 'function': case 'user': return `${Anthropic.HUMAN_PROMPT} ${content}` case 'assistant': return `${Anthropic.AI_PROMPT} ${content}` default: return content } }) .filter(Boolean) .join('\n') .concat(` ${Anthropic.AI_PROMPT}`) try { const response = await this.client.completions.create({ model: this.model, max_tokens_to_sample: 3000, stream: false, prompt, }) const result = response.completion.trim() // TODO: get cost from response const cost = 0 // Handle function calls if the model returns a function call if (result.includes('function_name') && functions) { let functionCall: AIbitat.FunctionCall try { functionCall = JSON.parse(result) } catch (error) { // call the complete function again in case it gets a json error return await this.complete( [ ...messages, { role: 'function', content: `You gave me this function call: ${result} but I couldn't parse it. ${(error as Error).message} Please try again.`, }, ], functions, ) } return { result: null, functionCall, cost, } } return { result, cost, } } catch (error) { if ( error instanceof Anthropic.RateLimitError || error instanceof Anthropic.InternalServerError || error instanceof Anthropic.APIError ) { throw new RetryError(error.message) } throw error } }
/** * Create a completion based on the received messages. * * @param messages A list of messages to send to the Anthropic API. * @param functions * @returns The completion. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/providers/anthropic.ts#L58-L156
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
OpenAIProvider.complete
async complete( messages: OpenAI.ChatCompletionMessageParam[], functions?: AIbitat.FunctionDefinition[], ): Promise<Provider.Completion> { try { const response = await this.client.chat.completions.create({ model: this.model, // stream: true, messages, functions, }) // Right now, we only support one completion, // so we just take the first one in the list const completion = response.choices[0].message const cost = this.getCost(response.usage) // treat function calls if (completion.function_call) { let functionArgs: object try { functionArgs = JSON.parse(completion.function_call.arguments) } catch (error) { // call the complete function again in case it gets a json error return this.complete( [ ...messages, { role: 'function', name: completion.function_call.name, function_call: completion.function_call, content: (error as Error).message, }, ], functions, ) } return { result: null, functionCall: { name: completion.function_call.name, arguments: functionArgs!, }, cost, } } return { result: completion.content, cost, } } catch (error) { if ( error instanceof OpenAI.RateLimitError || error instanceof OpenAI.InternalServerError || error instanceof OpenAI.APIError ) { throw new RetryError(error.message) } throw error } }
/** * Create a completion based on the received messages. * * @param messages A list of messages to send to the OpenAI API. * @param functions * @returns The completion. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/providers/openai.ts#L76-L138
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
OpenAIProvider.getCost
getCost(usage: OpenAI.Completions.CompletionUsage | undefined) { if (!usage) { return Number.NaN } // regex to remove the version number from the model const modelBase = this.model.replace(/-(\d{4})$/, '') if (!(modelBase in OpenAIProvider.COST_PER_TOKEN)) { return Number.NaN } const costPerToken = OpenAIProvider.COST_PER_TOKEN[ modelBase as keyof typeof OpenAIProvider.COST_PER_TOKEN ] const inputCost = (usage.prompt_tokens / 1000) * costPerToken.input const outputCost = (usage.completion_tokens / 1000) * costPerToken.output return inputCost + outputCost }
/** * Get the cost of the completion. * * @param usage The completion to get the cost for. * @returns The cost of the completion. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/providers/openai.ts#L146-L167
d66dfddae5c7b8c974cbee442707a04635333181
mini-canvas-editor
github_2023
img-js
typescript
MceCanvasReplacer.replaceRectToImage
public async replaceRectToImage( layer: MceLayer, sourceImage: HTMLImageElement | string, mode: 'stretch' | 'fit' | 'fill' ): Promise<void> { const rect = this.objects[layer.realIndex] as MceRect; if (!rect.visible) { // If the layer is hidden, do nothing. return; } if (typeof sourceImage === 'string') { sourceImage = await loadImage(sourceImage); } let image: MceImage; switch (mode) { case 'stretch': image = stretchImage(rect, sourceImage); break; case 'fit': image = fitImage(rect, sourceImage); break; case 'fill': image = fillImage(rect, sourceImage); break; default: throw new Error(`Unknown mode: ${mode}`); } this.canvas.remove(rect); this.canvas.insertAt(layer.realIndex, image); }
/** * Replace rectangle to image. * @param layer Layer. * @param sourceImage Image element or URL (for example data URL: `data:image/png;base64,...`). * @param mode Mode of fitting image to the rectangle. * @returns Promise that resolves when the rect is replaced. */
https://github.com/img-js/mini-canvas-editor/blob/17f21019bdac5a40d09fcdaaacd56915a8c356f6/core/src/replacer/mce-canvas-replacer.ts#L40-L71
17f21019bdac5a40d09fcdaaacd56915a8c356f6
mini-canvas-editor
github_2023
img-js
typescript
MceImage.toObject
public toObject(propertiesToInclude: string[] = []) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return super.toObject(propertiesToInclude.concat(['label', 'selectable']) as any); }
// @ts-expect-error TS this typing limitations
https://github.com/img-js/mini-canvas-editor/blob/17f21019bdac5a40d09fcdaaacd56915a8c356f6/core/src/shapes/mce-image.ts#L18-L21
17f21019bdac5a40d09fcdaaacd56915a8c356f6
mini-canvas-editor
github_2023
img-js
typescript
McePath.constructor
public constructor(path: any, options: TOptions<McePathProps>) { super(path, { label: 'Path', ...options }); }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/img-js/mini-canvas-editor/blob/17f21019bdac5a40d09fcdaaacd56915a8c356f6/core/src/shapes/mce-path.ts#L15-L20
17f21019bdac5a40d09fcdaaacd56915a8c356f6
mini-canvas-editor
github_2023
img-js
typescript
McePath.toObject
public toObject(propertiesToInclude: string[] = []) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return super.toObject(propertiesToInclude.concat(['label', 'selectable']) as any); }
// @ts-expect-error TS this typing limitations
https://github.com/img-js/mini-canvas-editor/blob/17f21019bdac5a40d09fcdaaacd56915a8c356f6/core/src/shapes/mce-path.ts#L23-L26
17f21019bdac5a40d09fcdaaacd56915a8c356f6
mini-canvas-editor
github_2023
img-js
typescript
MceRect.toObject
public toObject(propertiesToInclude: string[] = []) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return super.toObject(propertiesToInclude.concat(['label', 'selectable']) as any); }
// @ts-expect-error TS this typing limitations
https://github.com/img-js/mini-canvas-editor/blob/17f21019bdac5a40d09fcdaaacd56915a8c356f6/core/src/shapes/mce-rect.ts#L33-L36
17f21019bdac5a40d09fcdaaacd56915a8c356f6
mini-canvas-editor
github_2023
img-js
typescript
MceTextbox.toObject
public toObject(propertiesToInclude: string[] = []) { return super.toObject( propertiesToInclude.concat([ 'label', 'selectable', 'verticalAlign', 'maxHeight', 'verticalAlign', 'textBackground', 'textBackgroundFill' // eslint-disable-next-line @typescript-eslint/no-explicit-any ]) as any ); }
// @ts-expect-error TS this typing limitations
https://github.com/img-js/mini-canvas-editor/blob/17f21019bdac5a40d09fcdaaacd56915a8c356f6/core/src/shapes/mce-textbox.ts#L115-L128
17f21019bdac5a40d09fcdaaacd56915a8c356f6
mesop
github_2023
google
typescript
AutocompleteComponent._filter
private _filter( value: string, options: readonly AutocompleteOptionSet[], ): readonly AutocompleteOptionSet[] { if (!value) { return options; } const filterValue = value.toLowerCase(); const filteredOptions = new Array<AutocompleteOptionSet>(); for (const option of options) { if (option.getOptionGroup()) { const filteredOptionGroup = new AutocompleteOptionGroup(); filteredOptionGroup.setLabel(option.getOptionGroup()?.getLabel()!); for (const subOption of option.getOptionGroup()?.getOptionsList()!) { if (subOption?.getLabel()?.toLowerCase().includes(filterValue)) { filteredOptionGroup.addOptions(subOption); } } if (filteredOptionGroup.getOptionsList().length > 0) { const optionSet = new AutocompleteOptionSet(); optionSet.setOptionGroup(filteredOptionGroup); filteredOptions.push(optionSet); } } else { if ( option.getOption()?.getLabel()?.toLowerCase().includes(filterValue) ) { filteredOptions.push(option); } } } return filteredOptions; }
/** * Filters the autocomplete options based on the current input. * * The filtering will perform a case-insensitive substring match against the * options labels. * * @param value Value of the input * @param options Autocomplete options * @returns */
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/components/autocomplete/autocomplete.ts#L150-L182
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
DateRangePickerComponent.onChangeDebounced
onChangeDebounced( event: MatDatepickerInputEvent< string | undefined, DateRange<string | undefined> >, ): void { if (this.dateRange.value.start && this.dateRange.value.end) { const userEvent = new UserEvent(); userEvent.setHandlerId(this.config().getOnChangeHandlerId()!); const dateRangeEvent = new DateRangePickerEvent(); dateRangeEvent.setStartDate( this.makeDateString(this.dateRange.value.start), ); dateRangeEvent.setEndDate(this.makeDateString(this.dateRange.value.end)); userEvent.setDateRangePickerEvent(dateRangeEvent); userEvent.setKey(this.key); this.channel.dispatch(userEvent); } }
// event if the end date is also set.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/components/date_range_picker/date_range_picker.ts#L112-L130
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
ComponentRenderer.getStyle
getStyle(): string { if (!this._boxType) { return ''; } let style = ''; if (this.component.getStyle()) { style += formatStyle(this.component.getStyle()!); } return style; }
//////////////
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/component_renderer/component_renderer.ts#L308-L319
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
setIframeSrcImpl
function setIframeSrcImpl(iframe: HTMLIFrameElement, src: string) { // This is a tightly controlled list of attributes that enables us to // secure sandbox iframes. Do not add additional attributes without // consulting a security resource. // // Ref: // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox iframe.sandbox.add( 'allow-same-origin', 'allow-scripts', 'allow-forms', 'allow-popups', 'allow-popups-to-escape-sandbox', 'allow-storage-access-by-user-activation', ); iframe.src = sanitizeJavaScriptUrl(src)!; }
// copybara:strip_begin(external-only)
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/safe_iframe/safe_iframe.ts#L18-L35
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
reportJavaScriptUrl
function reportJavaScriptUrl(url: string): boolean { const hasJavascriptUrlScheme = !IS_NOT_JAVASCRIPT_URL_PATTERN.test(url); if (hasJavascriptUrlScheme) { console.error(`A URL with content '${url}' was sanitized away.`); } return hasJavascriptUrlScheme; }
/** * Checks whether a urls has a `javascript:` scheme. * If the url has a `javascript:` scheme, reports it and returns true. * Otherwise, returns false. */
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/safe_iframe/sanitize_javascript_url.ts#L36-L42
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
Channel.isBusy
isBusy(): boolean { if (this.experimentService.websocketsEnabled) { // When WebSockets are enabled, we disable the busy indicator // because it's possible for the server to push new data // at any point. Apps should use their own loading indicators // instead. return false; } return this.isWaiting && !this.isHotReloading(); }
/** * Return true if the channel has been doing work * triggered by a user that's been taking a while. */
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/services/channel.ts#L93-L102
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
Shell.maybeExecuteScrollCommand
maybeExecuteScrollCommand() { if (this.commandScrollKey) { const scrollKey = this.commandScrollKey; this.commandScrollKey = ''; const targetElements = document.querySelectorAll( `[data-key="${scrollKey}"]`, ); if (!targetElements.length) { console.error( `Could not scroll to component with key ${scrollKey} because no component found`, ); return; } if (targetElements.length > 1) { console.warn( 'Found multiple components', targetElements, 'to potentially scroll to for key', scrollKey, '. This is probably a bug and you should use a unique key identifier.', ); } targetElements[0].parentElement!.scrollIntoView({ behavior: 'smooth', }); } }
// Executes the scroll command if a key has been specified.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/shell/shell.ts#L246-L272
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
updateValue
function updateValue(root: object, path: (string | number)[], value: any) { let objectSegment = root; for (let i = 0; i < path.length; ++i) { if (i + 1 === path.length) { // @ts-ignore: Ignore type objectSegment[path[i]] = value; } else { // @ts-ignore: Ignore type objectSegment = objectSegment[path[i]]; } } }
// Updates value at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L141-L152
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
addArrayValue
function addArrayValue(root: object, path: (string | number)[], value: any) { const objectSegment = getLastObjectSegment(root, path); if (objectSegment) { // @ts-ignore: Ignore type objectSegment.splice(path[path.length - 1], 0, value); } }
// Adds item to the array at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L155-L161
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
removeArrayValue
function removeArrayValue(root: object, path: (string | number)[]) { let objectSegment = root; for (let i = 0; i < path.length; ++i) { if (i + 1 === path.length) { // @ts-ignore: Ignore type objectSegment.splice(path[i], 1); } else { // @ts-ignore: Ignore type objectSegment = objectSegment[path[i]]; } } }
// Removes item from array at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L164-L175
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
addSetValue
function addSetValue(root: object, path: (string | number)[], value: any) { const objectSegment = getLastObjectSegment(root, path); if (objectSegment) { // @ts-ignore: Ignore type objectSegment[path[path.length - 1]].push(value); } }
// Adds item from the set at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L178-L184
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
removeSetValue
function removeSetValue(root: object, path: (string | number)[], value: any) { const objectSegment = getLastObjectSegment(root, path); if (objectSegment) { // @ts-ignore: Ignore type const set = new Set(objectSegment[path[path.length - 1]]); set.delete(value); // @ts-ignore: Ignore type objectSegment[path[path.length - 1]] = [...set]; } }
// Removes item from the set at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L187-L196
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
updateObjectValue
function updateObjectValue( root: object, path: (string | number)[], value: any, ) { let objectSegment = root; for (let i = 0; i < path.length; ++i) { if (i + 1 === path.length) { // @ts-ignore: Ignore type objectSegment[path[i]] = value; } else { // @ts-ignore: Ignore type objectSegment = objectSegment[path[i]]; } } }
// Adds/Updates value to object at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L199-L214
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
removeObjectValue
function removeObjectValue(root: object, path: (string | number)[]) { let objectSegment = root; for (let i = 0; i < path.length; ++i) { if (i + 1 === path.length) { // @ts-ignore: Ignore type delete objectSegment[path[i]]; } else { // @ts-ignore: Ignore type objectSegment = objectSegment[path[i]]; } } }
// Removes value from object at path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L217-L228
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
getLastObjectSegment
function getLastObjectSegment( root: object, path: (string | number)[], ): object | null { let objectSegment = root; for (let i = 0; i < path.length; ++i) { if (i + 1 === path.length) { return objectSegment; } // Edge case where the array does not exist yet, so we need to create an array // before we can append. // // @ts-ignore: Ignore type if (objectSegment[path[i]] === undefined && i + 2 === path.length) { // @ts-ignore: Ignore type objectSegment[path[i]] = []; } // @ts-ignore: Ignore type objectSegment = objectSegment[path[i]]; } return null; }
// Helper function for retrieving the last segment from a given path.
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/mesop/web/src/utils/diff.ts#L231-L252
270a3fa90c31cebefc2202b65ea91194d5bf255e
mesop
github_2023
google
typescript
processBuildAction
async function processBuildAction(args: string[]) { const {loadPath, style, sourceMap, embedSources, inputExecpath, outExecpath} = await yargs(args) .showHelpOnFail(false) .strict() .parserConfiguration({'greedy-arrays': false}) .command('$0 <inputExecpath> <outExecpath>', 'Compiles a Sass file') .positional('inputExecpath', {type: 'string', demandOption: true}) .positional('outExecpath', {type: 'string', demandOption: true}) .option('embedSources', {type: 'boolean'}) .option('errorCss', {type: 'boolean'}) .option('sourceMap', {type: 'boolean'}) .option('loadPath', {type: 'array', string: true}) .option('style', {type: 'string'}) .parseAsync(); const result = sass.compile(inputExecpath, { style: style, // TODO: Re-add: as sass.OutputStyle, sourceMap, sourceMapIncludeSources: embedSources, loadPaths: loadPath, importers: [localPackageSassImporter], }); await fs.promises.writeFile(outExecpath, result.css); }
/** * Processes a build action expressed through command line arguments * as composed by the `sass_binary` rule. */
https://github.com/google/mesop/blob/270a3fa90c31cebefc2202b65ea91194d5bf255e/tools/sass/compiler-main.ts#L53-L78
270a3fa90c31cebefc2202b65ea91194d5bf255e
UptimeFlare
github_2023
lyc8503
typescript
formatAndNotify
let formatAndNotify = async ( monitor: any, isUp: boolean, timeIncidentStart: number, timeNow: number, reason: string ) => { if (workerConfig.notification?.appriseApiServer && workerConfig.notification?.recipientUrl) { const notification = formatStatusChangeNotification( monitor, isUp, timeIncidentStart, timeNow, reason, workerConfig.notification?.timeZone ?? 'Etc/GMT' ) await notifyWithApprise( workerConfig.notification.appriseApiServer, workerConfig.notification.recipientUrl, notification.title, notification.body ) } else { console.log(`Apprise API server or recipient URL not set, skipping apprise notification for ${monitor.name}`) } }
// Auxiliary function to format notification and send it via apprise
https://github.com/lyc8503/UptimeFlare/blob/07618a56386ae146ee218ccf69fb3f9152bb42bb/worker/src/index.ts#L46-L71
07618a56386ae146ee218ccf69fb3f9152bb42bb
shipfast
github_2023
vietanhdev
typescript
ApplicationMultipleTargetGroupsFargateService.constructor
constructor( scope: Construct, id: string, props: ApplicationMultipleTargetGroupsFargateServiceProps ) { super(scope, id, props); this.logGroups = []; this.assignPublicIp = props.assignPublicIp ?? false; if (props.taskDefinition && props.taskImageOptions) { throw new Error( 'You must specify only one of TaskDefinition or TaskImageOptions.' ); } else if (props.taskDefinition) { this.taskDefinition = props.taskDefinition; } else if (props.taskImageOptions) { const taskImageOptions = props.taskImageOptions; this.taskDefinition = new FargateTaskDefinition(this, 'TaskDef', { memoryLimitMiB: props.memoryLimitMiB, cpu: props.cpu, executionRole: props.executionRole, taskRole: props.taskRole, family: props.family, }); for (const taskImageOptionsProps of taskImageOptions) { const containerName = taskImageOptionsProps.containerName ?? 'web'; const container = this.taskDefinition.addContainer(containerName, { image: taskImageOptionsProps.image, logging: taskImageOptionsProps.enableLogging === false ? undefined : taskImageOptionsProps.logDriver || this.createAWSLogDriver(`${this.node.id}-${containerName}`), environment: taskImageOptionsProps.environment, secrets: taskImageOptionsProps.secrets, dockerLabels: taskImageOptionsProps.dockerLabels, command: taskImageOptionsProps.command, }); if (taskImageOptionsProps.containerPorts) { for (const containerPort of taskImageOptionsProps.containerPorts) { container.addPortMappings({ containerPort, }); } } } } else { throw new Error('You must specify one of: taskDefinition or image'); } if (!this.taskDefinition.defaultContainer) { throw new Error('At least one essential container must be specified'); } if (this.taskDefinition.defaultContainer.portMappings.length === 0) { this.taskDefinition.defaultContainer.addPortMappings({ containerPort: 80, }); } this.service = this.createFargateService(props); if (props.targetGroups) { this.addPortMappingForTargets( this.taskDefinition.defaultContainer, props.targetGroups ); this.targetGroup = this.registerECSTargets( this.service, this.taskDefinition.defaultContainer, props.targetGroups ); } }
/** * Constructs a new instance of the ApplicationMultipleTargetGroupsFargateService class. */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/infra/infra-core/src/lib/patterns/applicationMultipleTargetGroupsFargateService.ts#L149-L221
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
customRender
function customRender< Q extends Queries = typeof queries, Container extends Element | DocumentFragment = HTMLElement, BaseElement extends Element | DocumentFragment = Container >( ui: ReactElement, options: CustomRenderOptions<Q, Container, BaseElement> = {} ): RenderResult<Q, Container, BaseElement> & { waitForApolloMocks: WaitForApolloMocks } { const { wrapper, waitForApolloMocks } = getWrapper(ApiTestProviders, options); return { ...render(ui, { ...options, wrapper, }), waitForApolloMocks, }; }
/** * Method that extends [`render`](https://testing-library.com/docs/react-testing-library/api#render) method from * `@testing-library/react` package. It composes a wrapper using [`ApiTestProviders`](#apitestprovidersprops) component * and `options` property that is passed down to parent `render` method. It also extends returned result with the * [`waitForApolloMocks`](#waitforapollomocks) method. * @param ui * @param options */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp-libs/webapp-api-client/src/tests/utils/rendering.tsx#L114-L131
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
customRenderHook
function customRenderHook<Result, Props>(hook: (initialProps: Props) => Result, options: CustomRenderOptions = {}) { const { wrapper, waitForApolloMocks } = getWrapper(ApiTestProviders, options); return { ...renderHook(hook, { ...options, wrapper, }), waitForApolloMocks, }; }
/** * Method that extends [`renderHook`](https://testing-library.com/docs/react-testing-library/api#renderhook) method from * `@testing-library/react` package. It composes a wrapper using [`ApiTestProviders`](#apitestprovidersprops) component * and `options` property that is passed down to parent `renderHook` method. It also extends returned result with the * [`waitForApolloMocks`](#waitforapollomocks) method. * @param hook * @param options */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp-libs/webapp-api-client/src/tests/utils/rendering.tsx#L141-L151
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
customRender
function customRender< Q extends Queries = typeof queries, Container extends Element | DocumentFragment = HTMLElement, BaseElement extends Element | DocumentFragment = Container >( ui: ReactElement, options: CustomRenderOptions<Q, Container, BaseElement> = {} ): RenderResult<Q, Container, BaseElement> { const { wrapper } = getWrapper(CoreTestProviders, options); return { ...render<Q, Container, BaseElement>(ui, { ...options, wrapper, }), }; }
/** * Method that extends [`render`](https://testing-library.com/docs/react-testing-library/api#render) method from * `@testing-library/react` package. It composes a wrapper using [`CoreTestProviders`](#coretestproviders) component and * `options` property that is passed down to parent `render` method. * @param ui * @param options */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp-libs/webapp-core/src/tests/utils/rendering.tsx#L95-L111
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
customRenderHook
function customRenderHook<Result, Props>(hook: (initialProps: Props) => Result, options: CustomRenderOptions = {}) { const { wrapper } = getWrapper(CoreTestProviders, options); return { ...renderHook(hook, { ...options, wrapper, }), }; }
/** * Method that extends [`renderHook`](https://testing-library.com/docs/react-testing-library/api#renderhook) method from * `@testing-library/react` package. It composes a wrapper using [`CoreTestProviders`](#coretestproviders) component and * `options` property that is passed down to parent `renderHook` method. * @param hook * @param options */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp-libs/webapp-core/src/tests/utils/rendering.tsx#L120-L129
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
updateOrCreatePaymentIntent
const updateOrCreatePaymentIntent = async ( product: TestProduct ): Promise<{ errors?: readonly GraphQLError[]; paymentIntent?: StripePaymentIntentType | null }> => { if (!paymentIntent) { const { data, errors } = await commitCreatePaymentIntentMutation({ variables: { input: { product, }, }, }); if (errors) { return { errors }; } setPaymentIntent(data?.createPaymentIntent?.paymentIntent); return { paymentIntent: data?.createPaymentIntent?.paymentIntent }; } const { data, errors } = await commitUpdatePaymentIntentMutation({ variables: { input: { product, id: paymentIntent.id, }, }, }); if (errors) { return { errors }; } return { paymentIntent: data?.updatePaymentIntent?.paymentIntent }; };
/** * This function is responsible for creating a new payment intent and updating it if it has been created before. * * @param product This product will be passed to the payment intent create and update API endpoints. Backend should * handle amount and currency update based on the ID of this product. */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp-libs/webapp-finances/src/components/stripe/stripePayment.hooks.ts#L95-L127
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
customRender
function customRender(ui: ReactElement, options: CustomRenderOptions = {}) { const { wrapper, waitForApolloMocks } = getWrapper(apiUtils.ApiTestProviders, options); return { ...render(ui, { ...options, wrapper, }), waitForApolloMocks, }; }
/** * Method that extends [`render`](https://testing-library.com/docs/react-testing-library/api#render) method from * `@testing-library/react` package. It composes a wrapper using `ApiTestProviders` component from * `@shipfast/webapp-api-client/tests/utils/rendering` package and `options` property that is passed down to parent * `render` method. It also extends returned result with the * [`waitForApolloMocks`](../../../webapp-api-client/generated/modules/tests_utils_rendering#waitforapollomocks) method. * * @example * Example usage (reset CommonQuery): * ```tsx showLineNumbers * it('should render ', async () => { * const apolloMocks = [ * fillCommonQueryWithUser( * currentUserFactory({ * roles: [Role.ADMIN], * }) * ) * ]; * const { waitForApolloMocks } = render(<Component />, { * apolloMocks, * }); * * await waitForApolloMocks(); * * expect(screen.getByText('Rendered')).toBeInTheDocument(); * }); * ``` * * @example * Example usage (append query to default set): * ```tsx showLineNumbers * it('should render ', async () => { * const requestMock = composeMockedQueryResult(...); * const { waitForApolloMocks } = render(<Component />, { * apolloMocks: append(requestMock), * }); * * await waitForApolloMocks(); * * expect(screen.getByText('Rendered')).toBeInTheDocument(); * }); * ``` * * @param ui * @param options */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp/src/tests/utils/rendering.tsx#L70-L80
49707acf1cf69a561f35ade112a1376a29c57e8a
shipfast
github_2023
vietanhdev
typescript
customRenderHook
function customRenderHook<Result, Props>(hook: (initialProps: Props) => Result, options: CustomRenderOptions = {}) { const { wrapper, waitForApolloMocks } = getWrapper(apiUtils.ApiTestProviders, options); return { ...renderHook(hook, { ...options, wrapper, }), waitForApolloMocks, }; }
/** * Method that extends [`renderHook`](https://testing-library.com/docs/react-testing-library/api#renderhook) method from * `@testing-library/react` package. It composes a wrapper using `ApiTestProviders` component from * `@shipfast/webapp-api-client/tests/utils/rendering` package and `options` property that is passed down to parent * `renderHook` method. It also extends returned result with the * [`waitForApolloMocks`](../../../webapp-api-client/generated/modules/tests_utils_rendering#waitforapollomocks) method. * * @param hook * @param options */
https://github.com/vietanhdev/shipfast/blob/49707acf1cf69a561f35ade112a1376a29c57e8a/packages/webapp/src/tests/utils/rendering.tsx#L92-L102
49707acf1cf69a561f35ade112a1376a29c57e8a
MiniSearch
github_2023
felladrin
typescript
cacheSearchWithIndexedDB
function cacheSearchWithIndexedDB< T extends ImageSearchResults | TextSearchResults, >( fn: (query: string, limit?: number) => Promise<T>, storeName: string, ): (query: string, limit?: number) => Promise<T> { const databaseVersion = 2; const timeToLive = 15 * 60 * 1000; async function openDB(): Promise<IDBDatabase> { return new Promise((resolve, reject) => { let request = indexedDB.open(name, databaseVersion); request.onerror = () => reject(request.error); request.onsuccess = () => { const db = request.result; if ( !db.objectStoreNames.contains("textSearches") || !db.objectStoreNames.contains("imageSearches") ) { db.close(); request = indexedDB.open(name, databaseVersion); request.onupgradeneeded = createStores; request.onsuccess = () => { const upgradedDb = request.result; cleanExpiredCache(upgradedDb); resolve(upgradedDb); }; request.onerror = () => reject(request.error); } else { cleanExpiredCache(db); resolve(db); } }; request.onupgradeneeded = createStores; }); } function createStores(event: IDBVersionChangeEvent): void { const db = (event.target as IDBOpenDBRequest).result; if (!db.objectStoreNames.contains("textSearches")) { db.createObjectStore("textSearches"); } if (!db.objectStoreNames.contains("imageSearches")) { db.createObjectStore("imageSearches"); } } async function cleanExpiredCache(db: IDBDatabase): Promise<void> { const transaction = db.transaction(storeName, "readwrite"); const store = transaction.objectStore(storeName); const currentTime = Date.now(); return new Promise((resolve) => { const request = store.openCursor(); request.onsuccess = (event) => { const cursor = (event.target as IDBRequest).result; if (cursor) { if (currentTime - cursor.value.timestamp >= timeToLive) { cursor.delete(); } cursor.continue(); } else { resolve(); } }; }); } /** * Generates a hash for a given query string. * * This function implements a simple hash algorithm: * 1. It iterates through each character in the query string. * 2. For each character, it updates the hash value using bitwise operations. * 3. The final hash is converted to a 32-bit integer. * 4. The result is returned as a base-36 string representation. * * @param query - The input string to be hashed. * @returns A string representation of the hash in base-36. */ function hashQuery(query: string): string { return query .split("") .reduce((acc, char) => ((acc << 5) - acc + char.charCodeAt(0)) | 0, 0) .toString(36); } const dbPromise = openDB(); return async (query: string, limit?: number): Promise<T> => { if (!indexedDB) return fn(query, limit); const db = await dbPromise; const transaction = db.transaction(storeName, "readwrite"); const store = transaction.objectStore(storeName); const key = hashQuery(query); const cachedResult = await new Promise< | { results: T; timestamp: number; } | undefined >((resolve) => { const request = store.get(key); request.onerror = () => resolve(undefined); request.onsuccess = () => resolve(request.result); }); if (cachedResult && Date.now() - cachedResult.timestamp < timeToLive) { addLogEntry( `Search cache hit, returning cached results containing ${cachedResult.results.length} items`, ); if (storeName === "textSearches") { updateTextSearchResults(cachedResult.results as TextSearchResults); updateTextSearchState("completed"); } else if (storeName === "imageSearches") { updateImageSearchResults(cachedResult.results as ImageSearchResults); updateImageSearchState("completed"); } return cachedResult.results; } addLogEntry("Search cache miss, fetching new results"); const results = await fn(query, limit); const writeTransaction = db.transaction(storeName, "readwrite"); const writeStore = writeTransaction.objectStore(storeName); writeStore.put({ results, timestamp: Date.now() }, key); addLogEntry(`Search completed with ${results.length} items`); return results; }; }
/** * Creates a cached version of a search function using IndexedDB for storage. * * @param fn - The original search function to be cached. * @returns A new function that wraps the original, adding caching functionality. * * This function implements a caching mechanism for search results using IndexedDB. * It stores search results with a 15-minute time-to-live (TTL) to improve performance * for repeated searches. The cache is automatically cleaned of expired entries. * * The returned function behaves as follows: * 1. Checks IndexedDB for a cached result matching the query. * 2. If a valid (non-expired) cached result exists, it is returned immediately. * 3. Otherwise, the original search function is called, and its result is both * returned and stored in the cache for future use. * * If IndexedDB is not available, the function falls back to using the original * search function without caching. */
https://github.com/felladrin/MiniSearch/blob/f757e0f61eef7d663bc5a77a27ef170aa9a97295/client/modules/search.ts#L31-L168
f757e0f61eef7d663bc5a77a27ef170aa9a97295
MiniSearch
github_2023
felladrin
typescript
hashQuery
function hashQuery(query: string): string { return query .split("") .reduce((acc, char) => ((acc << 5) - acc + char.charCodeAt(0)) | 0, 0) .toString(36); }
/** * Generates a hash for a given query string. * * This function implements a simple hash algorithm: * 1. It iterates through each character in the query string. * 2. For each character, it updates the hash value using bitwise operations. * 3. The final hash is converted to a 32-bit integer. * 4. The result is returned as a base-36 string representation. * * @param query - The input string to be hashed. * @returns A string representation of the hash in base-36. */
https://github.com/felladrin/MiniSearch/blob/f757e0f61eef7d663bc5a77a27ef170aa9a97295/client/modules/search.ts#L114-L119
f757e0f61eef7d663bc5a77a27ef170aa9a97295
MiniSearch
github_2023
felladrin
typescript
streamTextInChunks
function streamTextInChunks( text: string, updateCallback: (text: string) => void, chunkSize = 3, delayMs = 60, ): void { const words = text.split(" "); let accumulatedText = ""; let i = 0; const intervalId = setInterval(() => { const chunk = words.slice(i, i + chunkSize).join(" "); accumulatedText += `${chunk} `; updateCallback(accumulatedText.trim()); i += chunkSize; if (i >= words.length) { clearInterval(intervalId); } }, delayMs); }
/** * Streams text in small chunks with a delay between each chunk for a smooth reading experience. * @param text The text to stream * @param updateCallback Function to call with each chunk of text * @param chunkSize Number of words per chunk (default: 3) * @param delayMs Delay between chunks in milliseconds (default: 50) */
https://github.com/felladrin/MiniSearch/blob/f757e0f61eef7d663bc5a77a27ef170aa9a97295/client/modules/textGenerationWithHorde.ts#L228-L247
f757e0f61eef7d663bc5a77a27ef170aa9a97295
soybean-admin-antd
github_2023
soybeanjs
typescript
getHue
function getHue(hsv: HsvColor, i: number, isLight: boolean) { let hue: number; const hsvH = Math.round(hsv.h); if (hsvH >= 60 && hsvH <= 240) { hue = isLight ? hsvH - hueStep * i : hsvH + hueStep * i; } else { hue = isLight ? hsvH + hueStep * i : hsvH - hueStep * i; } if (hue < 0) { hue += 360; } if (hue >= 360) { hue -= 360; } return hue; }
/** * Get hue * * @param hsv - Hsv format color * @param i - The relative distance from 6 * @param isLight - Is light color */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/color/src/palette/antd.ts#L96-L116
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getSaturation
function getSaturation(hsv: HsvColor, i: number, isLight: boolean) { if (hsv.h === 0 && hsv.s === 0) { return hsv.s; } let saturation: number; if (isLight) { saturation = hsv.s - saturationStep * i; } else if (i === darkColorCount) { saturation = hsv.s + saturationStep; } else { saturation = hsv.s + saturationStep2 * i; } if (saturation > 100) { saturation = 100; } if (isLight && i === lightColorCount && saturation > 10) { saturation = 10; } if (saturation < 6) { saturation = 6; } return saturation; }
/** * Get saturation * * @param hsv - Hsv format color * @param i - The relative distance from 6 * @param isLight - Is light color */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/color/src/palette/antd.ts#L125-L153
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getValue
function getValue(hsv: HsvColor, i: number, isLight: boolean) { let value: number; if (isLight) { value = hsv.v + brightnessStep1 * i; } else { value = hsv.v - brightnessStep2 * i; } if (value > 100) { value = 100; } return value; }
/** * Get value of hsv * * @param hsv - Hsv format color * @param i - The relative distance from 6 * @param isLight - Is light color */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/color/src/palette/antd.ts#L162-L176
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getNearestColorPaletteFamily
function getNearestColorPaletteFamily(color: string, families: ColorPaletteFamily[]) { const familyWithConfig = families.map(family => { const palettes = family.palettes.map(palette => { return { ...palette, delta: getDeltaE(color, palette.hex) }; }); const nearestPalette = palettes.reduce((prev, curr) => (prev.delta < curr.delta ? prev : curr)); return { ...family, palettes, nearestPalette }; }); const nearestPaletteFamily = familyWithConfig.reduce((prev, curr) => prev.nearestPalette.delta < curr.nearestPalette.delta ? prev : curr ); const { l } = getHsl(color); const paletteFamily: ColorPaletteFamilyWithNearestPalette = { ...nearestPaletteFamily, nearestLightnessPalette: nearestPaletteFamily.palettes.reduce((prev, curr) => { const { l: prevLightness } = getHsl(prev.hex); const { l: currLightness } = getHsl(curr.hex); const deltaPrev = Math.abs(prevLightness - l); const deltaCurr = Math.abs(currLightness - l); return deltaPrev < deltaCurr ? prev : curr; }) }; return paletteFamily; }
/** * get nearest color palette family * * @param color color * @param families color palette families */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/color/src/palette/recommend.ts#L114-L152
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
createContext
function createContext<T>(contextName: string) { const injectKey: InjectionKey<T> = Symbol(contextName); function useProvide(context: T) { provide(injectKey, context); return context; } function useInject() { return inject(injectKey) as T; } return { useProvide, useInject }; }
/** Create context */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/hooks/src/use-context.ts#L79-L96
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
SvgIconVNode
const SvgIconVNode = (config: IconConfig) => { const { color, fontSize, icon, localIcon } = config; const style: IconStyle = {}; if (color) { style.color = color; } if (fontSize) { style.fontSize = `${fontSize}px`; } if (!icon && !localIcon) { return undefined; } return () => h(SvgIcon, { icon, localIcon, style }); };
/** * Svg icon VNode * * @param config */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/hooks/src/use-svg-icon-render.ts#L28-L45
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
updateSearchParams
function updateSearchParams(params: Partial<Parameters<A>[0]>) { Object.assign(searchParams, params); }
/** * update search params * * @param params */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/hooks/src/use-table.ts#L127-L129
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
resetSearchParams
function resetSearchParams() { Object.assign(searchParams, jsonClone(apiParams)); }
/** reset search params */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/hooks/src/use-table.ts#L132-L134
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
createLayoutCssVarsByCssVarsProps
function createLayoutCssVarsByCssVarsProps(props: LayoutCssVarsProps) { const cssVars: LayoutCssVars = { '--soy-header-height': `${props.headerHeight}px`, '--soy-header-z-index': props.headerZIndex, '--soy-tab-height': `${props.tabHeight}px`, '--soy-tab-z-index': props.tabZIndex, '--soy-sider-width': `${props.siderWidth}px`, '--soy-sider-collapsed-width': `${props.siderCollapsedWidth}px`, '--soy-sider-z-index': props.siderZIndex, '--soy-mobile-sider-z-index': props.mobileSiderZIndex, '--soy-footer-height': `${props.footerHeight}px`, '--soy-footer-z-index': props.footerZIndex }; return cssVars; }
/** * Create layout css vars by css vars props * * @param props Css vars props */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/materials/src/libs/admin-layout/shared.ts#L14-L29
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getHue
function getHue(hsv: HsvColor, i: number, isLight: boolean) { let hue: number; const hsvH = Math.round(hsv.h); if (hsvH >= 60 && hsvH <= 240) { hue = isLight ? hsvH - hueStep * i : hsvH + hueStep * i; } else { hue = isLight ? hsvH + hueStep * i : hsvH - hueStep * i; } if (hue < 0) { hue += 360; } if (hue >= 360) { hue -= 360; } return hue; }
/** * Get hue * * @param hsv - Hsv format color * @param i - The relative distance from 6 * @param isLight - Is light color */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/utils/src/color.ts#L172-L192
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getSaturation
function getSaturation(hsv: HsvColor, i: number, isLight: boolean) { if (hsv.h === 0 && hsv.s === 0) { return hsv.s; } let saturation: number; if (isLight) { saturation = hsv.s - saturationStep * i; } else if (i === darkColorCount) { saturation = hsv.s + saturationStep; } else { saturation = hsv.s + saturationStep2 * i; } if (saturation > 100) { saturation = 100; } if (isLight && i === lightColorCount && saturation > 10) { saturation = 10; } if (saturation < 6) { saturation = 6; } return saturation; }
/** * Get saturation * * @param hsv - Hsv format color * @param i - The relative distance from 6 * @param isLight - Is light color */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/utils/src/color.ts#L201-L229
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getValue
function getValue(hsv: HsvColor, i: number, isLight: boolean) { let value: number; if (isLight) { value = hsv.v + brightnessStep1 * i; } else { value = hsv.v - brightnessStep2 * i; } if (value > 100) { value = 100; } return value; }
/** * Get value of hsv * * @param hsv - Hsv format color * @param i - The relative distance from 6 * @param isLight - Is light color */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/packages/utils/src/color.ts#L238-L252
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
canRender
function canRender() { return domRef.value && initialSize.width > 0 && initialSize.height > 0; }
/** * whether can render chart * * when domRef is ready and initialSize is valid */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L119-L121
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
isRendered
function isRendered() { return Boolean(domRef.value && chart); }
/** is chart rendered */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L124-L126
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
updateOptions
async function updateOptions(callback: (opts: T, optsFactory: () => T) => ECOption = () => chartOptions) { if (!isRendered()) return; const updatedOpts = callback(chartOptions, optionsFactory); Object.assign(chartOptions, updatedOpts); if (isRendered()) { chart?.clear(); } chart?.setOption({ ...updatedOpts, backgroundColor: 'transparent' }); await onUpdated?.(chart!); }
/** * update chart options * * @param callback callback function */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L133-L147
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
render
async function render() { if (!isRendered()) { const chartTheme = darkMode.value ? 'dark' : 'light'; await nextTick(); chart = echarts.init(domRef.value, chartTheme); chart.setOption({ ...chartOptions, backgroundColor: 'transparent' }); await onRender?.(chart); } }
/** render chart */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L154-L166
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
resize
function resize() { chart?.resize(); }
/** resize chart */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L169-L171
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
destroy
async function destroy() { if (!chart) return; await onDestroy?.(chart); chart?.dispose(); chart = null; }
/** destroy chart */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L174-L180
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
changeTheme
async function changeTheme() { await destroy(); await render(); await onUpdated?.(chart!); }
/** change chart theme */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L183-L187
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
renderChartBySize
async function renderChartBySize(w: number, h: number) { initialSize.width = w; initialSize.height = h; // size is abnormal, destroy chart if (!canRender()) { await destroy(); return; } // resize chart if (isRendered()) { resize(); } // render chart await render(); }
/** * render chart by size * * @param w width * @param h height */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/echarts.ts#L195-L213
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
createConfirmPwdRule
function createConfirmPwdRule(pwd: string | Ref<string> | ComputedRef<string>) { const confirmPwdRule: App.Global.FormRule[] = [ { required: true, message: $t('form.confirmPwd.required') }, { validator: (rule, value) => { if (value.trim() !== '' && value !== toValue(pwd)) { return Promise.reject(rule.message); } return Promise.resolve(); }, message: $t('form.confirmPwd.invalid'), trigger: 'change' } ]; return confirmPwdRule; }
/** create a rule for confirming the password */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/form.ts#L55-L70
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
toLogin
async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) { const module = loginModule || 'pwd-login'; const options: RouterPushOptions = { params: { module } }; const redirect = redirectUrl || route.value.fullPath; options.query = { redirect }; return routerPushByKey('login', options); }
/** * Navigate to login page * * @param loginModule The login module * @param redirectUrl The redirect url, if not specified, it will be the current route fullPath */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/router.ts#L67-L83
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
toggleLoginModule
async function toggleLoginModule(module: UnionKey.LoginModule) { const query = route.value.query as Record<string, string>; return routerPushByKey('login', { query, params: { module } }); }
/** * Toggle login module * * @param module */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/router.ts#L90-L94
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
redirectFromLogin
async function redirectFromLogin(needRedirect = true) { const redirect = route.value.query?.redirect as string; if (needRedirect && redirect) { await routerPush(redirect); } else { await toHome(); } }
/** * Redirect from login * * @param [needRedirect=true] Whether to redirect after login. Default is `true` */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/router.ts#L101-L109
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getDataByPage
async function getDataByPage(pageNum: number = 1) { updatePagination({ current: pageNum }); updateSearchParams({ current: pageNum, size: pagination.pageSize! }); await getData(); }
/** * get data by page number * * @param pageNum the page number. default is 1 */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/table.ts#L135-L146
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
onBatchDeleted
async function onBatchDeleted() { window.$message?.success($t('common.deleteSuccess')); checkedRowKeys.value = []; await getData(); }
/** the hook after the batch delete operation is completed */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/table.ts#L217-L223
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
onDeleted
async function onDeleted() { window.$message?.success($t('common.deleteSuccess')); await getData(); }
/** the hook after the delete operation is completed */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/hooks/common/table.ts#L226-L230
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
transformElegantRouteToVueRoute
function transformElegantRouteToVueRoute( route: ElegantConstRoute, layouts: Record<string, RouteComponent | (() => Promise<RouteComponent>)>, views: Record<string, RouteComponent | (() => Promise<RouteComponent>)> ) { const LAYOUT_PREFIX = 'layout.'; const VIEW_PREFIX = 'view.'; const ROUTE_DEGREE_SPLITTER = '_'; const FIRST_LEVEL_ROUTE_COMPONENT_SPLIT = '$'; function isLayout(component: string) { return component.startsWith(LAYOUT_PREFIX); } function getLayoutName(component: string) { const layout = component.replace(LAYOUT_PREFIX, ''); if(!layouts[layout]) { throw new Error(`Layout component "${layout}" not found`); } return layout; } function isView(component: string) { return component.startsWith(VIEW_PREFIX); } function getViewName(component: string) { const view = component.replace(VIEW_PREFIX, ''); if(!views[view]) { throw new Error(`View component "${view}" not found`); } return view; } function isFirstLevelRoute(item: ElegantConstRoute) { return !item.name.includes(ROUTE_DEGREE_SPLITTER); } function isSingleLevelRoute(item: ElegantConstRoute) { return isFirstLevelRoute(item) && !item.children?.length; } function getSingleLevelRouteComponent(component: string) { const [layout, view] = component.split(FIRST_LEVEL_ROUTE_COMPONENT_SPLIT); return { layout: getLayoutName(layout), view: getViewName(view) }; } const vueRoutes: RouteRecordRaw[] = []; // add props: true to route if (route.path.includes(':') && !route.props) { route.props = true; } const { name, path, component, children, ...rest } = route; const vueRoute = { name, path, ...rest } as RouteRecordRaw; try { if (component) { if (isSingleLevelRoute(route)) { const { layout, view } = getSingleLevelRouteComponent(component); const singleLevelRoute: RouteRecordRaw = { path, component: layouts[layout], meta: { title: route.meta?.title || '' }, children: [ { name, path: '', component: views[view], ...rest } as RouteRecordRaw ] }; return [singleLevelRoute]; } if (isLayout(component)) { const layoutName = getLayoutName(component); vueRoute.component = layouts[layoutName]; } if (isView(component)) { const viewName = getViewName(component); vueRoute.component = views[viewName]; } } } catch (error: any) { console.error(`Error transforming route "${route.name}": ${error.toString()}`); return []; } // add redirect to child if (children?.length && !vueRoute.redirect) { vueRoute.redirect = { name: children[0].name }; } if (children?.length) { const childRoutes = children.flatMap(child => transformElegantRouteToVueRoute(child, layouts, views)); if(isFirstLevelRoute(route)) { vueRoute.children = childRoutes; } else { vueRoutes.push(...childRoutes); } } vueRoutes.unshift(vueRoute); return vueRoutes; }
/** * transform elegant route to vue route * @param route elegant const route * @param layouts layout components * @param views view components */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/router/elegant/transform.ts#L30-L158
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
initRoute
async function initRoute(to: RouteLocationNormalized): Promise<RouteLocationRaw | null> { const routeStore = useRouteStore(); const notFoundRoute: RouteKey = 'not-found'; const isNotFoundRoute = to.name === notFoundRoute; // if the constant route is not initialized, then initialize the constant route if (!routeStore.isInitConstantRoute) { await routeStore.initConstantRoute(); // the route is captured by the "not-found" route because the constant route is not initialized // after the constant route is initialized, redirect to the original route const path = to.fullPath; const location: RouteLocationRaw = { path, replace: true, query: to.query, hash: to.hash }; return location; } const isLogin = Boolean(localStg.get('token')); if (!isLogin) { // if the user is not logged in and the route is a constant route but not the "not-found" route, then it is allowed to access. if (to.meta.constant && !isNotFoundRoute) { routeStore.onRouteSwitchWhenNotLoggedIn(); return null; } // if the user is not logged in, then switch to the login page const loginRoute: RouteKey = 'login'; const query = getRouteQueryOfLoginRoute(to, routeStore.routeHome); const location: RouteLocationRaw = { name: loginRoute, query }; return location; } if (!routeStore.isInitAuthRoute) { // initialize the auth route await routeStore.initAuthRoute(); // the route is captured by the "not-found" route because the auth route is not initialized // after the auth route is initialized, redirect to the original route if (isNotFoundRoute) { const rootRoute: RouteKey = 'root'; const path = to.redirectedFrom?.name === rootRoute ? '/' : to.fullPath; const location: RouteLocationRaw = { path, replace: true, query: to.query, hash: to.hash }; return location; } } routeStore.onRouteSwitchWhenLoggedIn(); // the auth route is initialized // it is not the "not-found" route, then it is allowed to access if (!isNotFoundRoute) { return null; } // it is captured by the "not-found" route, then check whether the route exists const exist = await routeStore.getIsAuthRouteExist(to.path as RoutePath); const noPermissionRoute: RouteKey = '403'; if (exist) { const location: RouteLocationRaw = { name: noPermissionRoute }; return location; } return null; }
/** * initialize route * * @param to to route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/router/guard/route.ts#L75-L162
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
handleRefreshToken
async function handleRefreshToken() { const { resetStore } = useAuthStore(); const rToken = localStg.get('refreshToken') || ''; const { error, data } = await fetchRefreshToken(rToken); if (!error) { localStg.set('token', data.token); localStg.set('refreshToken', data.refreshToken); return true; } resetStore(); return false; }
/** refresh token */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/service/request/shared.ts#L14-L28
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
reloadPage
async function reloadPage(duration = 300) { setReloadFlag(false); const d = themeStore.page.animate ? duration : 40; await new Promise(resolve => { setTimeout(resolve, d); }); setReloadFlag(true); if (themeStore.resetCacheStrategy === 'refresh') { routeStore.resetRouteCache(); } }
/** * Reload page * * @param duration Duration time */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/app/index.ts#L39-L53
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
updateDocumentTitleByLocale
function updateDocumentTitleByLocale() { const { i18nKey, title } = router.currentRoute.value.meta; const documentTitle = i18nKey ? $t(i18nKey) : title; useTitle(documentTitle); }
/** Update document title by locale */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/app/index.ts#L75-L81
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
resetStore
async function resetStore() { const authStore = useAuthStore(); clearAuthStorage(); authStore.$reset(); if (!route.meta.constant) { await toLogin(); } tabStore.cacheTabs(); routeStore.resetStore(); }
/** Reset auth store */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/auth/index.ts#L41-L54
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
login
async function login(userName: string, password: string, redirect = true) { startLoading(); const { data: loginToken, error } = await fetchLogin(userName, password); if (!error) { const pass = await loginByToken(loginToken); if (pass) { await redirectFromLogin(redirect); window.$notification?.success({ message: $t('page.login.common.loginSuccess'), description: $t('page.login.common.welcomeBack', { userName: userInfo.userName }) }); } } else { resetStore(); } endLoading(); }
/** * Login * * @param userName User name * @param password Password * @param [redirect=true] Whether to redirect after login. Default is `true` */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/auth/index.ts#L63-L84
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
setRouteHome
function setRouteHome(routeKey: LastLevelRouteKey) { routeHome.value = routeKey; }
/** * Set route home * * @param routeKey Route key */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L49-L51
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getGlobalMenus
function getGlobalMenus(routes: ElegantConstRoute[]) { menus.value = getGlobalMenusByAuthRoutes(routes); }
/** Get global menus */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L86-L88
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
updateGlobalMenusByLocale
function updateGlobalMenusByLocale() { menus.value = updateLocaleOfGlobalMenus(menus.value); }
/** Update global menus by locale */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L91-L93
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getCacheRoutes
function getCacheRoutes(routes: RouteRecordRaw[]) { cacheRoutes.value = getCacheRouteNames(routes); }
/** * Get cache routes * * @param routes Vue routes */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L110-L112
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
resetRouteCache
async function resetRouteCache(routeKey?: RouteKey) { const routeName = routeKey || (router.currentRoute.value.name as RouteKey); excludeCacheRoutes.value.push(routeName); await nextTick(); excludeCacheRoutes.value = []; }
/** * Reset route cache * * @default router.currentRoute.value.name current route name * @param routeKey */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L120-L128
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
resetStore
async function resetStore() { const routeStore = useRouteStore(); routeStore.$reset(); resetVueRoutes(); // after reset store, need to re-init constant route await initConstantRoute(); }
/** Reset store */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L134-L143
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
resetVueRoutes
function resetVueRoutes() { removeRouteFns.forEach(fn => fn()); removeRouteFns.length = 0; }
/** Reset vue routes */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L146-L149
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
initConstantRoute
async function initConstantRoute() { if (isInitConstantRoute.value) return; const staticRoute = createStaticRoutes(); if (authRouteMode.value === 'static') { addConstantRoutes(staticRoute.constantRoutes); } else { const { data, error } = await fetchGetConstantRoutes(); if (!error) { addConstantRoutes(data); } else { // if fetch constant routes failed, use static constant routes addConstantRoutes(staticRoute.constantRoutes); } } handleConstantAndAuthRoutes(); setIsInitConstantRoute(true); tabStore.initHomeTab(); }
/** init constant route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L152-L175
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
initAuthRoute
async function initAuthRoute() { // check if user info is initialized if (!authStore.userInfo.userId) { await authStore.initUserInfo(); } if (authRouteMode.value === 'static') { initStaticAuthRoute(); } else { await initDynamicAuthRoute(); } tabStore.initHomeTab(); }
/** Init auth route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L178-L191
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
initStaticAuthRoute
function initStaticAuthRoute() { const { authRoutes: staticAuthRoutes } = createStaticRoutes(); if (authStore.isStaticSuper) { addAuthRoutes(staticAuthRoutes); } else { const filteredAuthRoutes = filterAuthRoutesByRoles(staticAuthRoutes, authStore.userInfo.roles); addAuthRoutes(filteredAuthRoutes); } handleConstantAndAuthRoutes(); setIsInitAuthRoute(true); }
/** Init static auth route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L194-L208
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
initDynamicAuthRoute
async function initDynamicAuthRoute() { const { data, error } = await fetchGetUserRoutes(); if (!error) { const { routes, home } = data; addAuthRoutes(routes); handleConstantAndAuthRoutes(); setRouteHome(home); handleUpdateRootRouteRedirect(home); setIsInitAuthRoute(true); } else { // if fetch user routes failed, reset store authStore.resetStore(); } }
/** Init dynamic auth route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L211-L230
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
handleConstantAndAuthRoutes
function handleConstantAndAuthRoutes() { const allRoutes = [...constantRoutes.value, ...authRoutes.value]; const sortRoutes = sortRoutesByOrder(allRoutes); const vueRoutes = getAuthVueRoutes(sortRoutes); resetVueRoutes(); addRoutesToVueRouter(vueRoutes); getGlobalMenus(sortRoutes); getCacheRoutes(vueRoutes); }
/** handle constant and auth routes */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L233-L247
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
addRoutesToVueRouter
function addRoutesToVueRouter(routes: RouteRecordRaw[]) { routes.forEach(route => { const removeFn = router.addRoute(route); addRemoveRouteFn(removeFn); }); }
/** * Add routes to vue router * * @param routes Vue routes */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L254-L259
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
addRemoveRouteFn
function addRemoveRouteFn(fn: () => void) { removeRouteFns.push(fn); }
/** * Add remove route fn * * @param fn */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L266-L268
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
handleUpdateRootRouteRedirect
function handleUpdateRootRouteRedirect(redirectKey: LastLevelRouteKey) { const redirect = getRoutePath(redirectKey); if (redirect) { const rootRoute: CustomRoute = { ...ROOT_ROUTE, redirect }; router.removeRoute(rootRoute.name); const [rootVueRoute] = getAuthVueRoutes([rootRoute]); router.addRoute(rootVueRoute); } }
/** * Update root route redirect when auth route mode is dynamic * * @param redirectKey Redirect route key */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L275-L287
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getIsAuthRouteExist
async function getIsAuthRouteExist(routePath: RouteMap[RouteKey]) { const routeName = getRouteName(routePath); if (!routeName) { return false; } if (authRouteMode.value === 'static') { const { authRoutes: staticAuthRoutes } = createStaticRoutes(); return isRouteExistByRouteName(routeName, staticAuthRoutes); } const { data } = await fetchIsRouteExist(routeName); return data; }
/** * Get is auth route exist * * @param routePath Route path */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L294-L309
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getSelectedMenuKeyPath
function getSelectedMenuKeyPath(selectedKey: string) { return getSelectedMenuKeyPathByKey(selectedKey, menus.value); }
/** * Get selected menu key path * * @param selectedKey Selected menu key */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/index.ts#L316-L318
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
filterAuthRouteByRoles
function filterAuthRouteByRoles(route: ElegantConstRoute, roles: string[]): ElegantConstRoute[] { const routeRoles = (route.meta && route.meta.roles) || []; // if the route's "roles" is empty, then it is allowed to access const isEmptyRoles = !routeRoles.length; // if the user's role is included in the route's "roles", then it is allowed to access const hasPermission = routeRoles.some(role => roles.includes(role)); const filterRoute = { ...route }; if (filterRoute.children?.length) { filterRoute.children = filterRoute.children.flatMap(item => filterAuthRouteByRoles(item, roles)); } // Exclude the route if it has no children after filtering if (filterRoute.children?.length === 0) { return []; } return hasPermission || isEmptyRoles ? [filterRoute] : []; }
/** * Filter auth route by roles * * @param route Auth route * @param roles Roles */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/shared.ts#L22-L43
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
sortRouteByOrder
function sortRouteByOrder(route: ElegantConstRoute) { if (route.children?.length) { route.children.sort((next, prev) => (Number(next.meta?.order) || 0) - (Number(prev.meta?.order) || 0)); route.children.forEach(sortRouteByOrder); } return route; }
/** * sort route by order * * @param route route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/shared.ts#L50-L57
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
getGlobalMenuByBaseRoute
function getGlobalMenuByBaseRoute(route: RouteLocationNormalizedLoaded | ElegantConstRoute) { const { SvgIconVNode } = useSvgIcon(); const { name, path } = route; const { title, i18nKey, icon = import.meta.env.VITE_MENU_ICON, localIcon, iconFontSize } = route.meta ?? {}; const label = i18nKey ? $t(i18nKey) : title!; const menu: App.Global.Menu = { key: name as string, label, i18nKey, routeKey: name as RouteKey, routePath: path as RouteMap[RouteKey], icon: SvgIconVNode({ icon, localIcon, fontSize: iconFontSize || 20 }), title: label }; return menu; }
/** * Get global menu by route * * @param route */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/shared.ts#L128-L147
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
recursiveGetIsRouteExistByRouteName
function recursiveGetIsRouteExistByRouteName(route: ElegantConstRoute, routeName: RouteKey) { let isExist = route.name === routeName; if (isExist) { return true; } if (route.children && route.children.length) { isExist = route.children.some(item => recursiveGetIsRouteExistByRouteName(item, routeName)); } return isExist; }
/** * Recursive get is route exist by route name * * @param route * @param routeName */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/shared.ts#L185-L197
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
findMenuPath
function findMenuPath(targetKey: string, menu: App.Global.Menu): string[] | null { const path: string[] = []; function dfs(item: App.Global.Menu): boolean { path.push(item.key); if (item.key === targetKey) { return true; } if (item.children) { for (const child of item.children) { if (dfs(child)) { return true; } } } path.pop(); return false; } if (dfs(menu)) { return path; } return null; }
/** * Find menu path * * @param targetKey Target menu key * @param menu Menu */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/route/shared.ts#L229-L257
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
initHomeTab
function initHomeTab() { homeTab.value = getDefaultHomeTab(router, routeStore.routeHome); }
/** Init home tab */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L38-L40
6bd3e89e710836beb14b1a3381532a3eb7cc3a75
soybean-admin-antd
github_2023
soybeanjs
typescript
setActiveTabId
function setActiveTabId(id: string) { activeTabId.value = id; }
/** * Set active tab id * * @param id Tab id */
https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L53-L55
6bd3e89e710836beb14b1a3381532a3eb7cc3a75