repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
extension-bootc | github_2023 | podman-desktop | typescript | getPodmanCli | function getPodmanCli(): string {
const customBinaryPath = getCustomBinaryPath();
if (customBinaryPath) {
return customBinaryPath;
}
if (isWindows()) {
return 'podman.exe';
}
return 'podman';
} | // Below functions are borrowed from the podman extension | https://github.com/podman-desktop/extension-bootc/blob/d5bbd58a824131ca533ababcc2e7b35ff86c264b/packages/backend/src/machine-utils.ts#L154-L164 | d5bbd58a824131ca533ababcc2e7b35ff86c264b |
extension-bootc | github_2023 | podman-desktop | typescript | handleStdError | function handleStdError(e: unknown): void {
if (e instanceof Error && 'stderr' in e) {
throw new Error(typeof e.stderr === 'string' ? e.stderr : 'Unknown error');
} else {
throw new Error('Unknown error');
}
} | // Error handling function | https://github.com/podman-desktop/extension-bootc/blob/d5bbd58a824131ca533ababcc2e7b35ff86c264b/packages/backend/src/vm-manager.ts#L305-L311 | d5bbd58a824131ca533ababcc2e7b35ff86c264b |
extension-bootc | github_2023 | podman-desktop | typescript | aggregateLeaves | function aggregateLeaves(object: unknown): string[] {
if (!object) {
return [];
} else if (typeof object === 'string') {
return [object];
} else if (Array.isArray(object)) {
return object.flatMap(element => aggregateLeaves(element));
} else if (typeof object === 'object') {
return Object.values(object).flatMap(value => aggregateLeaves(value));
} else {
return [];
}
} | // Aggregate all leaves of a given object | https://github.com/podman-desktop/extension-bootc/blob/d5bbd58a824131ca533ababcc2e7b35ff86c264b/packages/frontend/src/lib/upstream/search-util.ts#L34-L46 | d5bbd58a824131ca533ababcc2e7b35ff86c264b |
cella | github_2023 | cellajs | typescript | isPGliteDatabase | const isPGliteDatabase = (_db: unknown): _db is PgliteDatabase => !!env.PGLITE; | // import { sdk } from './tracing'; | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/index.ts#L16-L16 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | docs | const docs = (app: OpenAPIHono<Env>) => {
const registry = app.openAPIRegistry;
const tags = commonModulesList.concat(appModulesList);
registry.registerComponent('securitySchemes', 'cookieAuth', {
type: 'apiKey',
in: 'cookie',
name: `${config.slug}-session-${config.apiVersion}`,
description:
"Authentication cookie. Copy the cookie from your network tab and paste it here. If you don't have it, you need to sign in or sign up first.",
});
app.doc31('/openapi.json', {
servers: [{ url: config.backendUrl }],
info: {
title: `${config.name} API`,
version: config.apiVersion,
description: config.apiDescription,
},
openapi: '3.1.0',
tags,
security: [{ cookieAuth: [] }],
});
app.get(
'/docs',
apiReference({
defaultHttpClient: {
targetKey: 'node',
clientKey: 'axios',
},
spec: {
url: 'openapi.json',
},
}),
);
}; | /**
* Generate OpenAPI documentation using hono/zod-openapi and scalar/hono-api-reference
*
* @link https://github.com/scalar/scalar/blob/main/documentation/configuration.md
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/lib/docs.ts#L31-L67 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | sendSSE | const sendSSE = (userId: string, eventName: string, data: Record<string, unknown>): void => {
const stream = streams.get(userId);
if (!stream) return;
stream.writeSSE({
event: eventName,
data: JSON.stringify(data),
retry: 5000,
});
}; | // SSE is used to send real-time updates to the client. Useful for simple updates such as an updated entity or a notification. | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/lib/sse.ts#L4-L13 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | isOAuthEnabled | function isOAuthEnabled(provider: EnabledOauthProvider): boolean {
if (!enabledStrategies.includes('oauth')) return false;
return enabledOauthProviders.includes(provider);
} | // Check if oauth provider is enabled by config | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/auth/handlers.ts#L62-L65 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | isAuthStrategy | const isAuthStrategy = (strategy: string): strategy is (typeof allSupportedStrategies)[number] => {
const [, ...elseStrategies] = supportedAuthStrategies;
const allSupportedStrategies = [...supportedOauthProviders, ...elseStrategies];
return (allSupportedStrategies as string[]).includes(strategy);
}; | // Type guard to check if strategy is supported | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/auth/helpers/session.ts#L19-L23 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | validateAuthStrategy | const validateAuthStrategy = (strategy: string) => (isAuthStrategy(strategy) ? strategy : null); | // Validate auth strategy | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/auth/helpers/session.ts#L26-L26 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | fetchMenuItemsForSection | const fetchMenuItemsForSection = async (section: EntityRelations) => {
let submenu: MenuItem[] = [];
const mainTable = entityTables[section.entity];
const mainEntityIdField = entityIdFields[section.entity];
const entity = await db
.select({
slug: mainTable.slug,
id: mainTable.id,
createdAt: mainTable.createdAt,
modifiedAt: mainTable.modifiedAt,
organizationId: membershipSelect.organizationId,
name: mainTable.name,
entity: mainTable.entity,
thumbnailUrl: mainTable.thumbnailUrl,
membership: membershipSelect,
})
.from(mainTable)
.where(and(eq(membershipsTable.userId, user.id), eq(membershipsTable.type, section.entity)))
.orderBy(asc(membershipsTable.order))
.innerJoin(membershipsTable, eq(membershipsTable[mainEntityIdField], mainTable.id));
// If the section has a submenu, fetch the submenu items
if (section.subEntity) {
const subTable = entityTables[section.subEntity];
const subEntityIdField = entityIdFields[section.subEntity];
submenu = await db
.select({
slug: subTable.slug,
id: subTable.id,
createdAt: subTable.createdAt,
modifiedAt: subTable.modifiedAt,
organizationId: membershipSelect.organizationId,
name: subTable.name,
entity: subTable.entity,
thumbnailUrl: subTable.thumbnailUrl,
membership: membershipSelect,
})
.from(subTable)
.where(and(eq(membershipsTable.userId, user.id), eq(membershipsTable.type, section.subEntity)))
.orderBy(asc(membershipsTable.order))
.innerJoin(membershipsTable, eq(membershipsTable[subEntityIdField], subTable.id));
}
return entity.map((entity) => ({
...entity,
submenu: submenu.filter((p) => p.membership[mainEntityIdField] === entity.id),
}));
}; | // Fetch function for each menu section, including handling submenus | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/me/handlers.ts#L72-L121 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | data | const data = async () => {
const result = await entityRelations.reduce(
async (accPromise, section) => {
const acc = await accPromise;
if (!memberships.length) {
acc[section.menuSectionName] = [];
return acc;
}
// Fetch menu items for the current section
acc[section.menuSectionName] = await fetchMenuItemsForSection(section);
return acc;
},
Promise.resolve({} as UserMenu),
);
return result;
}; | // Build the menu data asynchronously | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/me/handlers.ts#L124-L141 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | AdaptedMembershipAdapter.adapt | adapt(memberships: any[]): Membership[] {
return memberships.map((m) => ({
contextName: m.type?.toLowerCase() || '',
contextKey: m[`${m.type?.toLowerCase() || ''}Id`],
roleName: m.role,
ancestors: {
organization: m.organizationId,
},
}));
} | // biome-ignore lint/suspicious/noExplicitAny: The format of the membership object may vary. | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/permissions/permission-manager.ts#L46-L55 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | AdaptedSubjectAdapter.adapt | adapt(s: any): Subject {
return {
name: s.entity,
key: s.id,
ancestors: {
organization: s.organizationId,
},
};
} | // biome-ignore lint/suspicious/noExplicitAny: The format of the subject can vary depending on the subject. | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/permissions/permission-manager.ts#L69-L77 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | getGitCommandType | function getGitCommandType(command: string): GitCommandType {
if (command.startsWith('merge')) return 'merge';
if (command.startsWith('diff')) return 'diff';
return 'other';
} | // Helper to determine the type of Git command for custom handling | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/create-cella/src/utils/run-git-command.ts#L11-L15 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | isGitCommandSuccess | function isGitCommandSuccess(gitCommand: GitCommandType, code: number | null, errOutput: string): boolean {
if (gitCommand === 'merge') return code === 0 || (code === 1 && !errOutput);
if (gitCommand === 'diff') return code === 0 || (code === 2 && !errOutput);
return code === 0;
} | // Helper to check if a Git command is successful | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/create-cella/src/utils/run-git-command.ts#L18-L22 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | extractFromJson | async function extractFromJson(configFile: string): Promise<Config> {
try {
const fileContent = await readFile(configFile, 'utf-8');
const config: Config = JSON.parse(fileContent);
return extractConfig(config);
} catch (error) {
return { divergedFile: null, ignoreFile: null, ignoreList: [], forks: [], problems: [`Error parsing JSON file: ${error}`] };
}
} | // Function to extract paths from .json (simple key-value pairs) | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/config-file.ts#L20-L29 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | extractUsingDynamicImport | async function extractUsingDynamicImport(configFile: string): Promise<Config> {
try {
const { config } = await import(resolve(configFile)) as { config: Config };
return extractConfig(config);
} catch (error) {
return { divergedFile: null, ignoreFile: null, ignoreList: [], forks: [], problems: [`Error dynamically importing JS/TS file: ${error}`] };
}
} | // Function to extract paths using dynamic import for ES modules | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/config-file.ts#L32-L40 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | fileExists | async function fileExists(filePath: string): Promise<boolean> {
try {
await access(filePath);
return true;
} catch {
return false;
}
} | // Helper function to check if a file exists | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L10-L17 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | extractFromIgnoreFile | async function extractFromIgnoreFile(ignoreFile: string): Promise<string[]> {
const content = await readFile(ignoreFile, 'utf-8');
return content.split(/\r?\n/).filter(Boolean);
} | // Extract patterns from the ignore file | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L20-L23 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | extractFromIgnoreList | function extractFromIgnoreList(ignoreList: IgnoreList): string[] {
return Array.isArray(ignoreList)
? ignoreList
: ignoreList
? ignoreList.split(',')
: [];
} | // Extract patterns from the ignore list | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L26-L32 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | patternToRegex | function patternToRegex(pattern: string): RegExp {
// Escape special regex characters and convert wildcards
const escapedPattern = pattern
.replace(/([.*+?^${}()|[\]\\])/g, '\\$1') // Escape special characters
.replace(/\\\*/g, '.*') // Convert '*' to '.*'
.replace(/\\\?/g, '.'); // Convert '?' to '.'
return new RegExp(`^${escapedPattern}$`);
} | // Helper function to convert ignore patterns to regular expressions | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L48-L56 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | getGitCommandType | function getGitCommandType(command: string): GitCommandType {
if (command.startsWith('merge')) return 'merge';
if (command.startsWith('diff')) return 'diff';
return 'other';
} | // Helper to determine the type of Git command for custom handling | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/run-git-command.ts#L11-L15 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | isGitCommandSuccess | function isGitCommandSuccess(gitCommand: GitCommandType, code: number | null, errOutput: string): boolean {
if (gitCommand === 'merge') return code === 0 || (code === 1 && !errOutput);
if (gitCommand === 'diff') return code === 0 || (code === 2 && !errOutput);
return code === 0;
} | // Helper to check if a Git command is successful | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/run-git-command.ts#L18-L22 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useBodyClass | function useBodyClass(classMappings: { [key: string]: boolean }) {
// Memoize classMappings to prevent unnecessary re-renders
const stableClassMappings = useMemo(() => classMappings, [JSON.stringify(classMappings)]);
useEffect(() => {
const bodyClassList = document.body.classList;
const classNames = Object.keys(stableClassMappings);
// Use a for loop to add/remove classes
for (let i = 0; i < classNames.length; i++) {
const className = classNames[i];
if (stableClassMappings[className]) {
if (!bodyClassList.contains(className)) bodyClassList.add(className);
} else {
if (bodyClassList.contains(className)) bodyClassList.remove(className);
}
}
// Cleanup: remove all added classes on unmount
return () => {
for (let i = 0; i < classNames.length; i++) {
const className = classNames[i];
if (bodyClassList.contains(className)) bodyClassList.remove(className);
}
};
}, [stableClassMappings]);
} | /**
* Custom hook to conditionally add/remove body classes based on the provided class mappings.
*
* This hook allows you to dynamically update the body's class list based on a set of class mappings.
* It will add classes to the body if their corresponding value in `classMappings` is `true`, and remove them if `false`.
* The hook also cleans up the added classes when the component is unmounted.
*
* @param classMappings - An object where keys are class names and values are booleans indicating whether the class should be applied or not.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-body-class.ts#L12-L38 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | getMatchedBreakpoints | const getMatchedBreakpoints = () => {
const width = window.innerWidth;
let matched = sortedBreakpoints[0]; // Default to first breakpoint
for (let i = 1; i < sortedBreakpoints.length; i++) {
const prevBreakpointSize = Number.parseInt(breakpoints[sortedBreakpoints[i - 1]], 10);
const currentBreakpointSize = Number.parseInt(breakpoints[sortedBreakpoints[i]], 10);
if (width > currentBreakpointSize) {
matched = sortedBreakpoints[i];
} else if (width >= prevBreakpointSize && width < currentBreakpointSize) {
matched = sortedBreakpoints[i];
break;
}
}
return matched;
}; | // Function to get the matched breakpoint based on window width | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-breakpoints.tsx#L13-L29 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | updateGlobalBreakpoint | const updateGlobalBreakpoint = () => {
const newBreakpoint = getMatchedBreakpoints();
if (newBreakpoint !== currentBreakpoint) {
currentBreakpoint = newBreakpoint;
for (const listener of listeners) {
listener(newBreakpoint);
}
}
}; | // Function to update global breakpoint state (runs only when necessary) | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-breakpoints.tsx#L32-L40 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useDoubleClick | const useDoubleClick = ({
ref,
latency = 300,
excludeIds = [],
allowedTargets = [],
onSingleClick = () => null,
onDoubleClick = () => null,
}: UseDoubleClickOptions) => {
useEffect(() => {
const clickRef = ref.current;
if (!clickRef) return;
let clickCount = 0;
const handleClick = (e: Event) => {
const targetElement = e.target as HTMLElement | null;
// Ensure targetElement is not null before accessing its properties
if (!targetElement) return;
let isExcluded = false;
let parentElement: HTMLElement | null = targetElement;
while (parentElement) {
if (excludeIds.includes(parentElement.id)) {
isExcluded = true;
break;
}
parentElement = parentElement.parentElement;
}
// Ignore the click if it matches an allowed target or if it's excluded
if ((allowedTargets.length > 0 && !allowedTargets.includes(targetElement.localName)) || isExcluded) {
return;
}
// Update the type of the event parameter to Event
clickCount += 1;
setTimeout(() => {
if (clickCount === 1)
onSingleClick(e as MouseEvent); // Cast the event to MouseEvent
else if (clickCount === 2) onDoubleClick(e as MouseEvent); // Cast the event to MouseEvent
clickCount = 0;
}, latency);
};
// Add event listener for click events
clickRef.addEventListener('click', handleClick);
// Remove event listener
return () => {
clickRef.removeEventListener('click', handleClick);
};
});
}; | /**
* A simple React hook for differentiating single and double clicks on the same component.
*
* @param ref - Dom node to watch for double clicks
* @param latency - The amount of time (in milliseconds) to wait before differentiating a single from a double click, default 300
* @param onSingleClick - A callback function for single click events
* @param onDoubleClick - A callback function for double click events
* @param allowedTargets - Set a Lover case element name that allow to be tracked by hook
* @param excludeIds - Set a element id that excluded from tracking by hook
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-double-click.tsx#L22-L76 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useFocusById | const useFocusById = (id: string) => {
useEffect(() => {
const element = document.getElementById(id);
if (!element) return;
element.focus();
}, [id]);
}; | /**
* Hook to focus an element by its ID.
*
* @param id - The ID of the element to focus.
*
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-focus-by-id.tsx#L9-L15 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useHideElementsById | const useHideElementsById = (ids: string[]): void => {
useEffect(() => {
const hiddenElements: HTMLElement[] = [];
for (let i = 0; i < ids.length; i++) {
const element = document.getElementById(ids[i]);
if (element) {
element.style.display = 'none';
hiddenElements.push(element);
}
}
return () => {
for (let i = 0; i < hiddenElements.length; i++) {
hiddenElements[i].style.display = '';
}
};
}, [ids]);
}; | /**
* useHideElementsById - A custom React hook to hide elements by their IDs.
*
* @param ids - An array of element IDs to hide.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hide-elements-by-id.tsx#L8-L26 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useLazyComponent | function useLazyComponent<T extends ComponentType<any>>(importFunc: () => Promise<{ default: T }>, delay: number): LazyExoticComponent<T> | null {
const [Component, setComponent] = useState<LazyExoticComponent<T> | null>(null);
useEffect(() => {
const timer = setTimeout(() => {
importFunc().then((module) => {
const LazyComponent = lazy(() => Promise.resolve(module));
setComponent(LazyComponent);
});
}, delay);
return () => clearTimeout(timer);
}, [importFunc, delay]);
return Component;
} | /**
* Lazily loads a component after a specified delay.
*
* @param importFunc - Function returning a promise for the component.
* @param delay - Delay in milliseconds before loading.
* @returns Lazily loaded component.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-lazy-component.tsx#L11-L26 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useScrollTo | const useScrollTo = (scrollToRef: React.RefObject<HTMLElement>) => {
useEffect(() => {
if (scrollToRef.current) {
window.scrollTo({
top: scrollToRef.current.offsetTop,
});
}
}, [scrollToRef]);
}; | /**
* Custom hook to scroll to a specific HTML element.
* It automatically scrolls the window to the element's position when the reference is updated.
*
* @param scrollToRef - A ref pointing to the HTML element to scroll to.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-scroll-to.tsx#L9-L17 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | useSearchParams | const useSearchParams = <T extends Record<string, string | string[] | undefined>>({
from,
defaultValues,
saveDataInSearch = true,
}: SearchParams<T>) => {
const navigate = useNavigate();
const params = useParams(from ? { from, strict: true } : { strict: false });
const search = useSearch(from ? { from, strict: true } : { strict: false });
// Memoize merged search params with default values
const mergedSearch = useMemo(
() =>
({
...defaultValues,
...search,
}) as T,
[defaultValues, search],
);
// State to hold the current search parameters
const [currentSearch, setCurrentSearch] = useState<T>(mergedSearch);
const setSearch = (newValues: Partial<T>) => {
const updatedSearch = { ...currentSearch, ...newValues };
for (const key of objectKeys(updatedSearch)) {
const currentValue = updatedSearch[key];
// Handle empty or undefined values by setting to default
if (currentValue === '' || currentValue === undefined) {
updatedSearch[key] = defaultValues?.[key] ?? (undefined as T[keyof T]);
}
// Join array values into a string
if (Array.isArray(updatedSearch[key])) {
updatedSearch[key] = (
updatedSearch[key].length ? (updatedSearch[key].length === 1 ? updatedSearch[key][0] : updatedSearch[key].join('_')) : undefined
) as T[keyof T];
}
}
// Check if any search parameters have changed
const hasChanges = Object.keys(updatedSearch).some((key) => updatedSearch[key] !== currentSearch[key]);
if (hasChanges) {
setCurrentSearch(updatedSearch);
if (saveDataInSearch) {
navigate({
replace: true,
params,
resetScroll: false,
to: '.',
search: (prev) => ({
...prev,
...updatedSearch,
}),
});
}
}
};
// Sync default values on mount if necessary
useEffect(() => {
if (!defaultValues) return;
navigate({
replace: true,
params,
resetScroll: false,
to: '.',
search: (prev) => ({
...prev,
...defaultValues,
}),
});
}, []);
// Update current search state when URL search changes
useEffect(() => {
if (!saveDataInSearch || JSON.stringify(currentSearch) === JSON.stringify(mergedSearch)) return;
setCurrentSearch(mergedSearch);
}, [mergedSearch]);
return { search: currentSearch, setSearch };
}; | /**
* Hook to manage and synchronize search parameters (query string) with the URL.
*
* @template T - The type of search parameters (query string).
* @param from - The route identifier (optional). If provided, the hook is scoped to that route.
* @param defaultValues - Default values for search parameters (optional).
* @param saveDataInSearch - A flag (default: `true`) that controls whether changes to search parameters should be saved in the URL.
*
* @returns An object with:
* - `search`: The current search parameters (query string).
* - `setSearch`: A function to update the search parameters and sync with the URL.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-search-params.tsx#L26-L109 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | parseHotkey | function parseHotkey(hotkey: string): Hotkey {
const keys =
hotkey === '+'
? ['+']
: hotkey
.toLowerCase()
.split('+')
.map((part) => part.trim());
const modifiers: KeyboardModifiers = {
alt: keys.includes('alt'),
ctrl: keys.includes('ctrl'),
meta: keys.includes('meta'),
mod: keys.includes('mod'),
shift: keys.includes('shift'),
};
// Keys that are reserved for modifiers
const reservedKeys = ['alt', 'ctrl', 'meta', 'shift', 'mod'];
// Find the non-modifier key
const freeKey = keys.find((key) => !reservedKeys.includes(key));
return {
...modifiers,
key: freeKey,
};
} | // Parses a hotkey string into a Hotkey object with modifiers and a key | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L16-L43 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | isExactHotkey | function isExactHotkey(hotkey: Hotkey, event: KeyboardEvent): boolean {
const { alt, ctrl, meta, mod, shift, key } = hotkey;
const { altKey, ctrlKey, metaKey, shiftKey, key: pressedKey } = event;
// Check modifiers
if (alt !== altKey || (mod && !(ctrlKey || metaKey)) || ctrl !== ctrlKey || meta !== metaKey || shift !== shiftKey) {
return false;
}
// Check the actual key press
if (key && (pressedKey.toLowerCase() === key.toLowerCase() || event.code.replace('Key', '').toLowerCase() === key.toLowerCase())) {
return true;
}
return false;
} | // Checks if the given KeyboardEvent matches the specified hotkey | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L46-L61 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | getHotkeyMatcher | function getHotkeyMatcher(hotkey: string): CheckHotkeyMatch {
return (event) => isExactHotkey(parseHotkey(hotkey), event);
} | // check if a KeyboardEvent matches the specified hotkey string | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L64-L66 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | shouldFireEvent | function shouldFireEvent(event: KeyboardEvent, tagsToIgnore: string[], triggerOnContentEditable = false) {
if (event.target instanceof HTMLElement) {
if (triggerOnContentEditable) {
return !tagsToIgnore.includes(event.target.tagName);
}
return !event.target.isContentEditable && !tagsToIgnore.includes(event.target.tagName);
}
return true;
} | // Determines whether the event should trigger the hotkey handler based on the target element and settings | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L75-L83 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | formatRowData | const formatRowData = <R extends Row>(row: R, column: Column) => {
// Handle special cases
if ((column.key === 'adminCount' || column.key === 'memberCount') && 'counts' in row && 'memberships' in row.counts) {
const key = column.key.replace('Count', 's');
return row.counts.memberships[key];
}
const date = dayjs(row[column.key]);
if (date.isValid()) {
return date.format('lll');
}
return row[column.key];
}; | // Format data for a single row based on column configuration | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L101-L112 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | formatBodyData | const formatBodyData = <R extends Row>(rows: R[], columns: Column[]): (string | number)[][] => {
return rows.map((row) => columns.map((column) => formatRowData(row, column)));
}; | // Format the body data based on column definitions | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L115-L117 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | filterColumns | const filterColumns = (column: Column) => {
if ('visible' in column && column.key !== 'checkbox-column') return column.visible;
return false;
}; | // Filter columns based on visibility | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L120-L123 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | serialiseCellValue | function serialiseCellValue(value: unknown) {
if (typeof value === 'string') {
const formattedValue = value.replace(/"/g, '""');
return formattedValue.includes(',') ? `"${formattedValue}"` : formattedValue;
}
return value;
} | // Serialize cell values for CSV export | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L126-L132 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | downloadFile | function downloadFile(fileName: string, data: Blob) {
const downloadLink = document.createElement('a');
downloadLink.download = fileName;
const url = URL.createObjectURL(data);
downloadLink.href = url;
downloadLink.click();
URL.revokeObjectURL(url);
} | // Trigger file download in the browser | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L135-L142 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | prepareFilesForOffline | const prepareFilesForOffline = async (files: { [key: string]: UppyFile<UppyMeta, UppyBody> }) => {
console.warn('Files will be stored offline in indexedDB.');
// Save to local storage asynchronously
await LocalFileStorage.addFiles(files);
// Prepare successful files for manual `complete` event
const successfulFiles = Object.values(files);
return successfulFiles;
}; | // Prepare files for offline storage | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/imado.ts#L63-L72 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | fallbackMessages | const fallbackMessages = (t: (typeof i18n)['t']) => ({
400: t('error:bad_request_action'),
401: t('error:unauthorized_action'),
403: t('error:forbidden_action'),
404: t('error:not_found'),
429: t('error:too_many_requests'),
}); | /**
* Fallback messages for common 400 errors
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/query-client.ts#L13-L19 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | handleOnlineStatus | function handleOnlineStatus() {
onlineManager.setOnline(navigator.onLine);
} | /**
* Handle online status
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/router.ts#L11-L13 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | createIDBPersister | function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
return {
persistClient: async (client: PersistedClient) => {
await set(idbValidKey, client);
},
restoreClient: async () => {
return await get<PersistedClient>(idbValidKey);
},
removeClient: async () => {
await del(idbValidKey);
},
} as Persister;
} | /**
* Create an IndexedDB persister for react-query
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/router.ts#L47-L59 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | fetchFile | const fetchFile = async () => {
try {
const file = await LocalFileStorage.getFile(key);
if (file && isMounted.current) {
const blob = new Blob([file.data], { type: fileType || 'application/octet-stream' });
const newUrl = URL.createObjectURL(blob);
setBlobUrl(key, newUrl);
setFileUrl(newUrl);
}
} catch (error) {
console.error('Error fetching file from FileStorage:', error);
}
}; | // Fetch the file from indexedDB and create a blob URL | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/attachments/use-local-file.ts#L30-L42 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | parseRawAttachment | const parseRawAttachment = (rawAttachment: RawAttachment): Attachment => {
const columnEntries = Object.entries(attachmentsTableColumns);
const attachment = {} as unknown as Attachment;
for (const key of objectKeys(rawAttachment)) {
const columnEntry = columnEntries.find(([, columnName]) => columnName === key);
if (!columnEntry) continue;
const columnName = columnEntry[0] as keyof Attachment;
attachment[columnName] = rawAttachment[key] as never;
}
return attachment;
}; | // TODO use comments in this file and explain code better | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/attachments/table/helpers/use-sync.ts#L42-L52 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | openUploadDialog | const openUploadDialog = () => {
if (!onlineManager.isOnline()) return toaster(t('common:action.offline.text'), 'warning');
dialog(
<Suspense>
<UploadUppy
isPublic
uploadType="personal"
plugins={['webcam', 'image-editor']}
imageMode="avatar"
callback={(result) => {
const url = result[0].url;
if (url) setUrl(url);
dialog.remove(true, 'upload-image');
} | // Open the upload dialog | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/attachments/upload/upload-avatar.tsx | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | OauthOptions | const OauthOptions = ({ actionType = 'signIn' }: OauthOptionsProps) => {
const { t } = useTranslation();
const { mode } = useThemeStore();
const { token, redirect } = useSearch({ from: AuthenticateRoute.id });
const [loading, setLoading] = useState(false);
const redirectPath = redirect?.startsWith('/') ? redirect : config.defaultRedirectPath;
const actionText = actionType === 'signIn' ? t('common:sign_in') : actionType === 'signUp' ? t('common:sign_up') : t('common:continue');
const authenticateWithProvider = async (url: string) => {
setLoading(true);
let providerUrl = `${url}?redirect=${redirectPath}`;
if (token) providerUrl += `&token=${token}`;
window.location.assign(providerUrl);
};
if (config.enabledOauthProviders.length < 1) return null;
return (
<div data-mode={mode} className="group flex flex-col space-y-2">
{config.enabledOauthProviders.map((provider) => {
// Map provider data
const providerData = mapOauthProviders.find((p) => p.id === provider);
if (!providerData) return;
return (
<Button
loading={loading}
key={provider}
type="button"
variant="outline"
className="gap-1"
onClick={() => authenticateWithProvider(providerData.url)}
>
<img
data-provider={provider}
src={`/static/images/${provider}-icon.svg`}
alt={provider}
className="w-4 h-4 mr-1 data-[provider=github]:group-data-[mode=dark]:invert"
loading="lazy"
/>
<span>
{actionText} {t('common:with').toLowerCase()} {t(providerData.name)}
</span>
</Button>
);
})}
</div>
);
}; | /**
* Display OAuth options to sign in, sign up, accept invitation
*
* @param actionType The action type to perform
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/auth/oauth-options.tsx#L31-L83 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | PassKeyOption | const PassKeyOption = ({ email, actionType = 'signIn' }: PassKeyOptionProps) => {
const { t } = useTranslation();
const navigate = useNavigate();
const { mode } = useThemeStore();
const { redirect } = useSearch({ from: AuthenticateRoute.id });
const redirectPath = redirect?.startsWith('/') ? redirect : config.defaultRedirectPath;
const successCallback = () => {
navigate({ to: redirectPath, replace: true });
};
return (
<div data-mode={mode} className="group flex flex-col space-y-2">
<Button type="button" onClick={() => passkeyAuth(email, successCallback)} variant="plain" className="w-full gap-1.5">
<Fingerprint size={16} />
<span>
{actionType === 'signIn' ? t('common:sign_in') : t('common:sign_up')} {t('common:with').toLowerCase()} {t('common:passkey').toLowerCase()}
</span>
</Button>
</div>
);
}; | // TODO: split passkeyAuth into separate file | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/auth/passkey-option.tsx#L17-L39 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | SignOut | const SignOut = () => {
const { t } = useTranslation();
const navigate = useNavigate();
useEffect(() => {
signOutUser().then(() => {
flushStoresAndCache();
toaster(t('common:success.signed_out'), 'success');
navigate({ to: '/about', replace: true });
});
}, []);
return null;
}; | // Sign out user and clear all stores and query cache | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/auth/sign-out.tsx#L24-L37 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | isAllowedSlashMenu | const isAllowedSlashMenu = (item: string, allowedTypes: (CellaCustomBlockTypes | BasicBlockTypes)[]) => {
const allowedBlockTypes: readonly string[] = allowedTypes;
const allowedType = menusTitleToAllowedType[item as MenusItemsTitle];
return allowedType && allowedBlockTypes.includes(allowedType);
}; | // Filter function to check if the MenusItemsTitle has an allowed type | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/blocknote/helpers.tsx#L35-L39 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | handleDragStart | const handleDragStart = ({ dataTransfer, clientY }: React.DragEvent) => {
blockDragStart?.({ dataTransfer, clientY }, block);
}; | // Wrapper to match the signature of onDragStart | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/blocknote/custom-side-menu/drag-handle-button.tsx#L39-L41 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | handleButtonClick | const handleButtonClick = (e: React.MouseEvent) => e.preventDefault(); | // Prevent form submission when clicking the drag handle button | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/blocknote/custom-side-menu/drag-handle-button.tsx#L44-L44 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | setSortColumns | const setSortColumns = (newSortColumns: SortColumn[]) => {
if (newSortColumns.length === 0) return setSearch({ sort: undefined, order: undefined });
setSearch({
sort: newSortColumns[0].columnKey,
order: newSortColumns[0].direction === 'ASC' ? 'asc' : 'desc',
});
}; | // Use setSearch to set sort and order in URL | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/data-table/sort-columns.ts#L16-L22 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | SheetsStateObserver.notifySubscribers | subscribe = (subscriber: (action: SheetAction & SheetT) => void) => {
this.subscribers.push(subscriber);
return () => {
this.subscribers = this.subscribers.filter((sub) => sub !== subscriber);
};
} | // Remove a sheet by its ID or clear all sheets (with optionally an exluded) and notify subscribers | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/sheeter/state.ts | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | reconnect | const reconnect = () => {
if (source) source.close(); // Close old if it exists
const newSource = createSource(true);
setSource(newSource);
}; | // Closes old source, creates new | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/sse/provider.tsx#L19-L23 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | skipStep | const skipStep = (e: { preventDefault: () => void }) => {
e.preventDefault();
if (onDefaultBoardingSteps[activeStep].id === 'organization' && !hasOrganizations) {
dialog(<SkipOrganization />, {
className: 'md:max-w-xl',
title: `${t('common:skip')} ${t('common:create_resource', { resource: t('common:organization') }).toLowerCase()}`,
description: t('common:skip_org_creation.text'),
id: 'skip_org_creation',
});
return;
} | // Ask to confirm | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/home/onboarding/footer.tsx#L25-L35 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | backStep | const backStep = (e: { preventDefault: () => void }) => {
e.preventDefault();
prevStep();
}; | // prevent accidental submit | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/home/onboarding/footer.tsx#L40-L43 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | updateCounts | const updateCounts = (newSelected: InvitedMember[], newTotal: number | undefined) => {
if (newTotal !== total) setTotal(newTotal);
if (!arraysHaveSameElements(selected, newSelected)) setSelected(newSelected);
}; | // Update total and selected counts | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/memberships/invited-members-table/index.tsx#L35-L38 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | onRowsChange | const onRowsChange = (changedRows: Member[], { indexes, column }: RowsChangeData<Member>) => {
if (!onlineManager.isOnline()) return toaster(t('common:action.offline.text'), 'warning');
if (column.key !== 'role') return setRows(changedRows);
// If role is changed, update membership
for (const index of indexes) {
updateMemberMembership.mutateAsync(
{ ...changedRows[index].membership, orgIdOrSlug: organizationId, idOrSlug: entity.slug, entityType },
{
onSuccess(data, variables, context) {
queryClient.getMutationDefaults(membersKeys.update()).onSuccess?.(data, variables, context);
toaster(t('common:success.update_item', { item: t('common:role') }), 'success');
},
onError(error, variables, context) {
queryClient.getMutationDefaults(membersKeys.update()).onError?.(error, variables, context);
toaster('Error updating role', 'error');
},
},
);
}
setRows(changedRows);
}; | // Update rows | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/memberships/members-table/table.tsx#L47-L69 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | filterItems | const filterItems = (items: UserMenuItem[]): UserMenuItem[] =>
items.flatMap((item) => {
const isMatch = item.name.toLowerCase().includes(lowerCaseTerm);
const filteredSubmenu = item.submenu ? filterItems(item.submenu) : [];
return isMatch ? [item, ...filteredSubmenu] : filteredSubmenu;
}); | // Flatten menu items and submenus | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/navigation/menu-sheet/search-input.tsx#L29-L34 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | onRowsChange | const onRowsChange = (changedRows: User[], { indexes, column }: RowsChangeData<User>) => {
if (!onlineManager.isOnline()) return toaster(t('common:action.offline.text'), 'warning');
for (const index of indexes)
if (column.key === 'role') {
const newUser = changedRows[index];
const updateInfo = { idOrSlug: newUser.id, role: newUser.role };
updateUserRole(updateInfo, {
onSuccess: (updatedUser) => {
mutateQuery.update([updatedUser]);
toaster(t('common:success.update_item', { item: t('common:role') }), 'success');
},
onError: () => toaster('Error updating role', 'error'),
});
}
setRows(changedRows);
}; | // Update user role | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/users/table/table.tsx#L36-L51 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | prefetchMenuItems | const prefetchMenuItems = async (items: UserMenuItem[]) => {
for (const item of items) {
if (isCancelled) return;
if (item.membership.archived) continue; // Skip this item but continue with others
for (const query of queriesToMap(item)) {
prefetchQuery(query);
await waitFor(500);
if (isCancelled) return;
}
if (item.submenu) await prefetchMenuItems(item.submenu);
}
}; | // Recursively prefetch menu items | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/index.tsx#L44-L58 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | deepEqual | const deepEqual = (value1: any, value2: any): boolean => {
// Check if both values are the same reference
if (value1 === value2) return true;
// If either value is null or not an object, they're not equal
if (value1 === null || value2 === null || typeof value1 !== 'object' || typeof value2 !== 'object') return false;
// Check if both values are arrays
if (Array.isArray(value1) !== Array.isArray(value2)) return false;
// If both are arrays, compare each element recursively
if (Array.isArray(value1)) {
if (value1.length !== value2.length) return false;
for (let i = 0; i < value1.length; i++) if (!deepEqual(value1[i], value2[i])) return false;
return true;
}
// Otherwise, both values are objects, so compare their keys and values
const keys1 = Object.keys(value1);
const keys2 = Object.keys(value2);
if (keys1.length !== keys2.length) return false;
for (const key of keys1) if (!keys2.includes(key) || !deepEqual(value1[key], value2[key])) return false;
return true;
}; | // biome-ignore lint/suspicious/noExplicitAny: any is used to infer the type of the compare values | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/helpers/compare-query-keys.ts#L20-L46 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | getExact | const getExact = <T>(passedQueryKey: QueryKey): [QueryKey, InfiniteQueryData<T> | QueryData<T> | undefined][] => {
return [[passedQueryKey, queryClient.getQueryData<InfiniteQueryData<T> | QueryData<T>>(passedQueryKey)]];
}; | /**
* Retrieves query data for a given query key.
*
* @param passedQueryKey - Query key to search for similar queries.
* @returns An array with query key and its corresponding data.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/helpers/mutate-query.ts#L122-L124 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | updateArrayItems | const updateArrayItems = <T extends ItemData>(items: T[], dataItems: T[], action: QueryDataActions) => {
// Determine how to handle dataItems in the items array based on action type
switch (action) {
case 'create': {
// Filter out already existing items based on their IDs
const existingIds = items.map(({ id }) => id);
const newItems = dataItems.filter((i) => !existingIds.includes(i.id));
// Concatenate to add only new entries
return [...newItems, ...items];
}
case 'update':
// update existing items in dataItems
return items.map((item) => dataItems.find((i) => i.id === item.id) ?? item);
case 'delete': {
// Exclude items matching IDs in dataItems
const deleteIds = dataItems.map(({ id }) => id);
return items.filter((item) => !deleteIds.includes(item.id));
}
case 'updateMembership': {
// Update the membership field if it exists
return items.map((item) => {
if (item.membership) {
const updatedMembership = dataItems.find((i) => i.id === item.membership?.id);
return updatedMembership ? { ...item, membership: { ...item.membership, ...updatedMembership } } : item;
}
return item; // Return unchanged if no membership exists
});
}
default:
// Return items unchanged if action is unrecognized
return items;
}
}; | /**
* Helper function to update an array of items based on the action.
*
* @param items - Current items to update.
* @param dataItems - Items to merge into current items.
* @param action - `"create" | "update" | "delete" | "updateMembership"`
* @returns The updated array of items.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/hooks/use-mutate-query-data/helpers.ts#L128-L163 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | updateItem | const updateItem = <T extends ItemData>(prevItem: T, newItem: T, action: QueryDataActions) => {
// Determine how to handle dataItems in the items array based on action type
switch (action) {
case 'update':
return { ...prevItem, ...newItem };
case 'updateMembership': {
// update the membership field in dataItems
return {
...prevItem,
membership: { ...prevItem.membership, ...newItem },
};
}
default:
return prevItem;
}
}; | /**
* Helper function to update a single item based on the action.
*
* @param prevItem - Previous item to update.
* @param newItem - New item to merge.
* @param action - `"create" | "update" | "delete" | "updateMembership"`
* @returns The updated item.
*/ | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/hooks/use-mutate-query-data/helpers.ts#L173-L189 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | dataMutation | function dataMutation(items: ItemData[] | EntityData[] | ContextEntityData[], action: QueryDataActions, entity?: Entity, keyToOperateIn?: string) {
const passedQueryData = queryClient.getQueryData(passedQueryKey);
const passedQuery: [QueryKey, unknown] = [passedQueryKey, passedQueryData];
const similarQueries = queryClient.getQueriesData({ queryKey: passedQueryKey });
const queriesToWorkOn = passedQueryData ? [passedQuery] : similarQueries;
for (const [queryKey, queryData] of queriesToWorkOn) {
// Determine type of query and apply action
if (isQueryData(queryData)) changeQueryData(queryKey, items, action);
if (isInfiniteQueryData(queryData)) changeInfiniteQueryData(queryKey, items, action);
if (entity && isArbitraryQueryData(queryData)) changeArbitraryQueryData(queryKey, items as EntityData[], action, entity, keyToOperateIn);
}
// Invalidate queries if invalidateKeyGetter is provided and the action is included in useInvalidateOnActions
if (invalidateKeyGetter && useInvalidateOnActions?.includes(action)) {
for (const item of items) {
const queryKeyToInvalidate = invalidateKeyGetter(item);
queryClient.invalidateQueries({ queryKey: queryKeyToInvalidate });
}
}
} | // mutation function | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/hooks/use-mutate-query-data/index.tsx#L39-L60 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
cella | github_2023 | cellajs | typescript | generateNumber | function generateNumber(id: string) {
if (!id) return null;
for (let i = id.length - 1; i >= 0; i--) {
const char = id[i].toLowerCase();
if (Number.parseInt(char) >= 0 && Number.parseInt(char) <= 9) {
return Number.parseInt(char) % 10;
}
if (char >= 'a' && char <= 'z') {
return (char.charCodeAt(0) - 'a'.charCodeAt(0)) % 10;
}
}
return null;
} | // Generate a number from a string (ie. to choose a color) | https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/utils/number-to-color-class.ts#L4-L17 | 99695fe84ed346d91cd7e35b804c7ccce9e96f7b |
prettify-ts | github_2023 | mylesmmurphy | typescript | getTypeTree | function getTypeTree (type: ts.Type, depth: number, visited: Set<ts.Type>): TypeTree {
const typeName = checker.typeToString(type, undefined, typescript.TypeFormatFlags.NoTruncation)
const apparentType = checker.getApparentType(type)
if (depth >= options.maxDepth || isPrimitiveType(type) || options.skippedTypeNames.includes(typeName)) return {
kind: 'basic',
typeName
}
if (visited.has(type)) return {
kind: 'basic',
typeName
}
visited.add(type)
if (type.isUnion()) return {
kind: 'union',
typeName,
excessMembers: Math.max(0, type.types.length - options.maxUnionMembers),
types: type.types.slice(0, options.maxUnionMembers).sort(sortUnionTypes).map(t => getTypeTree(t, depth, new Set(visited)))
}
if (type?.symbol?.flags & typescript.SymbolFlags.EnumMember && type.symbol.parent) {
return {
kind: 'enum',
typeName,
member: `${type.symbol.parent.name}.${type.symbol.name}`
}
}
if (type.isIntersection()) return {
kind: 'intersection',
typeName,
types: type.types.map(t => getTypeTree(t, depth, new Set(visited)))
}
if (typeName.startsWith('Promise<')) {
if (!options.unwrapPromises) return { kind: 'basic', typeName }
const typeArgument = checker.getTypeArguments(apparentType as ts.TypeReference)[0]
return {
kind: 'promise',
typeName,
type: typeArgument ? getTypeTree(typeArgument, depth, new Set(visited)) : { kind: 'basic', typeName: 'void' }
}
}
const callSignatures = apparentType.getCallSignatures()
if (callSignatures.length > 0) {
if (!options.unwrapFunctions) {
depth = options.maxDepth
}
const signatures: TypeFunctionSignature[] = callSignatures.map(signature => {
const returnType = getTypeTree(checker.getReturnTypeOfSignature(signature), depth, new Set(visited))
const parameters = signature.parameters.map(symbol => {
const declaration = symbol.declarations?.[0]
const isRestParameter = Boolean(declaration && typescript.isParameter(declaration) && !!declaration.dotDotDotToken)
return {
name: symbol.getName(),
isRestParameter,
type: getTypeTree(checker.getTypeOfSymbol(symbol), depth, new Set(visited))
}
})
return { returnType, parameters }
})
return {
kind: 'function',
typeName,
signatures
}
}
if (checker.isArrayType(type)) {
if (!options.unwrapArrays) return { kind: 'basic', typeName }
const arrayType = checker.getTypeArguments(type as ts.TypeReference)[0]
const elementType: TypeTree = arrayType
? getTypeTree(arrayType, depth, new Set(visited))
: { kind: 'basic', typeName: 'any' }
return {
kind: 'array',
typeName,
readonly: type.getSymbol()?.getName() === 'ReadonlyArray',
elementType
}
}
if (apparentType.isClassOrInterface() || (apparentType.flags & typescript.TypeFlags.Object)) {
if (propertiesCount >= options.maxProperties) return { kind: 'basic', typeName }
// Resolve how many properties to show based on the maxProperties option
const remainingProperties = options.maxProperties - propertiesCount
const depthMaxProps = depth >= 1 ? options.maxSubProperties : options.maxProperties
const allowedPropertiesCount = Math.min(depthMaxProps, remainingProperties)
let typeProperties = apparentType.getProperties()
if (options.hidePrivateProperties) {
typeProperties = typeProperties.filter((symbol) => isPublicProperty(symbol))
}
const publicProperties = typeProperties.slice(0, allowedPropertiesCount)
propertiesCount += publicProperties.length
const excessProperties = Math.max(typeProperties.length - publicProperties.length, 0)
const properties: TypeProperty[] = publicProperties.map(symbol => {
const symbolType = checker.getTypeOfSymbol(symbol)
return {
name: symbol.getName(),
readonly: isReadOnly(symbol),
type: getTypeTree(symbolType, depth + 1, new Set(visited)) // Add depth for sub-properties
}
})
const stringIndexType = type.getStringIndexType()
if (stringIndexType) {
properties.push({
name: '[key: string]',
readonly: isReadOnly(stringIndexType.symbol),
type: getTypeTree(stringIndexType, depth + 1, new Set(visited))
})
}
const numberIndexType = type.getNumberIndexType()
if (numberIndexType) {
properties.push({
name: '[key: number]',
readonly: isReadOnly(numberIndexType.symbol),
type: getTypeTree(numberIndexType, depth + 1, new Set(visited))
})
}
return {
kind: 'object',
typeName,
properties,
excessProperties
}
}
return {
kind: 'basic',
typeName
}
} | /**
* Recursively get type information by building a TypeTree object from the given type
*/ | https://github.com/mylesmmurphy/prettify-ts/blob/4a4414df3aad32f34265d01b5881d57d720a61ac/packages/typescript-plugin/src/type-tree/index.ts#L75-L225 | 4a4414df3aad32f34265d01b5881d57d720a61ac |
prettify-ts | github_2023 | mylesmmurphy | typescript | sortUnionTypes | function sortUnionTypes (a: ts.Type, b: ts.Type): number {
const primitiveTypesOrder = ['string', 'number', 'bigint', 'boolean', 'symbol']
const falsyTypesOrder = ['null', 'undefined']
const aIntrinsicName = isIntrinsicType(a) ? a.intrinsicName : ''
const bIntrinsicName = isIntrinsicType(b) ? b.intrinsicName : ''
const aPrimitiveIndex = primitiveTypesOrder.indexOf(aIntrinsicName)
const bPrimitiveIndex = primitiveTypesOrder.indexOf(bIntrinsicName)
const aFalsyIndex = falsyTypesOrder.indexOf(aIntrinsicName)
const bFalsyIndex = falsyTypesOrder.indexOf(bIntrinsicName)
// If both types are primitive, sort based on the order in primitiveTypesOrder
if (aPrimitiveIndex !== -1 && bPrimitiveIndex !== -1) {
return aPrimitiveIndex - bPrimitiveIndex
}
// If one type is primitive and the other is not, the primitive type should come first
if (aPrimitiveIndex !== -1) {
return -1
}
if (bPrimitiveIndex !== -1) {
return 1
}
// If both types are falsy, sort based on the order in falsyTypesOrder
if (aFalsyIndex !== -1 && bFalsyIndex !== -1) {
return aFalsyIndex - bFalsyIndex
}
// If one type is falsy and the other is not, the falsy type should come last
if (aFalsyIndex !== -1) {
return 1
}
if (bFalsyIndex !== -1) {
return -1
}
// If neither type is primitive or falsy, maintain the original order
return 0
} | /**
* Sort union types by intrinsic types order, following ts quick info order
* Ex.
* string, number, bigint, { a: string }, null, undefined
*/ | https://github.com/mylesmmurphy/prettify-ts/blob/4a4414df3aad32f34265d01b5881d57d720a61ac/packages/typescript-plugin/src/type-tree/index.ts#L262-L303 | 4a4414df3aad32f34265d01b5881d57d720a61ac |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | CatalogManager.init | init(): void {
// Creating a json watcher
this.#jsonWatcher = new JsonWatcher(this.getUserCatalogPath(), {
version: CatalogFormat.CURRENT,
recipes: [],
models: [],
categories: [],
});
this.#jsonWatcher.onContentUpdated(content => this.onUserCatalogUpdate(content));
this.#jsonWatcher.init();
} | /**
* The init method will start a watcher on the user catalog.json
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L62-L72 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | CatalogManager.importUserModels | async importUserModels(localModels: LocalModelImportInfo[]): Promise<void> {
const userCatalogPath = this.getUserCatalogPath();
let content: ApplicationCatalog;
// check if we already have an existing user's catalog
if (fs.existsSync(userCatalogPath)) {
const raw = await promises.readFile(userCatalogPath, 'utf-8');
content = sanitize(JSON.parse(raw));
} else {
content = {
version: CatalogFormat.CURRENT,
recipes: [],
models: [],
categories: [],
};
}
// Transform local models into ModelInfo
const models: ModelInfo[] = await Promise.all(
localModels.map(async local => {
const statFile = await promises.stat(local.path);
const sha256 = crypto.createHash('sha256').update(local.path).digest('hex');
return {
id: sha256,
name: local.name,
description: `Model imported from ${local.path}`,
file: {
path: path.dirname(local.path),
file: path.basename(local.path),
size: statFile.size,
creation: statFile.mtime,
},
memory: statFile.size,
backend: local.backend ?? InferenceType.NONE,
};
}),
);
// Add all our models infos to the user's models catalog
content.models.push(...models);
// ensure parent directory exists
await promises.mkdir(path.dirname(userCatalogPath), { recursive: true });
// overwrite the existing catalog
return promises.writeFile(userCatalogPath, JSON.stringify(content, undefined, 2), 'utf-8');
} | /**
* This method is used to imports user's local models.
* @param localModels the models to imports
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L195-L241 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | CatalogManager.removeUserModel | async removeUserModel(modelId: string): Promise<void> {
const userCatalogPath = this.getUserCatalogPath();
if (!fs.existsSync(userCatalogPath)) {
throw new Error('User catalog does not exist.');
}
const raw = await promises.readFile(userCatalogPath, 'utf-8');
const content = sanitize(JSON.parse(raw));
return promises.writeFile(
userCatalogPath,
JSON.stringify(
{
version: content.version,
recipes: content.recipes,
models: content.models.filter(model => model.id !== modelId),
categories: content.categories,
},
undefined,
2,
),
'utf-8',
);
} | /**
* Remove a model from the user's catalog.
* @param modelId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L247-L270 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | CatalogManager.getUserCatalogPath | private getUserCatalogPath(): string {
return path.resolve(this.appUserDirectory, USER_CATALOG);
} | /**
* Return the path to the user catalog
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L275-L277 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | GitManager.getRepositoryStatus | async getRepositoryStatus(directory: string): Promise<{
modified: string[];
created: string[];
deleted: string[];
clean: boolean;
}> {
const status = await git.statusMatrix({
fs,
dir: directory,
});
const FILE = 0,
HEAD = 1,
WORKDIR = 2,
STAGE = 3;
const created = status.filter(row => row[HEAD] === 0 && row[WORKDIR] === 2).map(row => row[FILE]);
const deleted = status
.filter(row => row[HEAD] === 1 && (row[WORKDIR] === 0 || row[STAGE] === 0))
.map(row => row[FILE]);
const modified = status.filter(row => row[HEAD] === 1 && row[WORKDIR] === 2).map(row => row[FILE]);
const notClean = status.filter(row => row[HEAD] !== 1 || row[WORKDIR] !== 1 || row[STAGE] !== 1);
return {
modified,
created,
deleted,
clean: notClean.length === 0,
};
} | /* see https://isomorphic-git.org/docs/en/statusMatrix
*
* - The HEAD status is either absent (0) or present (1).
* - The WORKDIR status is either absent (0), identical to HEAD (1), or different from HEAD (2).
* - The STAGE status is either absent (0), identical to HEAD (1), identical to WORKDIR (2), or different from WORKDIR (3).
*
* // example StatusMatrix
* [
* ["a.txt", 0, 2, 0], // new, untracked
* ["b.txt", 0, 2, 2], // added, staged
* ["c.txt", 0, 2, 3], // added, staged, with unstaged changes
* ["d.txt", 1, 1, 1], // unmodified
* ["e.txt", 1, 2, 1], // modified, unstaged
* ["f.txt", 1, 2, 2], // modified, staged
* ["g.txt", 1, 2, 3], // modified, staged, with unstaged changes
* ["h.txt", 1, 0, 1], // deleted, unstaged
* ["i.txt", 1, 0, 0], // deleted, staged
* ["j.txt", 1, 2, 0], // deleted, staged, with unstaged-modified changes (new file of the same name)
* ["k.txt", 1, 1, 0], // deleted, staged, with unstaged changes (new file of the same name)
* ]
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/gitManager.ts#L74-L106 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ModelsManager.requestDownloadModel | async requestDownloadModel(model: ModelInfo, labels?: { [key: string]: string }): Promise<string> {
// Create a task to follow progress
const task: Task = this.createDownloadTask(model, labels);
// Check there is no existing downloader running
const existingDownloader = this.#downloaders.get(model.id);
if (!existingDownloader) {
return this.downloadModel(model, task);
}
if (existingDownloader.completed) {
task.state = 'success';
this.taskRegistry.updateTask(task);
return existingDownloader.getTarget();
}
// Propagate cancellation token from existing task to the new one
task.cancellationToken = this.taskRegistry.findTaskByLabels({ 'model-pulling': model.id })?.cancellationToken;
this.taskRegistry.updateTask(task);
// If we have an existing downloader running we subscribe on its events
return new Promise((resolve, reject) => {
const disposable = existingDownloader.onEvent(event => {
if (!isCompletionEvent(event)) return;
switch (event.status) {
case 'completed':
resolve(existingDownloader.getTarget());
break;
default:
reject(new Error(event.message));
}
disposable.dispose();
});
});
} | /**
* This method will resolve when the provided model will be downloaded.
*
* This can method can be call multiple time for the same model, it will reuse existing downloader and wait on
* their completion.
* @param model
* @param labels
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/modelsManager.ts#L253-L289 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PlaygroundV2Manager.submitSystemPrompt | private submitSystemPrompt(conversationId: string, content: string): void {
this.#conversationRegistry.submit(conversationId, {
content: content,
role: 'system',
id: this.#conversationRegistry.getUniqueId(),
timestamp: Date.now(),
} as SystemPrompt);
this.telemetry.logUsage('playground.system-prompt.create', {
modelId: getHash(this.#conversationRegistry.get(conversationId).modelId),
});
} | /**
* Add a system prompt to an existing conversation.
* @param conversationId the conversation to append the system prompt to.
* @param content the content of the system prompt
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L147-L157 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PlaygroundV2Manager.setSystemPrompt | setSystemPrompt(conversationId: string, content: string | undefined): void {
const conversation = this.#conversationRegistry.get(conversationId);
if (content === undefined || content.length === 0) {
this.#conversationRegistry.removeMessage(conversationId, conversation.messages[0].id);
this.telemetry.logUsage('playground.system-prompt.delete', {
modelId: getHash(conversation.modelId),
});
return;
}
if (conversation.messages.length === 0) {
this.submitSystemPrompt(conversationId, content);
} else if (conversation.messages.length === 1 && isSystemPrompt(conversation.messages[0])) {
this.#conversationRegistry.update(conversationId, conversation.messages[0].id, {
content,
});
this.telemetry.logUsage('playground.system-prompt.update', {
modelId: getHash(conversation.modelId),
});
} else {
throw new Error('Cannot change system prompt on started conversation.');
}
} | /**
* Given a conversation, update the system prompt.
* If none exists, it will create one, otherwise it will replace the content with the new one
* @param conversationId the conversation id to set the system id
* @param content the new system prompt to use
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L165-L188 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PlaygroundV2Manager.submit | async submit(conversationId: string, userInput: string, options?: ModelOptions): Promise<number> {
const conversation = this.#conversationRegistry.get(conversationId);
const servers = this.inferenceManager.getServers();
const server = servers.find(s => s.models.map(mi => mi.id).includes(conversation.modelId));
if (server === undefined) throw new Error('Inference server not found.');
if (server.status !== 'running') throw new Error('Inference server is not running.');
if (server.health?.Status !== 'healthy')
throw new Error(`Inference server is not healthy, currently status: ${server.health?.Status ?? 'unknown'}.`);
const modelInfo = server.models.find(model => model.id === conversation.modelId);
if (modelInfo === undefined)
throw new Error(
`modelId '${conversation.modelId}' is not available on the inference server, valid model ids are: ${server.models.map(model => model.id).join(', ')}.`,
);
this.#conversationRegistry.submit(conversation.id, {
content: userInput,
options: options,
role: 'user',
id: this.#conversationRegistry.getUniqueId(),
timestamp: Date.now(),
} as UserChat);
const client = new OpenAI({
baseURL: `http://localhost:${server.connection.port}/v1`,
apiKey: 'dummy',
});
if (!modelInfo.file?.file) throw new Error('model info has undefined file.');
const telemetry: Record<string, unknown> = {
conversationId: conversationId,
...options,
promptLength: userInput.length,
modelId: getHash(modelInfo.id),
};
// create an abort controller
const abortController = new AbortController();
const cancelTokenId = this.cancellationTokenRegistry.createCancellationTokenSource(() => {
abortController.abort('cancel');
});
client.chat.completions
.create(
{
messages: this.getFormattedMessages(conversation.id),
stream: true,
model: modelInfo.file.file,
...options,
},
{
signal: abortController.signal,
},
)
.then(response => {
// process stream async
this.processStream(conversation.id, response)
.catch((err: unknown) => {
console.error('Something went wrong while processing stream', err);
})
.finally(() => {
this.cancellationTokenRegistry.delete(cancelTokenId);
});
})
.catch((err: unknown) => {
telemetry['errorMessage'] = `${String(err)}`;
console.error('Something went wrong while creating model response', err);
this.processError(conversation.id, err).catch((err: unknown) => {
console.error('Something went wrong while processing stream', err);
});
})
.finally(() => {
this.telemetry.logUsage('playground.submit', telemetry);
});
return cancelTokenId;
} | /**
* @param conversationId
* @param userInput the user input
* @param options the model configuration
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L195-L274 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PlaygroundV2Manager.processStream | private async processStream(conversationId: string, stream: Stream<ChatCompletionChunk>): Promise<void> {
const conversation = this.#conversationRegistry.get(conversationId);
const messageId = this.#conversationRegistry.getUniqueId();
const start = Date.now();
this.#conversationRegistry.submit(conversationId, {
role: 'assistant',
choices: [],
completed: undefined,
id: messageId,
timestamp: start,
} as PendingChat);
for await (const chunk of stream) {
this.#conversationRegistry.appendChoice(conversationId, messageId, {
content: chunk.choices[0]?.delta?.content ?? '',
});
this.#conversationRegistry.setUsage(conversationId, messageId, chunk.usage as ModelUsage);
}
this.#conversationRegistry.completeMessage(conversationId, messageId);
this.telemetry.logUsage('playground.message.complete', {
duration: Date.now() - start,
modelId: getHash(conversation.modelId),
});
} | /**
* Given a Stream from the OpenAI library update and notify the publisher
* @param conversationId
* @param stream
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L295-L320 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PlaygroundV2Manager.getFormattedMessages | private getFormattedMessages(conversationId: string): ChatCompletionMessageParam[] {
const conversation = this.#conversationRegistry.get(conversationId);
if (!conversation) throw new Error(`conversation with id ${conversationId} does not exist.`);
return conversation.messages
.filter(m => isChatMessage(m))
.map(
message =>
({
name: undefined,
...message,
}) as ChatCompletionMessageParam,
);
} | /**
* Transform the ChatMessage interface to the OpenAI ChatCompletionMessageParam
* @private
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L326-L339 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.execute | execute(connection: ContainerProviderConnection, args: string[], options?: RunOptions): Promise<RunResult> {
const podman = extensions.getExtension('podman-desktop.podman');
if (!podman) {
console.warn('cannot find podman extension api');
return this.executeLegacy(args, options);
}
const podmanApi: {
exec(args: string[], options?: PodmanRunOptions): Promise<RunResult>;
} = podman.exports;
return podmanApi.exec(args, {
...options,
connection: this.getProviderContainerConnection(connection),
});
} | /**
* Execute the podman cli with the arguments provided
*
* @example
* ```
* const result = await podman.execute(connection, ['machine', 'ls', '--format=json']);
* ```
* @param connection
* @param args
* @param options
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L74-L89 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.executeSSH | executeSSH(connection: ContainerProviderConnection, args: string[], options?: RunOptions): Promise<RunResult> {
return this.execute(connection, ['machine', 'ssh', this.getNameLegacyCompatibility(connection), ...args], options);
} | /**
* Execute a command inside the podman machine
*
* @example
* ```
* const result = await podman.executeSSH(connection, ['ls', '/dev']);
* ```
* @param connection
* @param args
* @param options
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L102-L104 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.executeLegacy | protected executeLegacy(args: string[], options?: RunOptions): Promise<RunResult> {
return process.exec(getPodmanCli(), [...args], options);
} | /**
* Before 1.13, the podman extension was not exposing any api.
*
* Therefore, to support old version we need to get the podman executable ourself
* @deprecated
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L112-L114 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.getNameLegacyCompatibility | protected getNameLegacyCompatibility(connection: ContainerProviderConnection): string {
return getPodmanMachineName(connection);
} | /**
* Before 1.13, the {@link ContainerProviderConnection.name} field was used as friendly user
* field also.
*
* Therefore, we could have `Podman Machine Default` as name, where the real machine was `podman-machine-default`.
* @param connection
* @deprecated
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L124-L126 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.getContainerProviderConnectionInfo | getContainerProviderConnectionInfo(): ContainerProviderConnectionInfo[] {
const output: ContainerProviderConnectionInfo[] = [];
for (const [providerId, connections] of Array.from(this.#providers.entries())) {
output.push(
...connections.map(
(connection): ContainerProviderConnectionInfo => ({
providerId: providerId,
name: connection.name,
vmType: this.parseVMType(connection.vmType),
type: 'podman',
status: connection.status(),
}),
),
);
}
return output;
} | /**
* This method flatten the
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L135-L153 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.getProviderContainerConnection | protected getProviderContainerConnection(connection: ContainerProviderConnection): ProviderContainerConnection {
const providers: ProviderContainerConnection[] = provider.getContainerConnections();
const podmanProvider = providers
.filter(({ connection }) => connection.type === 'podman')
.find(provider => provider.connection.name === connection.name);
if (!podmanProvider) throw new Error(`cannot find podman provider with connection name ${connection.name}`);
return podmanProvider;
} | /**
* This method allow us to get the ProviderContainerConnection given a ContainerProviderConnection
* @param connection
* @protected
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L171-L180 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.getVMType | async getVMType(name?: string): Promise<VMType> {
const { stdout } = await process.exec(getPodmanCli(), ['machine', 'list', '--format', 'json']);
const parsed: unknown = JSON.parse(stdout);
if (!Array.isArray(parsed)) throw new Error('podman machine list provided a malformed response');
if (parsed.length === 0 && name) throw new Error('podman machine list provided an empty array');
// On Linux we might not have any machine
if (parsed.length === 0) return VMType.UNKNOWN;
if (parsed.length > 1 && !name)
throw new Error('name need to be provided when more than one podman machine is configured.');
let output: MachineJSON;
if (name) {
output = parsed.find(machine => typeof machine === 'object' && 'Name' in machine && machine.Name === name);
if (!output) throw new Error(`cannot find matching podman machine with name ${name}`);
} else {
output = parsed[0];
}
return this.parseVMType(output.VMType);
} | /**
* Get the VMType of the podman machine
* @param name the machine name, from {@link ContainerProviderConnection}
* @deprecated should uses the `getContainerProviderConnectionInfo()`
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L262-L282 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | PodmanConnection.getConnectionByEngineId | async getConnectionByEngineId(engineId: string): Promise<ContainerProviderConnection> {
const connections = Array.from(this.#providers.values()).flat();
for (const connection of connections) {
const infos = await containerEngine.listInfos({ provider: connection });
if (infos.length === 0) continue;
if (infos[0].engineId === engineId) return connection;
}
throw new Error('connection not found');
} | /**
* This method return the ContainerProviderConnection corresponding to an engineId
* @param engineId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L304-L313 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ApplicationManager.initApplication | private async initApplication(
connection: ContainerProviderConnection,
recipe: Recipe,
model: ModelInfo,
labels: Record<string, string> = {},
): Promise<PodInfo> {
// clone the recipe
await this.recipeManager.cloneRecipe(recipe, { ...labels, 'model-id': model.id });
// get model by downloading it or retrieving locally
let modelPath = await this.modelsManager.requestDownloadModel(model, {
...labels,
'recipe-id': recipe.id,
'model-id': model.id,
});
// build all images, one per container (for a basic sample we should have 2 containers = sample app + model service)
const recipeComponents = await this.recipeManager.buildRecipe(connection, recipe, model, {
...labels,
'recipe-id': recipe.id,
'model-id': model.id,
});
// upload model to podman machine if user system is supported
if (!recipeComponents.inferenceServer) {
modelPath = await this.modelsManager.uploadModelToPodmanMachine(connection, model, {
...labels,
'recipe-id': recipe.id,
'model-id': model.id,
});
}
// first delete any existing pod with matching labels
if (await this.hasApplicationPod(recipe.id, model.id)) {
await this.removeApplication(recipe.id, model.id);
}
// create a pod containing all the containers to run the application
return this.createApplicationPod(connection, recipe, model, recipeComponents, modelPath, {
...labels,
'recipe-id': recipe.id,
'model-id': model.id,
});
} | /**
* This method will execute the following tasks
* - git clone
* - git checkout
* - register local repository
* - download models
* - upload models
* - build containers
* - create pod
*
* @param connection
* @param recipe
* @param model
* @param labels
* @private
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L175-L218 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ApplicationManager.runApplication | protected async runApplication(podInfo: PodInfo, labels?: { [key: string]: string }): Promise<void> {
const task = this.taskRegistry.createTask('Starting AI App', 'loading', labels);
// it starts the pod
try {
await this.podManager.startPod(podInfo.engineId, podInfo.Id);
// check if all containers have started successfully
for (const container of podInfo.Containers ?? []) {
await this.waitContainerIsRunning(podInfo.engineId, container);
}
task.state = 'success';
task.name = 'AI App is running';
} catch (err: unknown) {
task.state = 'error';
task.error = String(err);
throw err;
} finally {
this.taskRegistry.updateTask(task);
}
return this.checkPodsHealth();
} | /**
* Given an ApplicationPodInfo, start the corresponding pod
* @param podInfo
* @param labels
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L225-L248 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ApplicationManager.stopApplication | async stopApplication(recipeId: string, modelId: string): Promise<PodInfo> {
// clear existing tasks
this.clearTasks(recipeId, modelId);
// get the application pod
const appPod = await this.getApplicationPod(recipeId, modelId);
// if the pod is already stopped skip
if (appPod.Status === 'Exited') {
return appPod;
}
// create a task to follow progress/error
const stoppingTask = this.taskRegistry.createTask(`Stopping AI App`, 'loading', {
'recipe-id': recipeId,
'model-id': modelId,
});
try {
await this.podManager.stopPod(appPod.engineId, appPod.Id);
stoppingTask.state = 'success';
stoppingTask.name = `AI App Stopped`;
} catch (err: unknown) {
stoppingTask.state = 'error';
stoppingTask.error = `Error removing the pod.: ${String(err)}`;
stoppingTask.name = 'Error stopping AI App';
throw err;
} finally {
this.taskRegistry.updateTask(stoppingTask);
await this.checkPodsHealth();
}
return appPod;
} | /**
* Stop the pod with matching recipeId and modelId
* @param recipeId
* @param modelId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L435-L468 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ApplicationManager.startApplication | async startApplication(recipeId: string, modelId: string): Promise<void> {
this.clearTasks(recipeId, modelId);
const pod = await this.getApplicationPod(recipeId, modelId);
return this.runApplication(pod, {
'recipe-id': recipeId,
'model-id': modelId,
});
} | /**
* Utility method to start a pod using (recipeId, modelId)
* @param recipeId
* @param modelId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L475-L483 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | ApplicationManager.removeApplication | async removeApplication(recipeId: string, modelId: string): Promise<void> {
const appPod = await this.stopApplication(recipeId, modelId);
const remoteTask = this.taskRegistry.createTask(`Removing AI App`, 'loading', {
'recipe-id': recipeId,
'model-id': modelId,
});
// protect the task
this.protectTasks.add(appPod.Id);
try {
await this.podManager.removePod(appPod.engineId, appPod.Id);
remoteTask.state = 'success';
remoteTask.name = `AI App Removed`;
// eslint-disable-next-line sonarjs/no-ignored-exceptions
} catch (err: unknown) {
remoteTask.error = 'error removing the pod. Please try to remove the pod manually';
remoteTask.name = 'Error stopping AI App';
} finally {
this.taskRegistry.updateTask(remoteTask);
}
} | /**
* Method that will stop then remove a pod corresponding to the recipe and model provided
* @param recipeId
* @param modelId
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L641-L663 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.dispose | dispose(): void {
this.cleanDisposables();
this.#servers.clear();
this.#initialized = false;
} | /**
* Cleanup the manager
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L77-L81 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.cleanDisposables | private cleanDisposables(): void {
this.#disposables.forEach(disposable => disposable.dispose());
} | /**
* Clean class disposables
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L86-L88 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.getServers | public getServers(): InferenceServer[] {
return Array.from(this.#servers.values());
} | /**
* Get the Inference servers
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L93-L95 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
podman-desktop-extension-ai-lab | github_2023 | containers | typescript | InferenceManager.get | public get(containerId: string): InferenceServer | undefined {
return this.#servers.get(containerId);
} | /**
* return an inference server
* @param containerId the containerId of the inference server
*/ | https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L101-L103 | acc28f4dac6ba1a6b6d39720e6721d150e76e5f7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.