repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
velite
github_2023
zce
typescript
VeliteFile.get
static get(path: string): VeliteFile | undefined { return loaded.get(path) }
/** * Get meta object from cache * @param path file path * @returns resolved meta object if exists */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L75-L77
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
VeliteFile.create
static async create({ path, config }: { path: string; config: Config }): Promise<VeliteFile> { const meta = new VeliteFile({ path, config }) const loader = config.loaders.find(loader => loader.test.test(path)) if (loader == null) return meta.fail(`no loader found for '${path}'`) meta.value = await readFile(path) meta.data = await loader.load(meta) if (meta.data?.data == null) return meta.fail(`no data loaded from '${path}'`) loaded.set(path, meta) return meta }
/** * Create meta object from file path * @param options meta options * @returns resolved meta object */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L84-L93
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
flatten
const flatten = (msg: unknown): unknown => { if (typeof msg !== 'string') return msg return msg.replaceAll(process.cwd() + sep, '').replace(/\\/g, '/') }
/** * replace cwd with '.' and replace backslash with slash to make output more readable * @param msg message * @returns flattened message */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/logger.ts#L24-L27
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodString.nonempty
nonempty(message?: errorUtil.ErrMessage) { return this.min(1, errorUtil.errToObj(message)) }
/** * @deprecated Use z.string().min(1) instead. * @see {@link ZodString.min} */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L1065-L1067
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
floatSafeRemainder
function floatSafeRemainder(val: number, step: number) { const valDecCount = (val.toString().split('.')[1] || '').length const stepDecCount = (step.toString().split('.')[1] || '').length const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount const valInt = parseInt(val.toFixed(decCount).replace('.', '')) const stepInt = parseInt(step.toFixed(decCount).replace('.', '')) return (valInt % stepInt) / Math.pow(10, decCount) }
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L1185-L1192
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodObject.extend
extend<Augmentation extends ZodRawShape>(augmentation: Augmentation): ZodObject<objectUtil.extendShape<T, Augmentation>, UnknownKeys, Catchall> { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }) as any }
// };
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2446-L2454
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodObject.merge
merge<Incoming extends AnyZodObject, Augmentation extends Incoming['shape']>( merging: Incoming ): ZodObject<objectUtil.extendShape<T, Augmentation>, Incoming['_def']['unknownKeys'], Incoming['_def']['catchall']> { const merged: any = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }) as any return merged }
/** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2498-L2511
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodObject.setKey
setKey<Key extends string, Schema extends ZodTypeAny>(key: Key, schema: Schema): ZodObject<T & { [k in Key]: Schema }, UnknownKeys, Catchall> { return this.augment({ [key]: schema }) as any }
// }
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2548-L2550
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodObject.catchall
catchall<Index extends ZodTypeAny>(index: Index): ZodObject<T, UnknownKeys, Index> { return new ZodObject({ ...this._def, catchall: index }) as any }
// }
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2573-L2578
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodObject.deepPartial
deepPartial(): partialUtil.DeepPartial<this> { return deepPartialify(this) as any }
/** * @deprecated */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2613-L2615
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
getDiscriminator
const getDiscriminator = <T extends ZodTypeAny>(type: T): Primitive[] => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema) } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()) } else if (type instanceof ZodLiteral) { return [type.value] } else if (type instanceof ZodEnum) { return type.options } else if (type instanceof ZodNativeEnum) { // eslint-disable-next-line ban/ban return util.objectValues(type.enum as any) } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType) } else if (type instanceof ZodUndefined) { return [undefined] } else if (type instanceof ZodNull) { return [null] } else if (type instanceof ZodOptional) { return [undefined, ...getDiscriminator(type.unwrap())] } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())] } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()) } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()) } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType) } else { return [] } }
/////////////////////////////////////////////////////
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2853-L2884
cfb639a8fa0452168c1be3962a1022cdb947d8d3
velite
github_2023
zce
typescript
ZodDiscriminatedUnion.create
static create<Discriminator extends string, Types extends [ZodDiscriminatedUnionOption<Discriminator>, ...ZodDiscriminatedUnionOption<Discriminator>[]]>( discriminator: Discriminator, options: Types, params?: RawCreateParams ): ZodDiscriminatedUnion<Discriminator, Types> { // Get all the valid discriminator values const optionsMap: Map<Primitive, Types[number]> = new Map() // try { for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]) if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`) } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`) } optionsMap.set(value, type) } } return new ZodDiscriminatedUnion< Discriminator, // DiscriminatorValue, Types >({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }) }
/** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */
https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/schemas/zod/types.ts#L2971-L3005
cfb639a8fa0452168c1be3962a1022cdb947d8d3
shadcnui-boilerplate
github_2023
TinsFox
typescript
createWrapper
const createWrapper = () => { return function Wrapper({ children }: { children: ReactNode }) { return ( <QueryClientProvider client={queryClient}> {children} </QueryClientProvider> ) } }
// 测试包装器
https://github.com/TinsFox/shadcnui-boilerplate/blob/880aba5f59a9ef6de3d42597cf332ae7754b4a50/apps/admin/src/hooks/query/use-user.test.tsx#L31-L39
880aba5f59a9ef6de3d42597cf332ae7754b4a50
shadcnui-boilerplate
github_2023
TinsFox
typescript
openInEditor
const openInEditor = (file: string) => { fetch(`/__open-in-editor?file=${encodeURIComponent(`${file}`)}`) }
// http://localhost:5173/src/App.tsx?t=1720527056591:41:9
https://github.com/TinsFox/shadcnui-boilerplate/blob/880aba5f59a9ef6de3d42597cf332ae7754b4a50/apps/admin/src/lib/dev.tsx#L59-L61
880aba5f59a9ef6de3d42597cf332ae7754b4a50
shadcnui-boilerplate
github_2023
TinsFox
typescript
getAbsolutePath
function getAbsolutePath(value: string): any { return dirname(require.resolve(join(value, "package.json"))) }
/** * This function is used to resolve the absolute path of a package. * It is needed in projects that use Yarn PnP or are set up within a monorepo. */
https://github.com/TinsFox/shadcnui-boilerplate/blob/880aba5f59a9ef6de3d42597cf332ae7754b4a50/packages/pro-table/.storybook/main.ts#L9-L11
880aba5f59a9ef6de3d42597cf332ae7754b4a50
shadcnui-boilerplate
github_2023
TinsFox
typescript
PaginationWrapper
function PaginationWrapper(props: Omit<React.ComponentProps<typeof DataTablePagination>, "table">) { // 模拟数据和列 const data = React.useMemo(() => Array.from({ length: 100 }).fill(0).map((_, index) => ({ id: index })), []) const columns = React.useMemo(() => [{ accessorKey: "id" }], []) const table = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel(), pageCount: Math.ceil(data.length / (props.pagination?.pageSize || 10)), state: { pagination: { pageIndex: props.pagination?.pageIndex || 0, pageSize: props.pagination?.pageSize || 10, }, }, manualPagination: true, }) return <DataTablePagination table={table} {...props} /> }
// 创建一个包装组件来使用 Hook
https://github.com/TinsFox/shadcnui-boilerplate/blob/880aba5f59a9ef6de3d42597cf332ae7754b4a50/packages/pro-table/src/components/data-table/data-table-pagination.stories.tsx#L8-L28
880aba5f59a9ef6de3d42597cf332ae7754b4a50
shadcnui-boilerplate
github_2023
TinsFox
typescript
ToolbarWrapper
function ToolbarWrapper(props: Omit<React.ComponentProps<typeof DataTableToolbar>, "table">) { const table = useReactTable({ data: [], columns: [], getCoreRowModel: getCoreRowModel(), }) return <DataTableToolbar table={table} {...props} /> }
// 创建一个包装组件来使用 Hook
https://github.com/TinsFox/shadcnui-boilerplate/blob/880aba5f59a9ef6de3d42597cf332ae7754b4a50/packages/pro-table/src/components/data-table/data-table-toolbar.stories.tsx#L8-L16
880aba5f59a9ef6de3d42597cf332ae7754b4a50
fuji-web
github_2023
normal-computing
typescript
visionActionAdapter
function visionActionAdapter(action: ParsedResponseSuccess): Action { const args = { ...action.parsedAction.args, uid: "" }; if ("elementId" in args) { args.uid = args.elementId; } return { thought: action.thought, operation: { name: action.parsedAction.name, args, } as Action["operation"], }; }
// make action compatible with vision agent
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/helpers/dom-agent/determineNextAction.ts#L145-L157
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
DomActions.sendCommand
private async sendCommand(method: string, params?: any): Promise<any> { return chrome.debugger.sendCommand({ tabId: this.tabId }, method, params); }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/helpers/rpc/domActions.ts#L21-L23
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
DomActions.waitTillElementRendered
public async waitTillElementRendered( selectorExpression: string, interval = DEFAULT_INTERVAL, timeout = DEFAULT_TIMEOUT, ): Promise<void> { return waitTillStable( async () => { const { result } = await this.sendCommand("Runtime.evaluate", { expression: `${selectorExpression}?.innerHTML?.length`, }); return result.value || 0; }, interval, timeout, ); }
// so always check if it exists first (e.g. with waitForElement)
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/helpers/rpc/domActions.ts#L186-L201
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
sendMessage
function sendMessage<K extends keyof RPCMethods>( tabId: number, method: K, payload: Parameters<RPCMethods[K]>, ): Promise<ReturnType<RPCMethods[K]>> { // Send a message to the other world // Ensure that the method and arguments are correct according to RpcMethods return new Promise((resolve, reject) => { chrome.tabs.sendMessage(tabId, { method, payload }, (response) => { if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); } else { resolve(response); } }); }); }
// Call these functions to execute code in the content script
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/helpers/rpc/pageRPC.ts#L6-L22
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
scrollIntoViewFunction
function scrollIntoViewFunction() { // @ts-expect-error this is run in the browser context this.scrollIntoView({ block: "center", inline: "center", // behavior: 'smooth', }); }
// TypeScript function
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/helpers/rpc/runtimeFunctionStrings.ts#L2-L9
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
isTouchedElement
function isTouchedElement(elem: Element) { return ( elem.hasAttribute(VISIBLE_TEXT_ATTRIBUTE_NAME) || elem.hasAttribute(ARIA_LABEL_ATTRIBUTE_NAME) ); }
// check if the node has the attributes we added
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/pages/content/drawLabels.ts#L119-L124
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
traverseDom
function traverseDom(node: Node, selector: string): DomAttrs { if (node.nodeType === Node.TEXT_NODE) { return { visibleText: node.nodeValue ?? "", ariaLabel: "" }; } else if (isElementNode(node)) { if (!isVisible(node)) return emptyDomAttrs; // skip if the element is not visible if (isTouchedElement(node)) { return { visibleText: node.getAttribute(VISIBLE_TEXT_ATTRIBUTE_NAME) ?? "", ariaLabel: node.getAttribute(ARIA_LABEL_ATTRIBUTE_NAME) ?? "", }; } let visibleText = ""; let ariaLabel = getAccessibleName(node); // skip children of SVGs because they have their own visibility rules if (node.tagName.toLocaleLowerCase() !== "svg") { for (const child of node.childNodes) { const result = traverseDom(child, selector); // aggregate visible text visibleText += " " + result.visibleText; visibleText = visibleText.trim(); // if parent doesn't have it, set aria-label with the first one found if (ariaLabel.length === 0 && result.ariaLabel.length > 0) { ariaLabel = result.ariaLabel; } } } visibleText = removeEmojis(visibleText); // cache attributes in DOM node.setAttribute(VISIBLE_TEXT_ATTRIBUTE_NAME, visibleText); node.setAttribute(ARIA_LABEL_ATTRIBUTE_NAME, ariaLabel); return { visibleText, ariaLabel }; } return emptyDomAttrs; }
// find the visible text and best-match aria-label of the element
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/pages/content/drawLabels.ts#L128-L164
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
removeEmojis
function removeEmojis(label: string) { return label.replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, "").trim(); }
// It removes all symbols except:
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/pages/content/drawLabels.ts#L171-L173
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
getWebPDataURL
function getWebPDataURL( canvas: HTMLCanvasElement, maxFileSizeMB: number = 5, maxQuality = 1, qualityStep = 0.05, ) { const maxFileSizeBytes = maxFileSizeMB * 1024 * 1024; let quality = maxQuality; let dataURL = canvas.toDataURL("image/webp", quality); // Check the size of the data URL while (dataURL.length * 0.75 > maxFileSizeBytes && quality > 0) { quality -= qualityStep; // Decrease quality dataURL = canvas.toDataURL("image/webp", quality); } return dataURL; }
// Function to get WebP data URL and ensure it's less than 5 MB
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/src/shared/images/mergeScreenshots.ts#L50-L67
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
ManifestParser.constructor
private constructor() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/utils/manifest-parser/index.ts#L5-L5
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
reload
function reload(): void { pendingReload = false; window.location.reload(); }
// reload
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/utils/reload/injections/view.ts#L19-L22
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
reloadWhenTabIsVisible
function reloadWhenTabIsVisible(): void { !document.hidden && pendingReload && reload(); }
// reload when tab is visible
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/utils/reload/injections/view.ts#L25-L27
1aec509e4c437ca7764a5b4a56deaeba18691729
fuji-web
github_2023
normal-computing
typescript
MessageInterpreter.constructor
private constructor() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/normal-computing/fuji-web/blob/1aec509e4c437ca7764a5b4a56deaeba18691729/utils/reload/interpreter/index.ts#L5-L5
1aec509e4c437ca7764a5b4a56deaeba18691729
DistiLlama
github_2023
shreyaskarnik
typescript
Header
const Header = ({ onBack, onRefresh, onOpenSettings }) => { return ( <div className="header"> <FaBackspace size="2rem" className="button" onClick={onBack} title="Go Back" /> <FaCog size="2rem" className="button center-button" onClick={onOpenSettings} title="Settings" /> <IoIosRefresh size="2rem" className="button" onClick={onRefresh} title="Refresh" /> </div> ); };
// eslint-disable-next-line react/prop-types
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/src/pages/common/Header.tsx#L7-L15
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
bytesToGB
const bytesToGB = bytes => (bytes / 1e9).toFixed(2);
// Helper function to convert bytes to GB
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/src/pages/sidePanel/Settings.tsx#L10-L10
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
updateStorage
const updateStorage = (newModel, newTemperature) => { chrome.storage.local.set({ model: newModel, temperature: newTemperature }); };
// Function to update Chrome storage
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/src/pages/sidePanel/Settings.tsx#L22-L24
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
fetchAndSetModels
const fetchAndSetModels = async () => { try { setIsLoading(true); const fetchedModels = await getModels(); if (isMounted) { setModels(fetchedModels); chrome.storage.local.get(['model', 'temperature', 'isDefaultSet'], result => { if (result.isDefaultSet) { setIsDefaultSet(true); } if (result.model) { const storedModel = fetchedModels.find(m => m.name === result.model.name); setSelectedModel(storedModel || fetchedModels[0]); setIsDefaultSet(result.isDefaultSet); } else { setSelectedModel(fetchedModels[0]); setIsDefaultSet(false); } if (result.temperature) { setTemperatureValue(result.temperature); setIsDefaultSet(result.isDefaultSet); } else { setTemperatureValue(DEFAULT_TEMPERATURE); setIsDefaultSet(false); } }); } } catch (err) { if (isMounted) { setError(err.message); } } finally { if (isMounted) { setIsLoading(false); } } };
// To handle component unmount
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/src/pages/sidePanel/Settings.tsx#L41-L78
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
ManifestParser.constructor
private constructor() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/utils/manifest-parser/index.ts#L5-L5
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
reload
function reload(): void { pendingReload = false; window.location.reload(); }
// reload
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/utils/reload/injections/view.ts#L19-L22
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
reloadWhenTabIsVisible
function reloadWhenTabIsVisible(): void { !document.hidden && pendingReload && reload(); }
// reload when tab is visible
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/utils/reload/injections/view.ts#L25-L27
d0bff7ae6a310d910488a87016e0f14be286c31d
DistiLlama
github_2023
shreyaskarnik
typescript
MessageInterpreter.constructor
private constructor() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/shreyaskarnik/DistiLlama/blob/d0bff7ae6a310d910488a87016e0f14be286c31d/utils/reload/interpreter/index.ts#L5-L5
d0bff7ae6a310d910488a87016e0f14be286c31d
InterpAny-Clearer
github_2023
zzh-tech
typescript
App
const App = () => { const [masks, setMasks] = useState<Array<modelMaskProps>>([]); const [defaultRawMask, setDefaultRawMask] = useState<modelRawMaskProps | null>(null); const [blocking, setBlocking] = useState<boolean>(false); const addMask = (mask: modelMaskProps) => { setMasks([...masks, mask]); } const [imagePath1, setImagePath1] = useState<string>(""); const [imagePath2, setImagePath2] = useState<string>(""); const handleDeleteMask = (index: number) => { const newMasks = [...masks]; newMasks.splice(index,1) setMasks(newMasks); }; const updateLoader = (loading: boolean) => { setBlocking(loading) } const updateMasks = (masks: Array<modelMaskProps>) => { console.log("vatran updateMasks", "") setMasks(masks); } const flexCenterClasses = "flex items-center justify-center m-auto"; return ( <> <div className="w-full h-full"> <h1 className="text-center text-2xl my-3">Manipulated Interpolation of Anything</h1> <div className={`${flexCenterClasses} w-[90%] h-[90%]`}> <AppContextProvider> <StageApp setDefaultRawMask={setDefaultRawMask} addMask={addMask} updateLoader={updateLoader} onUploadImage1={setImagePath1} onUploadImage2={setImagePath2} /> </AppContextProvider> <ControlContextProvider> <ControlApp defaultRawMask={defaultRawMask} masks={masks} handleDelete={handleDeleteMask} updateMasks={updateMasks} updateLoader={updateLoader} image1Path={imagePath1} image2Path={imagePath2} /> </ControlContextProvider> </div> </div> <div className={blocking? 'flex model' : 'hidden' }> <div className='modal-content'> <div className='loader'></div> <div className='modal-text'>Loading...</div> </div> </div> </> ); }
// 000
https://github.com/zzh-tech/InterpAny-Clearer/blob/50ece06a1fca91bfeed2bd3f2e724d696833ff63/webapp/webapp/src/App.tsx#L32-L82
50ece06a1fca91bfeed2bd3f2e724d696833ff63
InterpAny-Clearer
github_2023
zzh-tech
typescript
initModel
const initModel = async () => { try { if (MODEL_DIR === undefined) return; const URL: string = MODEL_DIR; const model = await InferenceSession.create(URL); setModel(model); } catch (e) { console.log(e); } };
// Initialize the ONNX model
https://github.com/zzh-tech/InterpAny-Clearer/blob/50ece06a1fca91bfeed2bd3f2e724d696833ff63/webapp/webapp/src/StageApp.tsx#L50-L59
50ece06a1fca91bfeed2bd3f2e724d696833ff63
InterpAny-Clearer
github_2023
zzh-tech
typescript
arrayToImageData
function arrayToImageData(input: any, width: number, height: number) { const [r, g, b, a] = [0, 114, 189, 255]; // the masks's blue color const arr = new Uint8ClampedArray(4 * width * height).fill(0); for (let i = 0; i < input.length; i++) { // Threshold the onnx model mask prediction at 0.0 // This is equivalent to thresholding the mask using predictor.model.mask_threshold // in python if (input[i] > 0.0) { arr[4 * i + 0] = r; arr[4 * i + 1] = g; arr[4 * i + 2] = b; arr[4 * i + 3] = a; } } return new ImageData(arr, height, width); }
// Convert the onnx model mask prediction to ImageData
https://github.com/zzh-tech/InterpAny-Clearer/blob/50ece06a1fca91bfeed2bd3f2e724d696833ff63/webapp/webapp/src/components/helpers/maskUtils.tsx#L28-L44
50ece06a1fca91bfeed2bd3f2e724d696833ff63
InterpAny-Clearer
github_2023
zzh-tech
typescript
imageDataToImage
function imageDataToImage(imageData: ImageData) { const canvas = imageDataToCanvas(imageData); const image = new Image(); image.src = canvas.toDataURL(); return image; }
// Use a Canvas element to produce an image from ImageData
https://github.com/zzh-tech/InterpAny-Clearer/blob/50ece06a1fca91bfeed2bd3f2e724d696833ff63/webapp/webapp/src/components/helpers/maskUtils.tsx#L47-L52
50ece06a1fca91bfeed2bd3f2e724d696833ff63
InterpAny-Clearer
github_2023
zzh-tech
typescript
imageDataToCanvas
function imageDataToCanvas(imageData: ImageData) { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = imageData.width; canvas.height = imageData.height; ctx?.putImageData(imageData, 0, 0); return canvas; }
// Canvas elements can be created from ImageData
https://github.com/zzh-tech/InterpAny-Clearer/blob/50ece06a1fca91bfeed2bd3f2e724d696833ff63/webapp/webapp/src/components/helpers/maskUtils.tsx#L55-L62
50ece06a1fca91bfeed2bd3f2e724d696833ff63
InterpAny-Clearer
github_2023
zzh-tech
typescript
handleImageScale
const handleImageScale = (image: HTMLImageElement) => { // Input images to SAM must be resized so the longest side is 1024 const LONG_SIDE_LENGTH = 1024; let w = image.naturalWidth; let h = image.naturalHeight; const samScale = LONG_SIDE_LENGTH / Math.max(h, w); return { height: h, width: w, samScale }; };
// Copyright (c) Meta Platforms, Inc. and affiliates.
https://github.com/zzh-tech/InterpAny-Clearer/blob/50ece06a1fca91bfeed2bd3f2e724d696833ff63/webapp/webapp/src/components/helpers/scaleHelper.tsx#L9-L16
50ece06a1fca91bfeed2bd3f2e724d696833ff63
ChatGPT_Agent
github_2023
liyucheng09
typescript
updateGame
const updateGame = () => { const currentTime = performance.now(); gc.lastFrameDelta = (currentTime - lastUpdateTime) / 1000; // const key = gc.input.getLastKeyDown("a", "w", "s", "d"); // if (key === "a") transform.translation.x -= 3; // else if (key === "d") transform.translation.x += 3; // else if (key === "w") transform.translation.y -= 3; // else if (key === "s") transform.translation.y += 3; const sprite = gc.playerEnt.sprite; const transform = gc.playerEnt.transform; const centerCharOffset = new Vec2( canvas.width * 0.5 - sprite.width * 0.5, canvas.height * 0.5 - sprite.height * 0.5); camera.translation = transform.translation.sub(centerCharOffset); gc.viewTransform = camera.mat3(); playerInteractionSystem.run(gc, ecs); mousePickerSystem.run(gc, ecs); gridMovementSystem.run(gc, ecs); agentMovementSystem.run(gc, ecs); spriteLocationSystem.run(gc, ecs); lastUpdateTime = currentTime; };
/************************************ ***** Updates the game state ******* ************************************/
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/components/Game.tsx#L231-L256
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
drawGame
const drawGame = () => { const ents: EntsWith<[CTransform, CBackgroundTile]> = ecs.getEntsWith(CTransform, CBackgroundTile); backgroundRenderSystem.run(gc, ents); spriteRenderSystem.run(gc, ecs); const fgEnts: EntsWith<[CTransform, CForegroundTile]> = ecs.getEntsWith(CTransform, CForegroundTile); foregroundRenderSystem.run(gc, fgEnts); // Call requestAnimationFrame to update and draw the game on the next frame requestAnimationFrame(gameLoop); };
/** * Renders all content in the game */
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/components/Game.tsx#L261-L271
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
CTransform.mat3
public mat3(): Mat3 { const c = Math.cos(this.rotation); const s = Math.sin(this.rotation); return new Mat3( this.scale.x * c, -this.scale.y * s, -this.translation.x, this.scale.x * s, this.scale.y * c, -this.translation.y, 0, 0, 1 ); }
/** * * @returns Matrix corresponding to Translate * R * scale, */
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/engine/comps/CTransform.ts#L13-L22
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
AgentMovementSystem.isPositionOpen
private isPositionOpen(entId: number, pos: Vec2, colliders: EntsWith<[CGridCollider]>): boolean { if (this.staticBoundaries.has(pos.toString())) { return false; } for (const [eid, [collider]] of colliders) { if (entId === eid) continue; if (collider.gridPos?.equals(pos)) return false; if (collider.nextGridPos?.equals(pos)) return false; } return true; }
/** * * @param eid The ent id that is trying to move. Necessary so that they dont pick up self collisions * @param pos The grid position they want to check if its available * @param colliders The other colliders in the scene to check * @returns */
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/engine/systems/AgentMovementSystem.ts#L144-L154
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
GridMovementSystem.isPositionOpen
private isPositionOpen(entId: number, pos: Vec2, colliders: EntsWith<[CGridCollider]>): boolean { if (this.staticBoundaries.has(pos.toString())) { return false; } // todo, optimize collision detection with a hashset for (const [eid, [collider]] of colliders) { if (entId === eid) continue; if (collider.gridPos?.equals(pos)) return false; if (collider.nextGridPos?.equals(pos)) return false; } return true; }
/** * * @param eid The ent id that is trying to move. Necessary so that they dont pick up self collisions * @param pos The grid position they want to check if its available * @param colliders The other colliders in the scene to check * @returns */
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/engine/systems/GridMovementSystem.ts#L100-L112
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
Index.addEnt
private addEnt(eid: EntIdType, manager: EcsManager) { const comps = this.componentTypes.map(compType => manager.getComponent(eid, compType)) as T; this.indexedComponents.set(eid, comps); }
// }
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L34-L37
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
EcsManager.addComponent
public addComponent<T extends IComponent>(eid: EntIdType, component: T): T { const store = this.getComponentStore(component.constructor.name); store.set(eid, component); this.updateIndexes(eid); return component; }
// Returns the component passed in
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L104-L109
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
EcsManager.removeComponent
public removeComponent<T extends IComponent>(eid: EntIdType, componentType: ComponentConstructor<T>): void { const store = this.getComponentStore(componentType.name); store.delete(eid); this.updateIndexes(eid); }
// Remove a component from an entity
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L112-L116
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
EcsManager.getComponent
public getComponent<T extends IComponent>(eid: EntIdType, componentType: ComponentConstructor<T>): T { const store = this.getComponentStore(componentType.name); return store.get(eid) as T; }
// Get a component from an entity
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L119-L122
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
EcsManager.hasComponent
public hasComponent<T extends IComponent>(eid: EntIdType, componentType: ComponentConstructor<T>): boolean { const store = this.getComponentStore(componentType.name); return store.has(eid); }
// Check if an entity has a component
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L125-L128
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
EcsManager.getEntsWith
public getEntsWith<T extends IComponent[]>(...componentTypes: ComponentConstructor<T[number]>[]) : EntsWith<T> { // if just on component type passed in, use the component store itself if (componentTypes.length === 1) { const store = this.getComponentStore(componentTypes[0].name); const iter = store.entries(); const next = { [Symbol.iterator]() { return { next(): IteratorResult<[EntIdType, T]> { const result = iter.next(); if (result.done) return { done: true, value: undefined }; const [eid, component] = result.value; return { done: false, value: [eid, [component]] } as any; } }; } } as IterableIterator<[EntIdType, T]>; return next; } // otherwise we try an index, (index must exist!) const index = this.getIndex(...componentTypes); if (!index) { // we could use the indexes we do have to intelligently get the ents. // basically compute an intersection starting with whatever has the smallest number // of components... throw new Error(`Index with key ${this.getIndexKey(...componentTypes)} does not exist`); } // need to swizzle index components to match the ordering of the arguments passed in const indexCompOrder = index.componentTypes.map(t => t.name); const requestedCompOrder = componentTypes.map(t => t.name); const swizzle = Array(requestedCompOrder.length); for (var i = 0; i < swizzle.length; i++) { swizzle[i] = indexCompOrder.indexOf(requestedCompOrder[i]); } const iter = index.indexedComponents.entries(); return { [Symbol.iterator]() { return { next(): IteratorResult<[EntIdType, T]> { const result = iter.next(); if (result.done) return { done: true, value: undefined }; const [eid, components] = result.value as [number, T[number][]]; const swizzled = Array(swizzle.length); for (var i = 0; i < swizzle.length; i++) { swizzled[i] = components[swizzle[i]]; } return { done: false, value: [eid, swizzled] } as any; } }; } } as IterableIterator<[EntIdType, T]>; }
// what if i make this extend the component constructors instead
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L163-L218
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
EcsManager.updateIndex
private updateIndex(index: Index<any>, entId?: EntIdType): void { if (entId) { index.addEntIfMatch(entId, this); return; } for (const eid of this.entities) { index.addEntIfMatch(eid, this); } }
// overloaded to support 1 or all
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Ecs.ts#L274-L282
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
InputMapper.getActionPressTime
getActionPressTime(action: Action): number | null { const keys = this.keyMap[action]; let minPressTime = this.keyListener.getKeyPressTime(keys[0]); for (let i = 1; i < keys.length; i++) { const keyPressTime = this.keyListener.getKeyPressTime(keys[i]); if (!keyPressTime) continue; if (!minPressTime) { minPressTime = keyPressTime; } else { minPressTime = Math.min(minPressTime, keyPressTime); } } return minPressTime; }
/** * * @param action The action to check * @returns The time the action was first pressed */
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/Inputmapper.ts#L28-L41
d7cd74e79af467a6c6c56b96090f6d9860a5574e
ChatGPT_Agent
github_2023
liyucheng09
typescript
KeyListener.getLastKeyDown
getLastKeyDown(...keys: string[]): string | null { let lastKeyDown: string | null = null; let lastKeyPressTime = Number.NEGATIVE_INFINITY; if ((keys?.length ?? 0) > 0) { keys.forEach(key => { const keyPressTime = this.getKeyPressTime(key); if (keyPressTime !== null && keyPressTime > lastKeyPressTime) { lastKeyDown = key; lastKeyPressTime = keyPressTime; } }); return lastKeyDown; } for (const [key, keyPressTime] of Object.entries(this.keyPressTimes)) { if (keyPressTime !== null && keyPressTime > lastKeyPressTime) { lastKeyDown = key; lastKeyPressTime = keyPressTime; } } return lastKeyDown; }
/** * * @param keys Optional. If not provided, all keys are checked * @returns The last key that was pressed */
https://github.com/liyucheng09/ChatGPT_Agent/blob/d7cd74e79af467a6c6c56b96090f6d9860a5574e/src/frontend/infra/KeyListener.ts#L38-L61
d7cd74e79af467a6c6c56b96090f6d9860a5574e
wordflow
github_2023
poloclub
typescript
Wordflow.constructor
constructor() { super(); }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/.fttemplates/default-template/[FTName].ts#L20-L22
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
Wordflow.willUpdate
willUpdate(changedProperties: PropertyValues<this>) {}
/** * This method is called before new DOM is updated and rendered * @param changedProperties Property that has been changed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/.fttemplates/default-template/[FTName].ts#L28-L28
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
Wordflow.initData
async initData() {}
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/.fttemplates/default-template/[FTName].ts
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarConfirmDialog.constructor
constructor() { super(); this.confirmAction = () => {}; this.cancelAction = () => {}; }
// ===== Lifecycle Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/confirm-dialog/confirm-dialog.ts#L42-L46
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarConfirmDialog.willUpdate
willUpdate(changedProperties: PropertyValues<this>) {}
/** * This method is called before new DOM is updated and rendered * @param changedProperties Property that has been changed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/confirm-dialog/confirm-dialog.ts#L56-L56
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarConfirmDialog.initData
initData = async () => {}
// ===== Custom Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/confirm-dialog/confirm-dialog.ts
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarConfirmDialog.dialogClicked
dialogClicked(e: MouseEvent) { if (e.target === this.dialogElement) { this.dialogElement.close(); } }
// ===== Event Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/confirm-dialog/confirm-dialog.ts#L91-L95
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarConfirmDialog.render
render() { return html` <dialog class="confirm-dialog" @click=${(e: MouseEvent) => this.dialogClicked(e)} > <div class="header"> <div class="header-name">${this.header}</div> </div> <div class="content"> <div class="message">${this.message}</div> <div class="skip-bar"> <input type="checkbox" id="checkbox-skip-confirmation" name="checkbox-skip-confirmation" /> <label for="checkbox-skip-confirmation" >Don't ask me again about this action</label > </div> </div> <div class="button-block"> <button class="cancel-button" @click=${(e: MouseEvent) => this.cancelClicked(e)} > Cancel </button> <button class="confirm-button" @click=${(e: MouseEvent) => this.confirmClicked(e)} > ${this.yesButtonText} </button> </div> </dialog> `; }
// ===== Templates and Styles ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/confirm-dialog/confirm-dialog.ts#L124-L164
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.constructor
constructor() { super(); }
// ===== Lifecycle Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L35-L37
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.willUpdate
willUpdate(changedProperties: PropertyValues<this>) {}
/** * This method is called before new DOM is updated and rendered * @param changedProperties Property that has been changed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L43-L43
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.initData
async initData() {}
// ===== Custom Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L46-L46
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.toolButtonGroupMouseEnterHandler
toolButtonGroupMouseEnterHandler(e: MouseEvent) { e.preventDefault(); // Tell the editor component to highlight the effective region const event = new Event('mouse-enter-tools', { bubbles: true, composed: true }); this.dispatchEvent(event); }
/** * Highlight the currently effective region when the user hovers over the buttons * @param e Mouse event */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L54-L63
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.toolButtonGroupMouseLeaveHandler
toolButtonGroupMouseLeaveHandler(e: MouseEvent) { e.preventDefault(); const event = new Event('mouse-leave-tools', { bubbles: true, composed: true }); this.dispatchEvent(event); }
/** * De-highlight the currently effective region when mouse leaves the buttons * @param e Mouse event */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L69-L76
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.toolButtonClickHandler
toolButtonClickHandler(e: MouseEvent, index: number) { e.preventDefault(); const curPrompt = this.favPrompts[index]; // Special case for empty button: clicking opens the setting window if (curPrompt === null) { this.settingButtonClicked(); return; } // Do not respond to interactions when an action is laoding if (this.loadingActionIndex !== null) return; // Prevent default suppresses ::active, we need to manually trigger it const target = e.target as HTMLElement; target.classList.add('active'); setTimeout(() => { target.classList.remove('active'); }, 100); const event = new CustomEvent<[PromptDataLocal, number]>( 'tool-button-clicked', { detail: [curPrompt, index], bubbles: true, composed: true } ); this.dispatchEvent(event); }
/** * Notify the parent to take wordflow action * @param e Mouse event * @param index Index of the active tool button */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L83-L113
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowFloatingMenu.render
render() { // Create the active tool buttons let toolButtons = html``; for (const [i, prompt] of this.favPrompts.entries()) { // Take the first unicode character as the icon const icon = prompt?.icon || '+'; toolButtons = html`${toolButtons} <button class="tool-button" ?is-loading=${this.loadingActionIndex === i} ?is-empty=${prompt === null} @mousedown=${(e: MouseEvent) => this.toolButtonClickHandler(e, i)} @mouseenter=${(e: MouseEvent) => this.toolButtonMouseEnterHandler(e, i)} @mouseleave=${(e: MouseEvent) => this.toolButtonMouseLeaveHandler(e)} > <div class="icon"> <div class="svg-icon"> ${this.loadingActionIndex === i ? '' : icon} </div> <div class="loader-container" ?hidden=${this.loadingActionIndex !== i} > <div class="circle-loader"></div> </div> </div> </button>`; } return html` <div class="floating-menu"> <div class="tool-buttons" ?has-loading-action=${this.loadingActionIndex !== null} @mouseenter=${(e: MouseEvent) => this.toolButtonGroupMouseEnterHandler(e)} @mouseleave=${(e: MouseEvent) => this.toolButtonGroupMouseLeaveHandler(e)} > ${toolButtons} </div> <button class="tool-button setting-button" @mousedown=${() => this.settingButtonClicked()} @mouseenter=${(e: MouseEvent) => this.settingButtonMouseEnterHandler(e)} @mouseleave=${(e: MouseEvent) => this.toolButtonMouseLeaveHandler(e)} > <div class="svg-icon">${unsafeHTML(homeIcon)}</div> </button> </div> `; }
// ===== Templates and Styles ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/floating-menu/floating-menu.ts#L172-L226
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowModalAuth.constructor
constructor() { super(); this.modelSetMap = { palm: false, gpt: false }; this.modelMessageMap = { palm: 'Verifying...', gpt: 'Verifying...' }; }
// ===== Lifecycle Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/modal-auth/modal-auth.ts#L41-L53
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowModalAuth.submitButtonClicked
initData = async () => {}
// ===== Custom Methods ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/modal-auth/modal-auth.ts
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowModalAuth.render
render() { const getInputButtonLabel = (model: Model) => { if (this.modelSetMap[model]) { return 'Edit'; } else { return 'Add'; } }; return html` <div class="modal-auth"> <div class="dialog-window"> <div class="header">Enter At Least an LLM API Key</div> <div class="content"> <div class="row"> <span class="info-text"> <strong>PaLM 2</strong> (<a href="https://makersuite.google.com/app/apikey" target="_blank" >reference</a >) </span> <div class="input-form"> <input id="api-input-palm" placeholder="API Key" /> <button class="primary" @click="${() => this.submitButtonClicked('palm')}" > ${getInputButtonLabel('palm')} </button> </div> <div class="message" id="message-palm"> ${this.modelMessageMap['palm']} </div> </div> <div class="row"> <span class="info-text"> <strong>GPT 3.5</strong> (<a href="https://platform.openai.com/docs/guides/gpt" target="_blank" >reference</a >) </span> <div class="input-form"> <input id="api-input-gpt" placeholder="API Key" /> <button class="primary" @click="${() => this.submitButtonClicked('gpt')}" > ${getInputButtonLabel('gpt')} </button> </div> <div class="message" id="message-gpt"> ${this.modelMessageMap['gpt']} </div> </div> </div> <div class="footer"> <button class="primary" ?disabled=${!Object.values(this.modelSetMap).some(d => d)} @click="${() => this.doneButtonClicked()}" > Done </button> <button disabled>Cancel</button> </div> </div> </div> `; }
// ===== Templates and Styles ======
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/modal-auth/modal-auth.ts#L250-L323
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarPagination.constructor
constructor() { super(); }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/pagination/pagination.ts#L34-L36
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarPagination.willUpdate
willUpdate(changedProperties: PropertyValues<this>) {}
/** * This method is called before new DOM is updated and rendered * @param changedProperties Property that has been changed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/pagination/pagination.ts#L42-L42
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarPagination.initData
async initData() {}
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/pagination/pagination.ts#L47-L47
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarPagination.pageButtonClicked
pageButtonClicked(name: string) { let newPage = this.curPage; if (name === 'Prev') { if (this.curPage > 1) { newPage -= 1; } } else if (name === 'Next') { if (this.curPage < this.totalPageNum) { newPage += 1; } } else { const pageNum = parseInt(name); if (this.curPage !== pageNum) { newPage = pageNum; } } const event = new CustomEvent<number>('page-clicked', { detail: newPage, bubbles: true, composed: true }); this.dispatchEvent(event); }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/pagination/pagination.ts#L52-L75
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarPagination.getPageButtonTemplate
getPageButtonTemplate = (name: string) => { return html` <button class="page-button" ?is-cur-page=${this.curPage === parseInt(name)} @click=${() => this.pageButtonClicked(name)} > ${name} </button>`; }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/pagination/pagination.ts
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
NightjarPagination.render
render() { // Compose the pagination let pagination = html``; if (this.totalPageNum <= this.pageWindowSize) { for (let i = 0; i < Math.max(this.totalPageNum, 1); i++) { pagination = html`${pagination} ${this.getPageButtonTemplate(`${i + 1}`)}`; } } else { const paginationPad = Math.floor((this.pageWindowSize - 1) / 2); let pageMin = this.curPage - paginationPad; let pageMax = this.curPage + paginationPad; if (pageMin < 1) { pageMin = 1; pageMax = this.pageWindowSize; } else if (pageMax > this.totalPageNum) { pageMin = this.totalPageNum - this.pageWindowSize + 1; pageMax = this.totalPageNum; } if (this.curPage > 1) { pagination = html`${pagination} ${this.getPageButtonTemplate('Prev')} `; } if (pageMin > 1) { pagination = html`${pagination} ${this.getPageButtonTemplate('1')}`; if (pageMin > 2) { pagination = html`${pagination} <span>...</span>`; } } for (let i = pageMin; i < pageMax + 1; i++) { pagination = html`${pagination} ${this.getPageButtonTemplate(i.toString())} `; } if (pageMax < this.totalPageNum) { if (pageMax < this.totalPageNum - 1) { pagination = html`${pagination}<span>...</span>`; } pagination = html`${pagination} ${this.getPageButtonTemplate(this.totalPageNum.toString())}`; } if (this.curPage < this.totalPageNum) { pagination = html`${pagination} ${this.getPageButtonTemplate('Next')} `; } } return html` <div class="pagination">${pagination}</div> `; }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/pagination/pagination.ts#L93-L146
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelCommunity.constructor
constructor() { super(); }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-community/panel-community.ts#L95-L97
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelCommunity.willUpdate
willUpdate(changedProperties: PropertyValues<this>) { if (changedProperties.has('is-shown') && this['is-shown']) { if (this.popularTags.length > 0) { this.updateMaxTagsOneLine(); } } }
/** * This method is called before new DOM is updated and rendered * @param changedProperties Property that has been changed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-community/panel-community.ts#L103-L109
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelCommunity.initData
async initData() {}
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-community/panel-community.ts#L116-L116
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelCommunity.updateMaxTagsOneLine
async updateMaxTagsOneLine() { const popularTagsElement = await this.popularTagsElementPromise; if (!this.panelElement) { throw Error('A queried element is not initialized.'); } const tagsBBox = popularTagsElement.getBoundingClientRect(); const tempTags = document.createElement('div'); this.panelElement.appendChild(tempTags); tempTags.style.setProperty('visibility', 'hidden'); tempTags.style.setProperty('position', 'absolute'); tempTags.style.setProperty('width', `${tagsBBox.width}px`); tempTags.classList.add('popular-tags'); const specialTag = document.createElement('span'); specialTag.classList.add('tag', 'expand-tag'); specialTag.innerHTML = ` <span class="svg-icon" >${this.isPopularTagListExpanded ? shrinkIcon : expandIcon}</span > more`; tempTags.appendChild(specialTag); const initHeight = tempTags.getBoundingClientRect().height; for ( let i = 0; i < Math.min(MAX_POPULAR_TAGS, this.popularTags.length); i++ ) { const curTag = document.createElement('tag'); curTag.classList.add('tag'); curTag.innerText = this.popularTags[i].tag; tempTags.appendChild(curTag); const curHeight = tempTags.getBoundingClientRect().height; if (curHeight > initHeight) { if (this.maxTagsOneLine !== i) { this.maxTagsOneLine = i; } break; } } tempTags.remove(); }
/** * Determine how many popular tags to show so that the tags element has only one line */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-community/panel-community.ts#L121-L167
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelCommunity.popularTagListToggled
popularTagListToggled() { this.isPopularTagListExpanded = !this.isPopularTagListExpanded; }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-community/panel-community.ts#L172-L174
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelCommunity.render
render() { // Create the tag list let popularTagList = html``; const curMaxTag = this.isPopularTagListExpanded ? Math.min(MAX_POPULAR_TAGS, this.popularTags.length) : this.maxTagsOneLine; for (const tag of this.popularTags.slice(0, curMaxTag)) { popularTagList = html`${popularTagList} <span class="tag" ?is-selected="${this.curSelectedTag === tag.tag}" @click=${() => this.tagClicked(tag.tag)} >${tag.tag}</span >`; } const specialTag = html`<span class="tag expand-tag" @click=${() => { this.popularTagListToggled(); }} ><span class="svg-icon" >${unsafeHTML( this.isPopularTagListExpanded ? shrinkIcon : expandIcon )}</span > ${this.isPopularTagListExpanded ? 'less' : 'more'}</span >`; // Compose the prompt cards let promptCards = html``; for (let i = 0; i < NUM_CARDS_PER_PAGE; i++) { const curIndex = (this.curPage - 1) * NUM_CARDS_PER_PAGE + i; if (curIndex > this.remotePrompts.length - 1) { break; } const curPromptData = this.remotePrompts[curIndex]; promptCards = html`${promptCards} <wordflow-prompt-card .promptData=${curPromptData} .curSelectedTag=${this.curSelectedTag} @click=${() => { this.promptCardClicked(curPromptData); }} @tag-clicked=${(e: CustomEvent<string>) => this.promptCardTagClickedHandler(e)} ></wordflow-prompt-card> `; } return html` <div class="panel-community"> <div class="header"> <div class="header-top"> <span class="name" >${this.remotePrompts.length}${this.remotePromptManager .promptIsSubset ? '+' : ''} Public Prompts</span > <span class="filter" ?is-hidden=${this.curSelectedTag === ''} >tagged <span class="tag show-cross" is-selected="" @click=${() => this.tagClicked(this.curSelectedTag)} >${this.curSelectedTag} <span class="svg-icon">${unsafeHTML(crossIcon)}</span> </span></span > <div class="header-toggle"> <span @click=${() => this.headerModeButtonClicked('popular')} ?is-active=${this.curMode === 'popular'} >Popular</span > <span @click=${() => this.headerModeButtonClicked('new')} ?is-active=${this.curMode === 'new'} >New</span > </div> </div> <div class="header-bottom"> <div class="header-tag-list"> <span class="name">Popular tags</span> <div class="popular-tags">${popularTagList} ${specialTag}</div> </div> </div> </div> <div class="prompt-content"> <div class="prompt-loader" ?is-hidden=${this.remotePrompts.length > 0 && !this.isWaitingForQueryResponse} > <div class="loader-container"> <span class="label">Loading Prompts</span> <div class="circle-loader"></div> </div> </div> <div class="prompt-container">${promptCards}</div> <div class="pagination" ?no-show=${this.remotePrompts.length <= NUM_CARDS_PER_PAGE} > <nightjar-pagination curPage=${this.curPage} totalPageNum=${Math.ceil( this.remotePrompts.length / NUM_CARDS_PER_PAGE )} pageWindowSize=${PAGINATION_WINDOW} @page-clicked=${(e: CustomEvent<number>) => this.pageClickedHandler(e)} ></nightjar-pagination> </div> <div class="prompt-modal hidden"> <wordflow-prompt-viewer .promptData=${this.selectedPrompt ? this.selectedPrompt : getEmptyPromptDataRemote()} .curSelectedTag=${this.curSelectedTag} @close-clicked=${() => this.modalCloseClickHandler()} ></wordflow-prompt-viewer> </div> </div> </div> `; }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-community/panel-community.ts#L290-L423
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.constructor
constructor() { super(); }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L114-L116
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.willUpdate
willUpdate(changedProperties: PropertyValues<this>) {}
/** * This method is called before new DOM is updated and rendered * @param changedProperties Property that has been changed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L133-L133
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.initData
async initData() {}
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L138-L138
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.promptCardClicked
promptCardClicked(promptData: PromptDataLocal) { if ( this.promptModalElement === undefined || this.promptContentElement === undefined ) { throw Error('promptModalElement is undefined.'); } this.shouldCreateNewPrompt = false; this.selectedPrompt = promptData; this.promptModalElement.style.setProperty( 'top', `${this.promptContentElement.scrollTop}px` ); this.promptModalElement.classList.remove('hidden'); }
//==========================================================================||
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L144-L158
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.promptContainerScrolled
async promptContainerScrolled() { if ( this.promptContainerElement === undefined || this.promptLoaderElement === undefined ) { throw Error('promptContainerElement is undefined'); } const isAtBottom = this.promptContainerElement.scrollHeight - this.promptContainerElement.scrollTop <= this.promptContainerElement.clientHeight + 5; if (isAtBottom && this.maxPromptCount < this.localPrompts.length) { // Keep track the original scroll position const previousScrollTop = this.promptContainerElement.scrollTop; // Show the loader for a while this.promptLoaderElement.classList.remove('hidden', 'no-display'); await new Promise<void>(resolve => { setTimeout(() => { resolve(); }, 800); }); this.maxPromptCount += promptCountIncrement; await this.updateComplete; // Hide the loader this.promptLoaderElement.classList.add('hidden'); // Restore the scroll position this.promptContainerElement.scrollTop = previousScrollTop; } if (this.maxPromptCount >= this.localPrompts.length) { this.promptLoaderElement.classList.add('no-display'); } }
/** * Event handler for scroll event. Load more items when the user scrolls to * the bottom. */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L164-L202
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.promptCardDragStarted
promptCardDragStarted(e: DragEvent) { this.isDraggingPromptCard = true; const target = e.target as WordflowPromptCard; target.classList.add('dragging'); document.body.style.setProperty('cursor', 'grabbing'); this.hoveringPromptCardIndex = null; // Set the current prompt to data transfer if (e.dataTransfer) { e.dataTransfer.dropEffect = 'copy'; e.dataTransfer.effectAllowed = 'copy'; e.dataTransfer.setData( 'newPromptData', JSON.stringify(target.promptData) ); } // Mimic the current slot width let slotWidth = 200; if (this.shadowRoot) { const favPrompt = this.shadowRoot.querySelector( '.fav-prompt-slot' ) as HTMLElement; slotWidth = favPrompt.getBoundingClientRect().width; } // Set the dragging image const tempFavSlot = document.createElement('div'); tempFavSlot.classList.add('fav-prompt-slot'); tempFavSlot.setAttribute('is-temp', 'true'); tempFavSlot.style.setProperty('width', `${slotWidth}px`); const miniCard = document.createElement('div'); miniCard.classList.add('prompt-mini-card'); const icon = document.createElement('span'); icon.classList.add('icon'); icon.innerText = target.promptData.icon; const title = document.createElement('span'); title.classList.add('title'); title.innerText = target.promptData.title; miniCard.appendChild(icon); miniCard.appendChild(title); tempFavSlot.appendChild(miniCard); // Need to add the temp element to body, because it seems safari has some // problems when using elements in a shadow element as drag image document.body.appendChild(tempFavSlot); this.draggingImageElement = tempFavSlot; e.dataTransfer?.setDragImage(tempFavSlot, 10, 10); }
/** * Event handler for drag starting from the prompt card * @param e Drag event */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L208-L261
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.promptCardDragEnded
promptCardDragEnded(e: DragEvent) { this.isDraggingPromptCard = false; const target = e.target as WordflowPromptCard; target.classList.remove('dragging'); document.body.style.removeProperty('cursor'); // Remove the temporary slot element this.draggingImageElement?.remove(); this.draggingImageElement = null; }
/** * Event handler for drag ending from the prompt card * @param e Drag event */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L267-L276
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.favPromptSlotDropped
favPromptSlotDropped(e: DragEvent, index: number) { if (e.dataTransfer) { const newPromptDataString = e.dataTransfer.getData('newPromptData'); const newPromptData = JSON.parse(newPromptDataString) as PromptDataLocal; this.favPrompts[index] = newPromptData; const newFavPrompts = structuredClone(this.favPrompts); newFavPrompts[index] = newPromptData; this.promptManager.setFavPrompt(index, newPromptData); } // Cancel the drag event because dragleave would not be fired after drop const currentTarget = e.currentTarget as HTMLDivElement; currentTarget.classList.remove('drag-over'); e.preventDefault(); }
/** * Copy prompt data to the favorite prompt slot * @param e Drag event * @param index Index of the current fav prompt slot */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L293-L307
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.menuIconMouseEntered
menuIconMouseEntered(e: MouseEvent, button: 'edit' | 'delete' | 'remove') { const target = e.currentTarget as HTMLElement; let content = ''; switch (button) { case 'edit': { content = 'Edit'; break; } case 'delete': { content = 'Delete'; break; } case 'remove': { content = 'Remove favorite prompt'; break; } default: { console.error(`Unknown button ${button}`); } } tooltipMouseEnter(e, content, 'top', this.tooltipConfig, 200, target, 10); }
/** * Event handler for mouse entering the menu bar button * @param e Mouse event * @param button Button name */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L352-L375
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.menuIconMouseLeft
menuIconMouseLeft() { tooltipMouseLeave(this.tooltipConfig, 0); }
/** * Event handler for mouse leaving the info icon in each filed */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L380-L382
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.menuDeleteClicked
menuDeleteClicked(promptData: PromptDataLocal) { if (this.confirmDialogComponent === undefined) { throw Error('confirmDialogComponent is undefined'); } const dialogInfo: DialogInfo = { header: 'Delete Prompt', message: 'Are you sure you want to delete this prompt? This action cannot be undone.', yesButtonText: 'Delete', actionKey: 'delete-prompt-local' }; this.confirmDialogComponent.show(dialogInfo, () => { this.promptManager.deletePrompt(promptData); }); }
/** * Delete the current prompt. */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L387-L403
09840c4b7b4434152c83b55c5d47ab85d367e772
wordflow
github_2023
poloclub
typescript
WordflowPanelLocal.searchBarEntered
searchBarEntered(e: InputEvent) { const inputElement = e.currentTarget as HTMLInputElement; const query = inputElement.value; if (query.length > 0) { if (!this.showSearchBarCancelButton) { // Record the total number of local prompts this.totalLocalPrompts = this.localPrompts.length; } this.showSearchBarCancelButton = true; } else { this.showSearchBarCancelButton = false; } if (this.searchBarDebounceTimer !== null) { clearTimeout(this.searchBarDebounceTimer); this.searchBarDebounceTimer = null; } this.searchBarDebounceTimer = setTimeout(() => { this.promptManager.searchPrompt(query); this.searchBarDebounceTimer = null; }, 150); }
/** * Handler for the search bar input event * @param e Input event */
https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L409-L432
09840c4b7b4434152c83b55c5d47ab85d367e772