repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
maxun | github_2023 | getmaxun | typescript | getShadowPath | const getShadowPath = (el: HTMLElement) => {
const path = [];
let current = el;
let depth = 0;
const MAX_DEPTH = 4;
while (current && depth < MAX_DEPTH) {
const rootNode = current.getRootNode();
if (rootNode instanceof ShadowRoot) {
path.unshift({
host: rootNode.host as HTMLElement,
root: rootNode,
element: current
});
current = rootNode.host as HTMLElement;
depth++;
} else {
break;
}
}
return path;
}; | // Get complete path up to document root | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1346-L1367 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | genValidAttributeFilter | function genValidAttributeFilter(element: HTMLElement, attributes: string[]) {
const attrSet = genAttributeSet(element, attributes);
return (name: string) => attrSet.has(name);
} | // Gets all attributes that aren't null and empty | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1499-L1503 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | isCharacterNumber | function isCharacterNumber(char: string) {
return char.length === 1 && char.match(/[0-9]/);
} | // isCharacterNumber | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1520-L1522 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | traverseShadowDOM | const traverseShadowDOM = (element: HTMLElement): HTMLElement => {
let current = element;
let deepest = current;
let shadowRoot = current.shadowRoot;
while (shadowRoot) {
const shadowElement = shadowRoot.elementFromPoint(x, y) as HTMLElement;
if (!shadowElement || shadowElement === current) break;
deepest = shadowElement;
current = shadowElement;
shadowRoot = current.shadowRoot;
}
return deepest;
}; | // Function to traverse shadow DOM | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1573-L1588 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getNonUniqueSelector | function getNonUniqueSelector(element: HTMLElement): string {
let selector = element.tagName.toLowerCase();
if (selector === 'td' && element.parentElement) {
// Find position among td siblings
const siblings = Array.from(element.parentElement.children);
const position = siblings.indexOf(element) + 1;
return `${selector}:nth-child(${position})`;
}
if (element.className) {
const classes = element.className.split(/\s+/).filter((cls: string) => Boolean(cls));
if (classes.length > 0) {
const validClasses = classes.filter((cls: string) => !cls.startsWith('!') && !cls.includes(':'));
if (validClasses.length > 0) {
selector += '.' + validClasses.map(cls => CSS.escape(cls)).join('.');
}
}
}
if (element.parentElement) {
// Look for identical siblings
const siblings = Array.from(element.parentElement.children);
const identicalSiblings = siblings.filter(sibling => {
if (sibling === element) return false;
let siblingSelector = sibling.tagName.toLowerCase();
const siblingClassName = typeof sibling.className === 'string' ? sibling.className : '';
if (siblingClassName) {
const siblingClasses = siblingClassName.split(/\s+/).filter(Boolean);
const validSiblingClasses = siblingClasses.filter(cls => !cls.startsWith('!') && !cls.includes(':'));
if (validSiblingClasses.length > 0) {
siblingSelector += '.' + validSiblingClasses.map(cls => CSS.escape(cls)).join('.');
}
}
return siblingSelector === selector;
});
if (identicalSiblings.length > 0) {
const position = siblings.indexOf(element) + 1;
selector += `:nth-child(${position})`;
}
}
return selector;
} | // Basic selector generation | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1637-L1683 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getNonUniqueSelector | function getNonUniqueSelector(element: HTMLElement): string {
let selector = element.tagName.toLowerCase();
if (selector === 'td' && element.parentElement) {
const siblings = Array.from(element.parentElement.children);
const position = siblings.indexOf(element) + 1;
return `${selector}:nth-child(${position})`;
}
if (element.className) {
const classes = element.className.split(/\s+/).filter(Boolean);
if (classes.length > 0) {
const validClasses = classes.filter(cls => !cls.startsWith('!') && !cls.includes(':'));
if (validClasses.length > 0) {
selector += '.' + validClasses.map(cls => CSS.escape(cls)).join('.');
}
}
}
if (element.parentElement) {
// Look for identical siblings
const siblings = Array.from(element.parentElement.children);
const identicalSiblings = siblings.filter(sibling => {
if (sibling === element) return false;
let siblingSelector = sibling.tagName.toLowerCase();
const siblingClassName = typeof sibling.className === 'string' ? sibling.className : '';
if (siblingClassName) {
const siblingClasses = siblingClassName.split(/\s+/).filter(Boolean);
const validSiblingClasses = siblingClasses.filter(cls => !cls.startsWith('!') && !cls.includes(':'));
if (validSiblingClasses.length > 0) {
siblingSelector += '.' + validSiblingClasses.map(cls => CSS.escape(cls)).join('.');
}
}
return siblingSelector === selector;
});
if (identicalSiblings.length > 0) {
const position = siblings.indexOf(element) + 1;
selector += `:nth-child(${position})`;
}
}
return selector;
} | // Generate basic selector from element's tag and classes | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1903-L1948 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getContextPath | function getContextPath(element: HTMLElement): DOMContext[] {
const path: DOMContext[] = [];
let current = element;
let depth = 0;
const MAX_DEPTH = 4;
while (current && depth < MAX_DEPTH) {
// Check for shadow DOM
const rootNode = current.getRootNode();
if (rootNode instanceof ShadowRoot) {
path.unshift({
type: 'shadow',
element: current,
container: rootNode,
host: rootNode.host as HTMLElement
});
current = rootNode.host as HTMLElement;
depth++;
continue;
}
// Check for iframe
const ownerDocument = current.ownerDocument;
const frameElement = ownerDocument?.defaultView?.frameElement as HTMLIFrameElement;
if (frameElement) {
path.unshift({
type: 'iframe',
element: current,
container: frameElement,
document: ownerDocument
});
current = frameElement;
depth++;
continue;
}
break;
}
return path;
} | // Get complete context path (both iframe and shadow DOM) | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L1686-L1727 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getNonUniqueSelector | function getNonUniqueSelector(element: HTMLElement): string {
let selector = element.tagName.toLowerCase();
if (selector === 'td' && element.parentElement) {
const siblings = Array.from(element.parentElement.children);
const position = siblings.indexOf(element) + 1;
return `${selector}:nth-child(${position})`;
}
const className = typeof element.className === 'string' ? element.className : '';
if (className) {
const classes = className.split(/\s+/).filter((cls: string) => Boolean(cls));
if (classes.length > 0) {
const validClasses = classes.filter((cls: string) => !cls.startsWith('!') && !cls.includes(':'));
if (validClasses.length > 0) {
selector += '.' + validClasses.map(cls => CSS.escape(cls)).join('.');
}
}
}
if (element.parentElement) {
// Look for identical siblings
const siblings = Array.from(element.parentElement.children);
const identicalSiblings = siblings.filter(sibling => {
if (sibling === element) return false;
let siblingSelector = sibling.tagName.toLowerCase();
const siblingClassName = typeof sibling.className === 'string' ? sibling.className : '';
if (siblingClassName) {
const siblingClasses = siblingClassName.split(/\s+/).filter(Boolean);
const validSiblingClasses = siblingClasses.filter(cls => !cls.startsWith('!') && !cls.includes(':'));
if (validSiblingClasses.length > 0) {
siblingSelector += '.' + validSiblingClasses.map(cls => CSS.escape(cls)).join('.');
}
}
return siblingSelector === selector;
});
if (identicalSiblings.length > 0) {
const position = siblings.indexOf(element) + 1;
selector += `:nth-child(${position})`;
}
}
return selector;
} | // Function to get a non-unique selector based on tag and class (if present) | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L2058-L2104 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getSelectorPath | function getSelectorPath(element: HTMLElement): string {
if (!element || !element.parentElement) return '';
const elementSelector = getNonUniqueSelector(element);
// Check for shadow DOM context
const rootNode = element.getRootNode();
if (rootNode instanceof ShadowRoot) {
const hostSelector = getNonUniqueSelector(rootNode.host as HTMLElement);
return `${hostSelector} >> ${elementSelector}`;
}
// Check for iframe context
const ownerDocument = element.ownerDocument;
const frameElement = ownerDocument?.defaultView?.frameElement as HTMLIFrameElement;
if (frameElement) {
const frameSelector = getNonUniqueSelector(frameElement);
return `${frameSelector} :>> ${elementSelector}`;
}
// Regular DOM context
const parentSelector = getNonUniqueSelector(element.parentElement);
return `${parentSelector} > ${elementSelector}`;
} | // Function to generate selector path from an element to its parent | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L2107-L2130 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getSpecialContextChildren | function getSpecialContextChildren(element: HTMLElement): HTMLElement[] {
const children: HTMLElement[] = [];
// Get shadow DOM children
const shadowRoot = element.shadowRoot;
if (shadowRoot) {
const shadowElements = Array.from(shadowRoot.querySelectorAll('*')) as HTMLElement[];
children.push(...shadowElements);
}
// Get iframe children
const iframes = Array.from(element.querySelectorAll('iframe')) as HTMLIFrameElement[];
for (const iframe of iframes) {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
if (iframeDoc) {
const iframeElements = Array.from(iframeDoc.querySelectorAll('*')) as HTMLElement[];
children.push(...iframeElements);
}
} catch (error) {
console.warn('Cannot access iframe content:', error);
continue;
}
}
return children;
} | // Function to get all children from special contexts | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L2134-L2160 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getAllDescendantSelectors | function getAllDescendantSelectors(element: HTMLElement): string[] {
let selectors: string[] = [];
// Handle regular DOM children
const children = Array.from(element.children) as HTMLElement[];
for (const child of children) {
const childPath = getSelectorPath(child);
if (childPath) {
selectors.push(childPath);
// Process regular descendants
selectors = selectors.concat(getAllDescendantSelectors(child));
// Process special context children (shadow DOM and iframes)
const specialChildren = getSpecialContextChildren(child);
for (const specialChild of specialChildren) {
const specialPath = getSelectorPath(specialChild);
if (specialPath) {
selectors.push(specialPath);
selectors = selectors.concat(getAllDescendantSelectors(specialChild));
}
}
}
}
// Handle direct special context children
const specialChildren = getSpecialContextChildren(element);
for (const specialChild of specialChildren) {
const specialPath = getSelectorPath(specialChild);
if (specialPath) {
selectors.push(specialPath);
selectors = selectors.concat(getAllDescendantSelectors(specialChild));
}
}
return selectors;
} | // Function to recursively get all descendant selectors including shadow DOM and iframes | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/selector.ts#L2163-L2199 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | promiseAllP | function promiseAllP(items: any, block: any) {
let promises: any = [];
items.forEach(function(item : any, index: number) {
promises.push( function(item,i) {
return new Promise(function(resolve, reject) {
// @ts-ignore
return block.apply(this,[item,index,resolve,reject]);
});
}(item,index))
});
return Promise.all(promises);
} | /**
* A helper function to apply a callback to the all resolved
* promises made out of an array of the items.
* @param items An array of items.
* @param block The function to call for each item after the promise for it was resolved.
* @returns {Promise<any[]>}
* @category WorkflowManagement-Storage
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/storage.ts#L71-L82 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.constructor | public constructor(socket: Socket) {
this.socket = socket;
this.registerEventHandlers(socket);
this.initializeSocketListeners();
} | /**
* The public constructor of the WorkflowGenerator.
* Takes socket for communication as a parameter and registers some important events on it.
* @param socket The socket used to communicate with the client.
* @constructor
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L76-L80 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.initializeSocketListeners | private initializeSocketListeners() {
this.socket.on('setGetList', (data: { getList: boolean }) => {
this.getList = data.getList;
});
this.socket.on('listSelector', (data: { selector: string }) => {
this.listSelector = data.selector;
})
this.socket.on('setPaginationMode', (data: { pagination: boolean }) => {
this.paginationMode = data.pagination;
})
} | /**
* Initializes the socket listeners for the generator.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L120-L130 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.addPairToWorkflowAndNotifyClient | private registerEventHandlers = (socket: Socket) => {
socket.on('save', (data) => {
const { fileName, userId, isLogin } = data;
logger.log('debug', `Saving workflow ${fileName} for user ID ${userId}`);
this.saveNewWorkflow(fileName, userId, isLogin);
});
socket.on('new-recording', () => this.workflowRecord = {
workflow: [],
});
socket.on('activeIndex', (data) => this.generatedData.lastIndex = parseInt(data));
socket.on('decision', async ({ pair, actionType, decision }) => {
const id = browserPool.getActiveBrowserId();
if (id) {
// const activeBrowser = browserPool.getRemoteBrowser(id);
// const currentPage = activeBrowser?.getCurrentPage();
if (!decision) {
switch (actionType) {
case 'customAction':
// pair.where.selectors = [this.generatedData.lastUsedSelector];
pair.where.selectors = pair.where.selectors.filter(
(selector: string) => selector !== this.generatedData.lastUsedSelector
);
break;
default: break;
}
}
// if (currentPage) {
// await this.addPairToWorkflowAndNotifyClient(pair, currentPage);
// }
}
})
socket.on('updatePair', (data) => {
this.updatePairInWorkflow(data.index, data.pair);
})
} | /**
* Adds a newly generated pair to the workflow and notifies the client about it by
* sending the updated workflow through socket.
*
* Checks some conditions for the correct addition of the pair.
* 1. The pair's action selector is already in the workflow as a different pair's where selector
* If so, the what part of the pair is added to the pair with the same where selector.
* 2. The pair's where selector is located on the page at the same time as another pair's where selector,
* having the same url. This state is called over-shadowing an already existing pair.
* If so, the pair is merged with the previous over-shadowed pair - what part is attached and
* new selector added to the where selectors. In case the over-shadowed pair is further down the
* workflow array, the new pair is added to the beginning of the workflow array.
*
* This function also makes sure to add a waitForLoadState and a generated flag
* action after every new action or pair added. The [waitForLoadState](https://playwright.dev/docs/api/class-frame#frame-wait-for-load-state)
* action waits for the networkidle event to be fired,
* and the generated flag action is used for making pausing the interpretation possible.
*
* @param pair The pair to add to the workflow.
* @param page The page to use for the state checking.
* @private
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.getLastUsedSelectorInfo | private async getLastUsedSelectorInfo(page: Page, selector: string) {
const elementHandle = await page.$(selector);
if (elementHandle) {
const tagName = await elementHandle.evaluate(el => (el as HTMLElement).tagName);
// TODO: based on tagName, send data. Always innerText won't hold true. For now, can roll.
const innerText = await elementHandle.evaluate(el => (el as HTMLElement).innerText);
return { tagName, innerText };
}
return { tagName: '', innerText: '' };
} | /**
* Returns tag name and text content for the specified selector
* used in customAction for decision modal
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L538-L548 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.updateWorkflowFile | public updateWorkflowFile = (workflowFile: WorkflowFile, meta: MetaData) => {
this.recordingMeta = meta;
const params = this.checkWorkflowForParams(workflowFile);
if (params) {
this.recordingMeta.params = params;
}
this.workflowRecord = workflowFile;
} | /**
* Enables to update the generated workflow file.
* Adds a generated flag action for possible pausing during the interpretation.
* Used for loading a recorded workflow to already initialized Generator.
* @param workflowFile The workflow file to be used as a replacement for the current generated workflow.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L688-L695 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.saveNewWorkflow | public saveNewWorkflow = async (fileName: string, userId: number, isLogin: boolean) => {
const recording = this.optimizeWorkflow(this.workflowRecord);
try {
this.recordingMeta = {
name: fileName,
id: uuid(),
createdAt: this.recordingMeta.createdAt || new Date().toLocaleString(),
pairs: recording.workflow.length,
updatedAt: new Date().toLocaleString(),
params: this.getParams() || [],
isLogin: isLogin,
}
const robot = await Robot.create({
userId,
recording_meta: this.recordingMeta,
recording: recording,
});
capture(
'maxun-oss-robot-created',
{
robot_meta: robot.recording_meta,
recording: robot.recording,
}
)
logger.log('info', `Robot saved with id: ${robot.id}`);
}
catch (e) {
const { message } = e as Error;
logger.log('warn', `Cannot save the file to the local file system ${e}`)
}
this.socket.emit('fileSaved');
} | /**
* Creates a recording metadata and stores the curren workflow
* with the metadata to the file system.
* @param fileName The name of the file.
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L703-L735 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.generateSelector | private generateSelector = async (page: Page, coordinates: Coordinates, action: ActionType) => {
const elementInfo = await getElementInformation(page, coordinates, this.listSelector, this.getList);
const selectorBasedOnCustomAction = (this.getList === true)
? await getNonUniqueSelectors(page, coordinates, this.listSelector)
: await getSelectors(page, coordinates);
if (this.paginationMode && selectorBasedOnCustomAction) {
// Chain selectors in specific priority order
const selectors = selectorBasedOnCustomAction;
const selectorChain = [
selectors?.iframeSelector?.full,
selectors?.shadowSelector?.full,
selectors?.testIdSelector,
selectors?.id,
selectors?.hrefSelector,
selectors?.accessibilitySelector,
selectors?.attrSelector
]
.filter(selector => selector !== null && selector !== undefined)
.join(',');
return selectorChain;
}
const bestSelector = getBestSelectorForAction(
{
type: action,
tagName: elementInfo?.tagName as TagName || '',
inputType: undefined,
value: undefined,
selectors: selectorBasedOnCustomAction || {},
timestamp: 0,
isPassword: false,
hasOnlyText: elementInfo?.hasOnlyText || false,
} as Action,
);
return bestSelector;
} | /**
* Uses a system of functions to generate a correct and unique css selector
* according to the action being performed.
* @param page The page to be used for obtaining the information and selector.
* @param coordinates The coordinates of the element.
* @param action The action for which the selector is being generated.
* @private
* @returns {Promise<string|null>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L746-L783 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.generateDataForHighlighter | public generateDataForHighlighter = async (page: Page, coordinates: Coordinates) => {
const rect = await getRect(page, coordinates, this.listSelector, this.getList);
const displaySelector = await this.generateSelector(page, coordinates, ActionType.Click);
const elementInfo = await getElementInformation(page, coordinates, this.listSelector, this.getList);
if (rect) {
const highlighterData = {
rect,
selector: displaySelector,
elementInfo,
// Include shadow DOM specific information
shadowInfo: elementInfo?.isShadowRoot ? {
mode: elementInfo.shadowRootMode,
content: elementInfo.shadowRootContent
} : null
};
if (this.getList === true) {
if (this.listSelector !== '') {
const childSelectors = await getChildSelectors(page, this.listSelector || '');
this.socket.emit('highlighter', { ...highlighterData, childSelectors })
} else {
this.socket.emit('highlighter', { ...highlighterData });
}
} else {
this.socket.emit('highlighter', { ...highlighterData });
}
}
} | /**
* Generates data for highlighting the element on client side and emits the
* highlighter event to the client.
* @param page The page to be used for obtaining data.
* @param coordinates The coordinates of the element.
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L792-L819 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.notifyUrlChange | public notifyUrlChange = (url: string) => {
if (this.socket) {
this.socket.emit('urlChanged', url);
}
} | /**
* Notifies the client about the change of the url if navigation
* happens after some performed action.
* @param url The new url.
* @param fromNavBar Whether the navigation is from the simulated browser's navbar or not.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L828-L832 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.notifyOnNewTab | public notifyOnNewTab = (page: Page, pageIndex: number) => {
if (this.socket) {
page.on('close', () => {
this.socket.emit('tabHasBeenClosed', pageIndex);
})
const parsedUrl = new URL(page.url());
const host = parsedUrl.hostname?.match(/\b(?!www\.)[a-zA-Z0-9]+/g)?.join('.');
this.socket.emit('newTab', host ? host : 'new tab')
}
} | /**
* Notifies the client about the new tab if popped-up
* @param page The page to be used for obtaining data.
* @param pageIndex The index of the page.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L840-L849 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.onGoBack | public onGoBack = (newUrl: string) => {
//it's safe to always add a go back action to the first rule in the workflow
this.workflowRecord.workflow[0].what.push({
action: 'goBack',
args: [{ waitUntil: 'commit' }],
});
this.notifyUrlChange(newUrl);
this.socket.emit('workflow', this.workflowRecord);
} | /**
* Generates a pair for navigating to the previous page.
* This function alone adds the pair to the workflow and notifies the client.
* It's safe to always add a go back action to the first rule in the workflow and do not check
* general conditions for adding a pair to the workflow.
* @param newUrl The previous page's url.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L859-L867 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.onGoForward | public onGoForward = (newUrl: string) => {
//it's safe to always add a go forward action to the first rule in the workflow
this.workflowRecord.workflow[0].what.push({
action: 'goForward',
args: [{ waitUntil: 'commit' }],
});
this.notifyUrlChange(newUrl);
this.socket.emit('workflow', this.workflowRecord);
} | /**
* Generates a pair for navigating to the next page.
* This function alone adds the pair to the workflow and notifies the client.
* It's safe to always add a go forward action to the first rule in the workflow and do not check
* general conditions for adding a pair to the workflow.
* @param newUrl The next page's url.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L877-L885 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.IsOverShadowingAction | private IsOverShadowingAction = async (pair: WhereWhatPair, page: Page) => {
type possibleOverShadow = {
index: number;
isOverShadowing: boolean;
}
const possibleOverShadow: possibleOverShadow[] = [];
const haveSameUrl = this.workflowRecord.workflow
.filter((p, index) => {
if (p.where.url === pair.where.url) {
possibleOverShadow.push({ index: index, isOverShadowing: false });
return true;
} else {
return false;
}
});
if (haveSameUrl.length !== 0) {
for (let i = 0; i < haveSameUrl.length; i++) {
//@ts-ignore
if (haveSameUrl[i].where.selectors && haveSameUrl[i].where.selectors.length > 0) {
//@ts-ignore
const isOverShadowing = await isRuleOvershadowing(haveSameUrl[i].where.selectors, page);
if (isOverShadowing) {
possibleOverShadow[i].isOverShadowing = true;
}
}
}
}
return possibleOverShadow;
} | /**
* Checks and returns possible pairs that would get over-shadowed by the pair
* from the current workflow.
* @param pair The pair that could be over-shadowing.
* @param page The page to be used for checking the visibility and accessibility of the selectors.
* @private
* @returns {Promise<PossibleOverShadow[]>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L895-L925 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.handleOverShadowing | private handleOverShadowing = async (pair: WhereWhatPair, page: Page, index: number): Promise<boolean> => {
const overShadowing = (await this.IsOverShadowingAction(pair, page))
.filter((p) => p.isOverShadowing);
if (overShadowing.length !== 0) {
for (const overShadowedAction of overShadowing) {
if (overShadowedAction.index === index) {
if (pair.where.selectors) {
for (const selector of pair.where.selectors) {
if (this.workflowRecord.workflow[index].where.selectors?.includes(selector)) {
break;
} else {
// add new selector to the where part of the overshadowing pair
this.workflowRecord.workflow[index].where.selectors?.push(selector);
}
}
}
// push the action automatically to the first/the closest rule which would be overShadowed
this.workflowRecord.workflow[index].what =
this.workflowRecord.workflow[index].what.concat(pair.what);
return true;
} else {
// notify client about overshadowing a further rule
return false;
}
}
}
return false;
} | /**
* General over-shadowing handler.
* Checks for possible over-shadowed pairs and if found,
* adds the pair to the workflow in the correct way.
* @param pair The pair that could be over-shadowing.
* @param page The page to be used for checking the visibility and accessibility of the selectors.
* @private
* @returns {Promise<boolean>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L937-L964 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.getBestUrl | private getBestUrl = (url: string) => {
const parsedUrl = new URL(url);
const protocol = parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'http:' ? `${parsedUrl.protocol}//` : parsedUrl.protocol;
const regex = new RegExp(/(?=.*[A-Z])/g)
// remove all params with uppercase letters, they are most likely dynamically generated
// also escapes all regex characters from the params
const search = parsedUrl.search
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.split('&').map((param, index) => {
if (!regex.test(param)) {
return param;
} else {
return '.*';
}
})
.join('&');
let bestUrl;
if (search) {
bestUrl = {
$regex: `^${protocol}${parsedUrl.host}${parsedUrl.pathname}${search}${parsedUrl.hash}`
}
} else {
bestUrl = `${protocol}${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.hash}`;
}
return bestUrl;
} | /**
* Returns the best possible url representation for a where condition according to the heuristics.
* @param url The url to be checked and possibly replaced.
* @private
* @returns {string | {$regex: string}}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L972-L997 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.checkWorkflowForParams | private checkWorkflowForParams = (workflow: WorkflowFile): string[] | null => {
// for now the where condition cannot have any params, so we're checking only what part of the pair
// where only the args part of what condition can have a parameter
for (const pair of workflow.workflow) {
for (const condition of pair.what) {
if (condition.args) {
const params: any[] = [];
condition.args.forEach((arg) => {
if (arg.$param) {
params.push(arg.$param);
}
})
if (params.length !== 0) {
return params;
}
}
}
}
return null;
} | /**
* Returns parameters if present in the workflow or null.
* @param workflow The workflow to be checked.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L1003-L1022 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.optimizeWorkflow | private optimizeWorkflow = (workflow: WorkflowFile) => {
// replace a sequence of press actions by a single fill action
let input = {
selector: '',
value: '',
type: '',
actionCounter: 0,
};
const pushTheOptimizedAction = (pair: WhereWhatPair, index: number) => {
if (input.value.length === 1) {
// when only one press action is present, keep it and add a waitForLoadState action
pair.what.splice(index + 1, 0, {
action: 'waitForLoadState',
args: ['networkidle'],
})
} else {
// when more than one press action is present, add a type action
pair.what.splice(index - input.actionCounter, input.actionCounter, {
action: 'type',
args: [input.selector, encrypt(input.value), input.type],
}, {
action: 'waitForLoadState',
args: ['networkidle'],
});
}
}
for (const pair of workflow.workflow) {
pair.what.forEach((condition, index) => {
if (condition.action === 'press') {
if (condition.args && condition.args[1]) {
if (!input.selector) {
input.selector = condition.args[0];
}
if (input.selector === condition.args[0]) {
input.actionCounter++;
if (condition.args[1].length === 1) {
input.value = input.value + condition.args[1];
} else if (condition.args[1] === 'Backspace') {
input.value = input.value.slice(0, -1);
} else if (condition.args[1] !== 'Shift') {
pushTheOptimizedAction(pair, index);
pair.what.splice(index + 1, 0, {
action: 'waitForLoadState',
args: ['networkidle'],
})
input = { selector: '', value: '', type: '', actionCounter: 0 };
}
} else {
pushTheOptimizedAction(pair, index);
input = {
selector: condition.args[0],
value: condition.args[1],
type: condition.args[2],
actionCounter: 1,
};
}
}
} else {
if (input.value.length !== 0) {
pushTheOptimizedAction(pair, index);
// clear the input
input = { selector: '', value: '', type: '', actionCounter: 0 };
}
}
});
}
return workflow;
} | /**
* A function for workflow optimization once finished.
* @param workflow The workflow to be optimized.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L1028-L1099 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.getParams | public getParams = (): string[] | null => {
return this.checkWorkflowForParams(this.workflowRecord);
} | /**
* Returns workflow params from the stored metadata.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L1104-L1106 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowGenerator.clearLastIndex | public clearLastIndex = () => {
this.generatedData.lastIndex = null;
} | /**
* Clears the last generated data index.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Generator.ts#L1111-L1113 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | processWorkflow | function processWorkflow(workflow: WorkflowFile, checkLimit: boolean = false): WorkflowFile {
const processedWorkflow = JSON.parse(JSON.stringify(workflow)) as WorkflowFile;
processedWorkflow.workflow.forEach((pair) => {
pair.what.forEach((action) => {
// Handle limit validation for scrapeList action
if (action.action === 'scrapeList' && checkLimit && Array.isArray(action.args) && action.args.length > 0) {
const scrapeConfig = action.args[0];
if (scrapeConfig && typeof scrapeConfig === 'object' && 'limit' in scrapeConfig) {
if (typeof scrapeConfig.limit === 'number' && scrapeConfig.limit > 5) {
scrapeConfig.limit = 5;
}
}
}
// Handle decryption for type and press actions
if ((action.action === 'type' || action.action === 'press') && Array.isArray(action.args) && action.args.length > 1) {
try {
const encryptedValue = action.args[1];
if (typeof encryptedValue === 'string') {
const decryptedValue = decrypt(encryptedValue);
action.args[1] = decryptedValue;
} else {
logger.log('error', 'Encrypted value is not a string');
action.args[1] = '';
}
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.log('error', `Failed to decrypt input value: ${errorMessage}`);
action.args[1] = '';
}
}
});
});
return processedWorkflow;
} | /**
* Decrypts any encrypted inputs in the workflow. If checkLimit is true, it will also handle the limit validation for scrapeList action.
* @param workflow The workflow to decrypt.
* @param checkLimit If true, it will handle the limit validation for scrapeList action.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Interpreter.ts#L13-L49 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowInterpreter.constructor | constructor(socket: Socket) {
this.socket = socket;
} | /**
* A public constructor taking a socket instance for communication with the client.
* @param socket Socket.io socket instance enabling communication with the client (frontend) side.
* @constructor
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Interpreter.ts#L117-L119 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowInterpreter.subscribeToPausing | public subscribeToPausing = () => {
this.socket.on('pause', () => {
this.interpretationIsPaused = true;
});
this.socket.on('resume', () => {
this.interpretationIsPaused = false;
if (this.interpretationResume) {
this.interpretationResume();
this.socket.emit('log', '----- The interpretation has been resumed -----', false);
} else {
logger.log('debug', "Resume called but no resume function is set");
}
});
this.socket.on('step', () => {
if (this.interpretationResume) {
this.interpretationResume();
} else {
logger.log('debug', "Step called but no resume function is set");
}
});
this.socket.on('breakpoints', (data: boolean[]) => {
logger.log('debug', "Setting breakpoints: " + data);
this.breakpoints = data
});
} | /**
* Subscribes to the events that are used to control the interpretation.
* The events are pause, resume, step and breakpoints.
* Step is used to interpret a single pair and pause on the other matched pair.
* @returns void
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Interpreter.ts#L127-L151 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowInterpreter.interpretRecordingInEditor | public interpretRecordingInEditor = async (
workflow: WorkflowFile,
page: Page,
updatePageOnPause: (page: Page) => void,
settings: InterpreterSettings,
) => {
const params = settings.params ? settings.params : null;
delete settings.params;
const processedWorkflow = processWorkflow(workflow, true);
const options = {
...settings,
debugChannel: {
activeId: (id: any) => {
this.activeId = id;
this.socket.emit('activePairId', id);
},
debugMessage: (msg: any) => {
this.debugMessages.push(`[${new Date().toLocaleString()}] ` + msg);
this.socket.emit('log', msg)
},
},
serializableCallback: (data: any) => {
this.socket.emit('serializableCallback', data);
},
binaryCallback: (data: string, mimetype: string) => {
this.socket.emit('binaryCallback', { data, mimetype });
}
}
const interpreter = new Interpreter(processedWorkflow, options);
this.interpreter = interpreter;
interpreter.on('flag', async (page, resume) => {
if (this.activeId !== null && this.breakpoints[this.activeId]) {
logger.log('debug', `breakpoint hit id: ${this.activeId}`);
this.socket.emit('breakpointHit');
this.interpretationIsPaused = true;
}
if (this.interpretationIsPaused) {
this.interpretationResume = resume;
logger.log('debug', `Paused inside of flag: ${page.url()}`);
updatePageOnPause(page);
this.socket.emit('log', '----- The interpretation has been paused -----', false);
} else {
resume();
}
});
this.socket.emit('log', '----- Starting the interpretation -----', false);
const status = await interpreter.run(page, params);
this.socket.emit('log', `----- The interpretation finished with status: ${status} -----`, false);
logger.log('debug', `Interpretation finished`);
this.interpreter = null;
this.socket.emit('activePairId', -1);
this.interpretationIsPaused = false;
this.interpretationResume = null;
this.socket.emit('finished');
} | /**
* Sets up the instance of {@link Interpreter} and interprets
* the workflow inside the recording editor.
* Cleans up this interpreter instance after the interpretation is finished.
* @param workflow The workflow to interpret.
* @param page The page instance used to interact with the browser.
* @param updatePageOnPause A callback to update the page after a pause.
* @returns {Promise<void>}
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Interpreter.ts | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | WorkflowInterpreter.InterpretRecording | public InterpretRecording = async (
workflow: WorkflowFile,
page: Page,
updatePageOnPause: (page: Page) => void,
settings: InterpreterSettings
) => {
const params = settings.params ? settings.params : null;
delete settings.params;
const processedWorkflow = processWorkflow(workflow);
const options = {
...settings,
debugChannel: {
activeId: (id: any) => {
this.activeId = id;
this.socket.emit('activePairId', id);
},
debugMessage: (msg: any) => {
this.debugMessages.push(`[${new Date().toLocaleString()}] ` + msg);
this.socket.emit('debugMessage', msg)
},
},
serializableCallback: (data: any) => {
this.serializableData.push(data);
this.socket.emit('serializableCallback', data);
},
binaryCallback: async (data: string, mimetype: string) => {
this.binaryData.push({ mimetype, data: JSON.stringify(data) });
this.socket.emit('binaryCallback', { data, mimetype });
}
}
const interpreter = new Interpreter(processedWorkflow, options);
this.interpreter = interpreter;
interpreter.on('flag', async (page, resume) => {
if (this.activeId !== null && this.breakpoints[this.activeId]) {
logger.log('debug', `breakpoint hit id: ${this.activeId}`);
this.socket.emit('breakpointHit');
this.interpretationIsPaused = true;
}
if (this.interpretationIsPaused) {
this.interpretationResume = resume;
logger.log('debug', `Paused inside of flag: ${page.url()}`);
updatePageOnPause(page);
this.socket.emit('log', '----- The interpretation has been paused -----', false);
} else {
resume();
}
});
const status = await interpreter.run(page, params);
const lastArray = this.serializableData.length > 1
? [this.serializableData[this.serializableData.length - 1]]
: this.serializableData;
const result = {
log: this.debugMessages,
result: status,
serializableOutput: lastArray.reduce((reducedObject, item, index) => {
return {
[`item-${index}`]: item,
...reducedObject,
}
}, {}),
binaryOutput: this.binaryData.reduce((reducedObject, item, index) => {
return {
[`item-${index}`]: item,
...reducedObject,
}
}, {})
}
logger.log('debug', `Interpretation finished`);
this.clearState();
return result;
} | /**
* Interprets the recording as a run.
* @param workflow The workflow to interpret.
* @param page The page instance used to interact with the browser.
* @param settings The settings to use for the interpretation.
*/ | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/server/src/workflow-management/classes/Interpreter.ts#L259-L338 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | getAndClearCookie | const getAndClearCookie = (name: string) => {
const value = document.cookie
.split('; ')
.find(row => row.startsWith(`${name}=`))
?.split('=')[1];
if (value) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
}
return value;
}; | // Helper function to get and clear a cookie | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/src/components/robot/Recordings.tsx#L48-L59 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
maxun | github_2023 | getmaxun | typescript | isPrintableCharacter | const isPrintableCharacter = (char: string): boolean => {
return char.length === 1 && !!char.match(/^[\x20-\x7E]$/);
}; | // Helper function to check if a character is printable | https://github.com/getmaxun/maxun/blob/be7c599195a0e2a1c08a28a9eb094a79359a3e9c/src/components/robot/RobotEdit.tsx#L131-L133 | be7c599195a0e2a1c08a28a9eb094a79359a3e9c |
harper | github_2023 | Automattic | typescript | test | function test(){} | /** This is a doc comment.
* Since there are no keywords it _sould_ be checked. */ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/harper-comments/tests/language_support_sources/jsdoc.ts#L3-L3 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | foo | function foo(n, o, d) {
return n
} | /** Here is another example: {@link this sould also b unchecked}. But this _sould_ be.*/ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/harper-comments/tests/language_support_sources/jsdoc.ts#L24-L26 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | test | function test() {} | // This is an example of an problematic comment | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/harper-comments/tests/language_support_sources/multiline_comments.ts#L3-L3 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | arbitrary | function arbitrary() {} | /***
* This is an example of a possible error:
* these subsequent lines should not be considered a new sentence and should
* produce no errors.
*/ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/harper-comments/tests/language_support_sources/multiline_comments.ts#L10-L10 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | LocalLinter.initialize | private async initialize(): Promise<void> {
if (!this.inner) {
const wasm = await loadWasm();
wasm.setup();
this.inner = wasm.Linter.new();
}
} | /** Initialize the WebAssembly and construct the inner Linter. */ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/packages/harper.js/src/LocalLinter.ts#L12-L18 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | WorkerLinter.rpc | private async rpc(procName: string, args: any[]): Promise<any> {
const promise = new Promise((resolve, reject) => {
this.requestQueue.push({
resolve,
reject,
request: { procName, args }
});
this.submitRemainingRequests();
});
return promise;
} | /** Run a procedure on the remote worker. */ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/packages/harper.js/src/WorkerLinter/index.ts#L133-L145 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | HarperPlugin.constructEditorLinter | private constructEditorLinter(): Extension {
return linter(
async (view) => {
const text = view.state.doc.sliceString(-1);
const chars = toArray(text);
const lints = await this.harper.lint(text);
return lints.map((lint) => {
const span = lint.span();
span.start = charIndexToCodePointIndex(span.start, chars);
span.end = charIndexToCodePointIndex(span.end, chars);
return {
from: span.start,
to: span.end,
severity: 'error',
title: lint.lint_kind(),
message: lint.message(),
ignore: async () => {
await this.harper.ignoreLint(lint);
await this.reinitialize();
},
actions: lint.suggestions().map((sug) => {
return {
name: suggestionToLabel(sug),
apply: (view) => {
if (sug.kind() === SuggestionKind.Remove) {
view.dispatch({
changes: {
from: span.start,
to: span.end,
insert: ''
}
});
} else if (sug.kind() === SuggestionKind.Replace) {
view.dispatch({
changes: {
from: span.start,
to: span.end,
insert: sug.get_replacement_text()
}
});
} else if (sug.kind() === SuggestionKind.InsertAfter) {
view.dispatch({
changes: {
from: span.end,
to: span.end,
insert: sug.get_replacement_text()
}
});
}
}
};
})
};
});
},
{
delay: -1
}
);
} | /** Construct the linter plugin that actually shows the errors. */ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/packages/obsidian-plugin/src/index.ts#L167-L230 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
harper | github_2023 | Automattic | typescript | charIndexToCodePointIndex | function charIndexToCodePointIndex(index: number, sourceChars: string[]): number {
let traversed = 0;
for (let i = 0; i < index; i++) {
const delta = sourceChars[i].length;
traversed += delta;
}
return traversed;
} | /** Harper returns positions based on char indexes,
* but Obsidian identifies locations in documents based on Unicode code points.
* This converts between from the former to the latter.*/ | https://github.com/Automattic/harper/blob/c963a156a27a669fc5ecacd7509ff699b7a1f242/packages/obsidian-plugin/src/index.ts#L236-L246 | c963a156a27a669fc5ecacd7509ff699b7a1f242 |
vechain-dapp-kit | github_2023 | vechain | typescript | AppComponent.ngOnInit | public ngOnInit(): void {
const walletConnectOptions = {
projectId: 'a0b855ceaf109dbc8426479a4c3d38d8',
metadata: {
name: 'Sample VeChain dApp',
description: 'A sample VeChain dApp',
url: window.location.origin,
icons: [`${window.location.origin}/images/logo/my-dapp.png`],
},
};
const vechainDAppKitOptions = {
nodeUrl: 'https://testnet.vechain.org/',
walletConnectOptions,
usePersistence: true,
};
DAppKitUI.configure(vechainDAppKitOptions);
// custom button configuration
const customButton = document.getElementById('custom-button');
if (customButton) {
const handleConnected = (address: string | null): void => {
if (address) {
const formattedAddress = `${address.slice(
0,
6,
)}...${address.slice(-4)}`;
customButton.innerText = `Disconnect from ${formattedAddress}`;
} else {
customButton.innerText = 'Connect Custom Button';
}
};
handleConnected(DAppKitUI.wallet.state.address);
DAppKitUI.modal.onConnectionStatusChange(handleConnected);
}
} | // ------------------------------------------------------------------------------- | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/examples/sample-angular-app/src/app/app.component.ts#L16-L53 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | CustomWalletConnectModal.openModal | openModal(options: OpenOptions): Promise<void> {
DAppKitLogger.debug('CustomWalletConnectModal', 'opening the wc modal');
dispatchCustomEvent('vdk-open-wc-qrcode', options);
return Promise.resolve();
} | /**
* WalletConnect
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/packages/dapp-kit-ui/src/classes/custom-wallet-connect-modal.ts#L37-L41 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | createThorDriver | const createThorDriver = (
node: string,
genesis: Connex.Thor.Block,
net: Net,
): DriverNoVendor => {
// Stringify the certificate to hash
const certificateToHash = JSON.stringify({
node,
genesis,
});
// Encode the certificate to hash
const encodedCertificateToHash = new TextEncoder().encode(
certificateToHash.normalize(),
);
// Get the key (the hash of the certificate) without 0x prefix
const key: string = Hex.of(
blake2b256(encodedCertificateToHash, 'hex'),
).digits;
let driver = cache[key];
if (!driver) {
driver = new DriverNoVendor(net, genesis);
cache[key] = driver;
}
return driver;
}; | /**
* START: TEMPORARY COMMENT
* For hashing we will improve SDK conversion and encoding later
* END: TEMPORARY COMMENT
*
* Create a new Thor driver
*
* @param node - The node URL
* @param genesis - The genesis block
* @param net - The network
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/packages/dapp-kit/src/dapp-kit.ts#L25-L52 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | WalletManager.signConnectionCertificate | setAccountDomain = (address: string | null): void => {
if (address) {
this.state.isAccountDomainLoading = true;
getAccountDomain({ address, driver: this.driver })
.then((domain) => {
this.state.accountDomain = domain;
})
.catch((e) => {
console.error('Error getting account domain', e);
this.state.accountDomain = null;
})
.finally(() => {
this.state.isAccountDomainLoading = false;
});
} else {
this.state.accountDomain = null;
this.state.isAccountDomainLoading = false;
}
} | /**
* Sign a connection certificate
* this is needed for wallet connect connections when a connection certificate is required
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/packages/dapp-kit/src/classes/wallet-manager.ts | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | listenToEvents | const listenToEvents = (_client: SignClient): void => {
_client.on('session_update', ({ topic, params }): void => {
DAppKitLogger.debug('wallet connect signer', 'session_update', {
topic,
params,
});
const { namespaces } = params;
const _session = _client.session.get(topic);
session = { ..._session, namespaces };
});
_client.on('session_delete', () => {
onDisconnected();
disconnect().catch(() => {
throw new Error('Failed to disconnect');
});
});
}; | // listen for session updates | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/packages/dapp-kit/src/utils/create-wc-signer.ts#L59-L76 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | restoreSession | const restoreSession = (_client: SignClient): void => {
if (typeof session !== 'undefined') return;
DAppKitLogger.debug('wallet connect signer', 'restore session');
const sessionKeys = _client.session.keys;
for (const key of sessionKeys) {
const _session = _client.session.get(key);
const accounts = _session.namespaces.vechain.accounts;
for (const acc of accounts) {
if (acc.split(':')[1] === genesisId.slice(-32)) {
session = _session;
return;
}
}
}
}; | // restore a session if undefined | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/packages/dapp-kit/src/utils/create-wc-signer.ts#L79-L96 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | validateSession | const validateSession = (
requestedAddress?: string,
): SessionAccount | undefined => {
if (!session) return;
DAppKitLogger.debug('wallet connect signer', 'validate session');
const firstAccount = session.namespaces.vechain.accounts[0];
const address = firstAccount.split(':')[2];
const networkIdentifier = firstAccount.split(':')[1];
// Return undefined if the network identifier doesn't match
if (networkIdentifier !== genesisId.slice(-32)) return;
// Return undefined if the address doesn't match
if (
requestedAddress &&
requestedAddress.toLowerCase() !== address.toLowerCase()
)
return;
return {
address,
networkIdentifier,
topic: session.topic,
};
}; | /**
* Validates the requested account and network against a request
* @param requestedAddress - The optional requested account address
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/packages/dapp-kit/src/utils/create-wc-signer.ts#L102-L128 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | isPasswordSubmitted | const isPasswordSubmitted = async () => {
return extension.driver.isElementPresent(
Locators.byRole('goToImportWallet'),
);
}; | /**
* Checks for next screen's elements
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/tests/e2e/src/extension/flows/SetupPasswordFlows.ts#L32-L36 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | ExtensionDriver.getBaseUrl | public getBaseUrl = async (): Promise<string> => {
if (this.extensionUrl) return this.extensionUrl;
await this.get('chrome://extensions');
const extensionId: string = await this.executeScript(`
return document.querySelector("extensions-manager").shadowRoot
.querySelector("extensions-item-list").shadowRoot
.querySelector("extensions-item").getAttribute("id")
`);
this.extensionUrl = `chrome-extension://${extensionId}/index.html#`;
return this.extensionUrl;
} | /**
* This method is built on the assumption that our extension is the only one existing
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/tests/e2e/src/extension/selenium/WebDriver.ts | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
vechain-dapp-kit | github_2023 | vechain | typescript | goToUrl | const goToUrl = async (url: string): Promise<string> => {
await extension.driver.get(url);
await extension.driver.sleep(1000);
return extension.driver.getWindowHandle();
}; | /**
* @returns the window handle of the given URL
*/ | https://github.com/vechain/vechain-dapp-kit/blob/614d863ea5a3bb27d0c65a5446fad7c937c5e2b6/tests/e2e/src/extension/utils/NavigationUtils.ts#L12-L16 | 614d863ea5a3bb27d0c65a5446fad7c937c5e2b6 |
multiwoven | github_2023 | Multiwoven | typescript | useQueryWrapper | const useQueryWrapper = <TData, TError = unknown>(
key: QueryKey,
queryFn: QueryFunction<TData>,
options?: Omit<UseQueryOptions<TData, TError>, 'queryKey' | 'queryFn'>,
): UseQueryResult<TData, TError> => {
const activeWorkspaceId = useStore((state) => state.workspaceId);
const queryOptions: UseQueryOptions<TData, TError> = {
...options,
queryKey: [...key, activeWorkspaceId],
queryFn: activeWorkspaceId > 0 ? queryFn : () => Promise.resolve(null as unknown as TData),
enabled: activeWorkspaceId > 0,
};
return useQuery<TData, TError>(queryOptions);
}; | // Custom hook for queries with workspace ID check | https://github.com/Multiwoven/multiwoven/blob/21bf4c88c80d9b98f0ea146e66620f3dd8e6c6ab/ui/src/hooks/useQueryWrapper.tsx#L11-L26 | 21bf4c88c80d9b98f0ea146e66620f3dd8e6c6ab |
multiwoven | github_2023 | Multiwoven | typescript | createAxiosInstance | function createAxiosInstance(apiHost: string) {
const instance = axios.create({
baseURL: `${apiHost}`,
});
instance.interceptors.request.use(function requestSuccess(config) {
const token = Cookies.get('authToken');
config.headers['Content-Type'] = 'application/json';
config.headers['Workspace-Id'] = useStore.getState().workspaceId;
config.headers['Authorization'] = `Bearer ${token}`;
config.headers['Accept'] = '*/*';
return config;
});
instance.interceptors.response.use(
function responseSuccess(config) {
return config;
},
function responseError(error) {
if (error && error.response && error.response.status) {
switch (error.response.status) {
case 401:
if (window.location.pathname !== '/sign-in') {
window.location.href = '/sign-in';
Cookies.remove('authToken');
useStore.getState().clearState();
}
break;
case 403:
break;
case 501:
break;
case 500:
break;
default:
break;
}
}
return error.response;
},
);
return instance;
} | // Function to create axios instance with the current apiHost | https://github.com/Multiwoven/multiwoven/blob/21bf4c88c80d9b98f0ea146e66620f3dd8e6c6ab/ui/src/services/axios.ts#L13-L56 | 21bf4c88c80d9b98f0ea146e66620f3dd8e6c6ab |
multiwoven | github_2023 | Multiwoven | typescript | SignUp | const SignUp = (): JSX.Element => {
const [submitting, setSubmitting] = useState(false);
const navigate = useNavigate();
const showToast = useCustomToast();
const apiErrorToast = useAPIErrorsToast();
const errorToast = useErrorToast();
const { mutateAsync } = useMutation({
mutationFn: (values: SignUpPayload) => signUp(values),
mutationKey: ['signUp'],
});
const handleSubmit = async (values: any) => {
setSubmitting(true);
try {
const result = await mutateAsync(values);
if (result.data?.attributes) {
showToast({
title: 'Account created.',
status: CustomToastStatus.Success,
duration: 3000,
isClosable: true,
position: 'bottom-right',
});
navigate(`/sign-up/success?email=${values.email}`);
} else {
apiErrorToast(result.errors || []);
}
} catch (error) {
errorToast('An error occured. Please try again later.', true, null, true);
} finally {
setSubmitting(false);
}
};
const { logoUrl, brandName, privacyPolicyUrl, termsOfServiceUrl } = mwTheme;
return (
<>
<AuthCard logoUrl={logoUrl} brandName={brandName}>
<Stack spacing='8px' textAlign='center' mb='32px'>
<Heading size='xs' fontWeight='semibold'>
Get started with {brandName}
</Heading>
</Stack>
<SignUpAuthView
logoUrl={logoUrl}
brandName={brandName}
handleSubmit={handleSubmit}
submitting={submitting}
privacyPolicyUrl={privacyPolicyUrl}
termsOfServiceUrl={termsOfServiceUrl}
initialValues={{
company_name: '',
email: '',
name: '',
password: '',
password_confirmation: '',
}}
/>
</AuthCard>
<AuthFooter
brandName={brandName}
privacyPolicyUrl={privacyPolicyUrl}
termsOfServiceUrl={termsOfServiceUrl}
/>
</>
);
}; | // import isValidEmailDomain from '@/utils/isValidEmailDomain'; | https://github.com/Multiwoven/multiwoven/blob/21bf4c88c80d9b98f0ea146e66620f3dd8e6c6ab/ui/src/views/Authentication/SignUp/SignUp.tsx#L15-L85 | 21bf4c88c80d9b98f0ea146e66620f3dd8e6c6ab |
alien-signals | github_2023 | stackblitz | typescript | runEffect | function runEffect(e: Effect): void {
const prevSub = activeSub;
activeSub = e;
startTracking(e);
try {
e.fn();
} finally {
activeSub = prevSub;
endTracking(e);
}
} | //#endregion | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/index.ts#L140-L150 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
alien-signals | github_2023 | stackblitz | typescript | computedGetter | function computedGetter<T>(this: Computed<T>): T {
const flags = this.flags;
if (flags & (SubscriberFlags.Dirty | SubscriberFlags.PendingComputed)) {
processComputedUpdate(this, flags);
}
if (activeSub !== undefined) {
link(this, activeSub);
} else if (activeScope !== undefined) {
link(this, activeScope);
}
return this.currentValue!;
} | //#endregion | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/index.ts#L188-L199 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
alien-signals | github_2023 | stackblitz | typescript | linkNewDep | function linkNewDep(dep: Dependency, sub: Subscriber, nextDep: Link | undefined, depsTail: Link | undefined): Link {
const newLink: Link = {
dep,
sub,
nextDep,
prevSub: undefined,
nextSub: undefined,
};
if (depsTail === undefined) {
sub.deps = newLink;
} else {
depsTail.nextDep = newLink;
}
if (dep.subs === undefined) {
dep.subs = newLink;
} else {
const oldTail = dep.subsTail!;
newLink.prevSub = oldTail;
oldTail.nextSub = newLink;
}
sub.depsTail = newLink;
dep.subsTail = newLink;
return newLink;
} | /**
* Creates and attaches a new link between the given dependency and subscriber.
*
* Reuses a link object from the linkPool if available. The newly formed link
* is added to both the dependency's linked list and the subscriber's linked list.
*
* @param dep - The dependency to link.
* @param sub - The subscriber to be attached to this dependency.
* @param nextDep - The next link in the subscriber's chain.
* @param depsTail - The current tail link in the subscriber's chain.
* @returns The newly created link object.
*/ | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/system.ts#L346-L373 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
alien-signals | github_2023 | stackblitz | typescript | checkDirty | function checkDirty(link: Link): boolean {
let stack = 0;
let dirty: boolean;
top: do {
dirty = false;
const dep = link.dep;
if ('flags' in dep) {
const depFlags = dep.flags;
if ((depFlags & (SubscriberFlags.Computed | SubscriberFlags.Dirty)) === (SubscriberFlags.Computed | SubscriberFlags.Dirty)) {
if (updateComputed(dep)) {
const subs = dep.subs!;
if (subs.nextSub !== undefined) {
shallowPropagate(subs);
}
dirty = true;
}
} else if ((depFlags & (SubscriberFlags.Computed | SubscriberFlags.PendingComputed)) === (SubscriberFlags.Computed | SubscriberFlags.PendingComputed)) {
const depSubs = dep.subs!;
if (depSubs.nextSub !== undefined) {
depSubs.prevSub = link;
}
link = dep.deps!;
++stack;
continue;
}
}
if (!dirty && link.nextDep !== undefined) {
link = link.nextDep;
continue;
}
if (stack) {
let sub = link.sub as Dependency & Subscriber;
do {
--stack;
const subSubs = sub.subs!;
if (dirty) {
if (updateComputed(sub)) {
if ((link = subSubs.prevSub!) !== undefined) {
subSubs.prevSub = undefined;
shallowPropagate(subSubs);
sub = link.sub as Dependency & Subscriber;
} else {
sub = subSubs.sub as Dependency & Subscriber;
}
continue;
}
} else {
sub.flags &= ~SubscriberFlags.PendingComputed;
}
if ((link = subSubs.prevSub!) !== undefined) {
subSubs.prevSub = undefined;
if (link.nextDep !== undefined) {
link = link.nextDep;
continue top;
}
sub = link.sub as Dependency & Subscriber;
} else {
if ((link = subSubs.nextDep!) !== undefined) {
continue top;
}
sub = subSubs.sub as Dependency & Subscriber;
}
dirty = false;
} while (stack);
}
return dirty;
} while (true);
} | /**
* Recursively checks and updates all computed subscribers marked as pending.
*
* It traverses the linked structure using a stack mechanism. For each computed
* subscriber in a pending state, updateComputed is called and shallowPropagate
* is triggered if a value changes. Returns whether any updates occurred.
*
* @param link - The starting link representing a sequence of pending computeds.
* @returns `true` if a computed was updated, otherwise `false`.
*/ | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/system.ts#L385-L460 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
alien-signals | github_2023 | stackblitz | typescript | shallowPropagate | function shallowPropagate(link: Link): void {
do {
const sub = link.sub;
const subFlags = sub.flags;
if ((subFlags & (SubscriberFlags.PendingComputed | SubscriberFlags.Dirty)) === SubscriberFlags.PendingComputed) {
sub.flags = subFlags | SubscriberFlags.Dirty | SubscriberFlags.Notified;
if ((subFlags & (SubscriberFlags.Effect | SubscriberFlags.Notified)) === SubscriberFlags.Effect) {
if (queuedEffectsTail !== undefined) {
queuedEffectsTail.depsTail!.nextDep = sub.deps;
} else {
queuedEffects = sub;
}
queuedEffectsTail = sub;
}
}
link = link.nextSub!;
} while (link !== undefined);
} | /**
* Quickly propagates PendingComputed status to Dirty for each subscriber in the chain.
*
* If the subscriber is also marked as an effect, it is added to the queuedEffects list
* for later processing.
*
* @param link - The head of the linked list to process.
*/ | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/system.ts#L470-L487 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
alien-signals | github_2023 | stackblitz | typescript | isValidLink | function isValidLink(checkLink: Link, sub: Subscriber): boolean {
const depsTail = sub.depsTail;
if (depsTail !== undefined) {
let link = sub.deps!;
do {
if (link === checkLink) {
return true;
}
if (link === depsTail) {
break;
}
link = link.nextDep!;
} while (link !== undefined);
}
return false;
} | /**
* Verifies whether the given link is valid for the specified subscriber.
*
* It iterates through the subscriber's link list (from sub.deps to sub.depsTail)
* to determine if the provided link object is part of that chain.
*
* @param checkLink - The link object to validate.
* @param sub - The subscriber whose link list is being checked.
* @returns `true` if the link is found in the subscriber's list; otherwise `false`.
*/ | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/system.ts#L499-L514 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
alien-signals | github_2023 | stackblitz | typescript | clearTracking | function clearTracking(link: Link): void {
do {
const dep = link.dep;
const nextDep = link.nextDep;
const nextSub = link.nextSub;
const prevSub = link.prevSub;
if (nextSub !== undefined) {
nextSub.prevSub = prevSub;
} else {
dep.subsTail = prevSub;
}
if (prevSub !== undefined) {
prevSub.nextSub = nextSub;
} else {
dep.subs = nextSub;
}
if (dep.subs === undefined && 'deps' in dep) {
const depFlags = dep.flags;
if (!(depFlags & SubscriberFlags.Dirty)) {
dep.flags = depFlags | SubscriberFlags.Dirty;
}
const depDeps = dep.deps;
if (depDeps !== undefined) {
link = depDeps;
dep.depsTail!.nextDep = nextDep;
dep.deps = undefined;
dep.depsTail = undefined;
continue;
}
}
link = nextDep!;
} while (link !== undefined);
} | /**
* Clears dependency-subscription relationships starting at the given link.
*
* Detaches the link from both the dependency and subscriber, then continues
* to the next link in the chain. The link objects are returned to linkPool for reuse.
*
* @param link - The head of a linked chain to be cleared.
*/ | https://github.com/stackblitz/alien-signals/blob/59e393501597f6c8c4cf08c4e540c4517841a0cb/src/system.ts#L524-L559 | 59e393501597f6c8c4cf08c4e540c4517841a0cb |
pro-chat | github_2023 | ant-design | typescript | ShouldUpdateItem.shouldComponentUpdate | shouldComponentUpdate(nextProps: any) {
if (nextProps.shouldUpdate) {
return nextProps.shouldUpdate(this.props, nextProps);
}
try {
return (
!isEqual(this.props.content, nextProps?.content) ||
!isEqual(this.props.loading, nextProps?.loading) ||
!isEqual(this.props.chatItemRenderConfig, nextProps?.chatItemRenderConfig) ||
!isEqual(this.props.meta, nextProps?.meta)
);
} catch (error) {
return true;
}
} | /**
* 判断组件是否需要更新。
* @param nextProps - 下一个属性对象。
* @returns 如果需要更新则返回 true,否则返回 false。
*/ | https://github.com/ant-design/pro-chat/blob/73be565e1b00787435fd951df7fbc684db7923d5/src/ChatList/ShouldUpdateItem.tsx#L19-L33 | 73be565e1b00787435fd951df7fbc684db7923d5 |
pro-chat | github_2023 | ant-design | typescript | compilerMessages | const compilerMessages = (slicedMessages: ChatMessage[]) => {
const compiler = template(config.inputTemplate, { interpolate: /{{([\S\s]+?)}}/g });
return slicedMessages.map((m) => {
if (m.role === 'user') {
try {
return { ...m, content: compiler({ text: m.content }) };
} catch (error) {
console.error(error);
return m;
}
}
return m;
});
}; | // 2. 替换 inputMessage 模板 | https://github.com/ant-design/pro-chat/blob/73be565e1b00787435fd951df7fbc684db7923d5/src/ProChat/store/action.ts#L211-L225 | 73be565e1b00787435fd951df7fbc684db7923d5 |
pro-chat | github_2023 | ant-design | typescript | checkAndToggleChatLoading | const checkAndToggleChatLoading = () => {
clearTimeout(timeoutId); // 清除任何现有的计时器
// 等待队列内容输出完毕
if (outputQueue === undefined || outputQueue.length === 0 || outputQueue.toString() === '') {
// 当队列为空时
toggleChatLoading(false, undefined, t('generateMessage(end)') as string);
clearTimeout(timeoutId);
} else {
// 如果队列不为空,则设置一个延迟或者使用某种形式的轮询来再次检查队列
timeoutId = setTimeout(checkAndToggleChatLoading, 30); // CHECK_INTERVAL 是毫秒数,代表检查间隔时间
}
}; | // 用于存储轮询队列的计时器id | https://github.com/ant-design/pro-chat/blob/73be565e1b00787435fd951df7fbc684db7923d5/src/ProChat/store/action.ts#L311-L322 | 73be565e1b00787435fd951df7fbc684db7923d5 |
pro-chat | github_2023 | ant-design | typescript | stopAnimation | const stopAnimation = () => {
isAnimationActive = false;
if (animationTimeoutId !== null) {
clearTimeout(animationTimeoutId);
animationTimeoutId = null;
}
}; | // when you need to stop the animation, call this function | https://github.com/ant-design/pro-chat/blob/73be565e1b00787435fd951df7fbc684db7923d5/src/ProChat/store/action.ts#L486-L492 | 73be565e1b00787435fd951df7fbc684db7923d5 |
pro-chat | github_2023 | ant-design | typescript | startAnimation | const startAnimation = (speed = 2) =>
new Promise<void>((resolve) => {
if (isAnimationActive) {
resolve();
return;
}
isAnimationActive = true;
const updateText = () => {
// 如果动画已经不再激活,则停止更新文本
if (!isAnimationActive) {
clearTimeout(animationTimeoutId!);
animationTimeoutId = null;
resolve();
}
// 如果还有文本没有显示
// 检查队列中是否有字符待显示
if (outputQueue.length > 0) {
// 从队列中获取前两个字符(如果存在)
const charsToAdd = outputQueue.splice(0, speed).join('');
buffer += charsToAdd;
if (typeof mixRequestResponse === 'object' && 'content' in mixRequestResponse) {
dispatchMessage({
...mixRequestResponse,
id,
key: 'content',
type: 'updateMessage',
value: buffer,
});
} else {
// 更新消息内容,这里可能需要结合实际情况调整
dispatchMessage({ id, key: 'content', type: 'updateMessage', value: buffer });
}
// 设置下一个字符的延迟
animationTimeoutId = setTimeout(updateText, 16); // 16 毫秒的延迟模拟打字机效果
} else {
// 当所有字符都显示完毕时,清除动画状态
isAnimationActive = false;
animationTimeoutId = null;
resolve();
}
};
updateText();
}); | // define startAnimation function to display the text in buffer smooth | https://github.com/ant-design/pro-chat/blob/73be565e1b00787435fd951df7fbc684db7923d5/src/ProChat/store/action.ts#L496-L543 | 73be565e1b00787435fd951df7fbc684db7923d5 |
pro-chat | github_2023 | ant-design | typescript | onMouseMove | const onMouseMove = (e: MouseEvent) => {
const bound = element.getBoundingClientRect();
setOffset({ x: e.clientX - bound.x, y: e.clientY - bound.y });
setOutside(false);
}; | // debounce? | https://github.com/ant-design/pro-chat/blob/73be565e1b00787435fd951df7fbc684db7923d5/src/components/Spotlight/index.tsx#L17-L21 | 73be565e1b00787435fd951df7fbc684db7923d5 |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountApiApiUinApiPost | public accountApiApiUinApiPost(uin: number, name: string, body: object, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountApiApiUinApiPost(uin, name, body, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Api
* @param {number} uin
* @param {string} name
* @param {object} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2087-L2089 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountConfigDeleteApiUinConfigDelete | public accountConfigDeleteApiUinConfigDelete(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountConfigDeleteApiUinConfigDelete(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Config Delete
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2099-L2101 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountConfigReadApiUinConfigGet | public accountConfigReadApiUinConfigGet(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountConfigReadApiUinConfigGet(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Config Read
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2111-L2113 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountConfigWriteApiUinConfigPatch | public accountConfigWriteApiUinConfigPatch(uin: number, accountConfigFile: AccountConfigFile, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountConfigWriteApiUinConfigPatch(uin, accountConfigFile, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Config Write
* @param {number} uin
* @param {AccountConfigFile} accountConfigFile
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2124-L2126 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountDeviceDeleteApiUinDeviceDelete | public accountDeviceDeleteApiUinDeviceDelete(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountDeviceDeleteApiUinDeviceDelete(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Device Delete
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2136-L2138 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountDeviceReadApiUinDeviceGet | public accountDeviceReadApiUinDeviceGet(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountDeviceReadApiUinDeviceGet(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Device Read
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2148-L2150 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountDeviceWriteApiUinDevicePatch | public accountDeviceWriteApiUinDevicePatch(uin: number, deviceInfo: DeviceInfo, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountDeviceWriteApiUinDevicePatch(uin, deviceInfo, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Device Write
* @param {number} uin
* @param {DeviceInfo} deviceInfo
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2161-L2163 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountSessionDeleteApiUinSessionDelete | public accountSessionDeleteApiUinSessionDelete(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountSessionDeleteApiUinSessionDelete(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Session Delete
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2173-L2175 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountSessionReadApiUinSessionGet | public accountSessionReadApiUinSessionGet(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountSessionReadApiUinSessionGet(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Session Read
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2185-L2187 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.accountSessionWriteApiUinSessionPatch | public accountSessionWriteApiUinSessionPatch(uin: number, sessionTokenFile: SessionTokenFile, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).accountSessionWriteApiUinSessionPatch(uin, sessionTokenFile, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Account Session Write
* @param {number} uin
* @param {SessionTokenFile} sessionTokenFile
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2198-L2200 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.allAccountsApiAccountsGet | public allAccountsApiAccountsGet(nicknameCache?: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).allAccountsApiAccountsGet(nicknameCache, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary All Accounts
* @param {number} [nicknameCache]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2210-L2212 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.createAccountApiUinPut | public createAccountApiUinPut(uin: number, accountCreation?: AccountCreation, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).createAccountApiUinPut(uin, accountCreation, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Create Account
* @param {number} uin
* @param {AccountCreation} [accountCreation]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2223-L2225 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.deleteAccountApiUinDelete | public deleteAccountApiUinDelete(uin: number, withFile?: boolean, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).deleteAccountApiUinDelete(uin, withFile, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Delete Account
* @param {number} uin
* @param {boolean} [withFile]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2236-L2238 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.processInputLineApiUinProcessLogsPost | public processInputLineApiUinProcessLogsPost(uin: number, stdinInputContent: StdinInputContent, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).processInputLineApiUinProcessLogsPost(uin, stdinInputContent, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Process Input Line
* @param {number} uin
* @param {StdinInputContent} stdinInputContent
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2249-L2251 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.processLogsHistoryApiUinProcessLogsGet | public processLogsHistoryApiUinProcessLogsGet(uin: number, reverse?: boolean, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).processLogsHistoryApiUinProcessLogsGet(uin, reverse, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Process Logs History
* @param {number} uin
* @param {boolean} [reverse]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2262-L2264 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.processStartApiUinProcessPut | public processStartApiUinProcessPut(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).processStartApiUinProcessPut(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Process Start
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2274-L2276 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.processStatusApiUinProcessStatusGet | public processStatusApiUinProcessStatusGet(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).processStatusApiUinProcessStatusGet(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Process Status
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2286-L2288 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.processStopApiUinProcessDelete | public processStopApiUinProcessDelete(uin: number, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).processStopApiUinProcessDelete(uin, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary Process Stop
* @param {number} uin
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2298-L2300 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.systemLogsHistoryApiLogsGet | public systemLogsHistoryApiLogsGet(reverse?: boolean, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).systemLogsHistoryApiLogsGet(reverse, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary System Logs History
* @param {boolean} [reverse]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2310-L2312 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.systemStatusApiStatusGet | public systemStatusApiStatusGet(options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).systemStatusApiStatusGet(options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary System Status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2321-L2323 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.loginApi | public loginApi(username: string, password: string, options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).loginApi(username, password, options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary 登录API
* @param {string} username 用户名
* @param {string} password 密码
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2334-L2336 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | ApiApi.checkLoginStatus | public checkLoginStatus(options?: AxiosRequestConfig) {
return ApiApiFp(this.configuration).checkLoginStatus(options).then((request) => request(this.axios, this.basePath));
} | /**
*
* @summary 检查登录状态
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ApiApi
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/api.ts#L2345-L2347 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
Gensokyo | github_2023 | Hoshinonyaruko | typescript | Configuration.isJsonMime | public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
} | /**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/ | https://github.com/Hoshinonyaruko/Gensokyo/blob/043f80cf2bc0063ae193bb44549275d6c2530cdd/frontend/src/api/configuration.ts#L97-L100 | 043f80cf2bc0063ae193bb44549275d6c2530cdd |
agentcloud | github_2023 | rnadigital | typescript | gracefulStop | const gracefulStop = () => {
log('SIGINT SIGNAL RECEIVED');
db.client().close();
redis.close();
process.exit(0);
}; | //graceful stop handling | https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/server.ts#L107-L112 | 9ebed808f9b49541882b384f29a1a79ca80fae50 |
agentcloud | github_2023 | rnadigital | typescript | fetchModelFormData | async function fetchModelFormData() {
await API.getModels({ resourceSlug }, dispatch, setError, router);
} | // const { } = state as any; //TODO: secrets here | https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/components/CreateModelModal.tsx#L24-L26 | 9ebed808f9b49541882b384f29a1a79ca80fae50 |
agentcloud | github_2023 | rnadigital | typescript | ScriptEditor | const ScriptEditor = (props: ScriptEditorProps): JSX.Element => {
const { code, setCode, editorOptions, onInitializePane, height, language, editorJsonSchema } =
props;
const monacoEditorRef = useRef<typeof monaco.editor>(null);
const editorRef = useRef<any | null>(null);
// monaco takes years to mount, so this may fire repeatedly without refs set
useEffect(() => {
if (monacoEditorRef?.current) {
// again, monaco takes years to mount and load, so this may load as null
const model: any = monacoEditorRef.current.getModels();
if (model?.length > 0) {
// finally, do editor's document initialization here
onInitializePane(monacoEditorRef, editorRef, model);
}
}
});
return (
<Editor
height={height || '42.9em'} // preference | // | https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/components/Editor.tsx#L44-L66 | 9ebed808f9b49541882b384f29a1a79ca80fae50 |
agentcloud | github_2023 | rnadigital | typescript | fetchDatasource | async function fetchDatasource() {
if (datasourceId) {
await API.getDatasource(
{
resourceSlug,
datasourceId
},
res => {
const datasource = res?.datasource;
if (datasource?.status === DatasourceStatus.READY) {
router.push(`/${resourceSlug}/connections`);
}
},
() => {},
router
);
}
} | // Added dependency array | https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/components/connections/DatasourceSyncing.tsx#L26-L43 | 9ebed808f9b49541882b384f29a1a79ca80fae50 |
agentcloud | github_2023 | rnadigital | typescript | fetchDatasource | async function fetchDatasource() {
if (datasourceId) {
await API.getDatasource(
{
resourceSlug,
datasourceId
},
res => {
const datasource = res?.datasource;
if (datasource?.status === DatasourceStatus.READY) {
router.push(`/${resourceSlug}/apps`);
}
},
() => {},
router
);
}
} | // Added dependency array | https://github.com/rnadigital/agentcloud/blob/9ebed808f9b49541882b384f29a1a79ca80fae50/webapp/src/components/onboarding/DatasourceSyncing.tsx#L25-L42 | 9ebed808f9b49541882b384f29a1a79ca80fae50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.