type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
MethodDeclaration |
disposeTemplate(templateData: ITrustedUriPathColumnTemplateData): void {
templateData.disposables.dispose();
templateData.renderDisposables.dispose();
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
renderTemplate(container: HTMLElement): ITrustedUriHostColumnTemplateData {
const disposables = new DisposableStore();
const renderDisposables = disposables.add(new DisposableStore());
const element = container.appendChild($('.host'));
const hostContainer = element.appendChild($('div.host-label'));
const buttonBarContainer = element.appendChild($('div.button-bar'));
return {
element,
hostContainer,
buttonBarContainer,
disposables,
renderDisposables
};
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriHostColumnTemplateData, height: number | undefined): void {
templateData.renderDisposables.clear();
templateData.renderDisposables.add({ dispose: () => { clearNode(templateData.buttonBarContainer); } });
templateData.hostContainer.innerText = getHostLabel(this.labelService, item);
templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem);
templateData.hostContainer.style.display = '';
templateData.buttonBarContainer.style.display = 'none';
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
disposeTemplate(templateData: ITrustedUriHostColumnTemplateData): void {
templateData.disposables.dispose();
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
protected createEditor(parent: HTMLElement): void {
this.rootElement = append(parent, $('.workspace-trust-editor', { tabindex: '0' }));
this.rootElement.style.visibility = 'hidden';
this.createHeaderElement(this.rootElement);
const scrollableContent = $('.workspace-trust-editor-body');
this.bodyScrollBar = this._register(new DomScrollableElement(scrollableContent, {
horizontal: ScrollbarVisibility.Hidden,
vertical: ScrollbarVisibility.Auto,
}));
append(this.rootElement, this.bodyScrollBar.getDomNode());
this.createAffectedFeaturesElement(scrollableContent);
this.createConfigurationElement(scrollableContent);
this._register(attachStylerCallback(this.themeService, { debugIconStartForeground, editorErrorForeground, buttonBackground, buttonSecondaryBackground }, colors => {
this.rootElement.style.setProperty('--workspace-trust-selected-color', colors.buttonBackground?.toString() || '');
this.rootElement.style.setProperty('--workspace-trust-unselected-color', colors.buttonSecondaryBackground?.toString() || '');
this.rootElement.style.setProperty('--workspace-trust-check-color', colors.debugIconStartForeground?.toString() || '');
this.rootElement.style.setProperty('--workspace-trust-x-color', colors.editorErrorForeground?.toString() || '');
}));
// Navigate page with keyboard
this._register(addDisposableListener(this.rootElement, EventType.KEY_DOWN, e => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.UpArrow) || event.equals(KeyCode.DownArrow)) {
const navOrder = [this.headerContainer, this.trustedContainer, this.untrustedContainer, this.configurationContainer];
const currentIndex = navOrder.findIndex(element => {
return isAncestor(document.activeElement, element);
});
let newIndex = currentIndex;
if (event.equals(KeyCode.DownArrow)) {
newIndex++;
} else if (event.equals(KeyCode.UpArrow)) {
newIndex = Math.max(0, newIndex);
newIndex--;
}
newIndex += navOrder.length;
newIndex %= navOrder.length;
navOrder[newIndex].focus();
} else if (event.equals(KeyCode.Escape)) {
this.rootElement.focus();
}
}));
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
override focus() {
this.rootElement.focus();
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
override async setInput(input: WorkspaceTrustEditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
await super.setInput(input, options, context, token);
if (token.isCancellationRequested) { return; }
await this.workspaceTrustManagementService.workspaceTrustInitialized;
this.registerListeners();
this.render();
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private registerListeners(): void {
this._register(this.extensionWorkbenchService.onChange(() => this.render()));
this._register(this.configurationService.onDidChangeRestrictedSettings(() => this.render()));
this._register(this.workspaceTrustManagementService.onDidChangeTrust(() => this.render()));
this._register(this.workspaceTrustManagementService.onDidChangeTrustedFolders(() => this.render()));
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private getHeaderContainerClass(trusted: boolean): string {
if (trusted) {
return 'workspace-trust-header workspace-trust-trusted';
}
return 'workspace-trust-header workspace-trust-untrusted';
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private getHeaderTitleText(trusted: boolean): string {
if (trusted) {
if (this.workspaceTrustManagementService.isWorkspaceTrustForced()) {
return localize('trustedUnsettableWindow', "This window is trusted");
}
switch (this.workspaceService.getWorkbenchState()) {
case WorkbenchState.EMPTY:
return localize('trustedHeaderWindow', "You trust this window");
case WorkbenchState.FOLDER:
return localize('trustedHeaderFolder', "You trust this folder");
case WorkbenchState.WORKSPACE:
return localize('trustedHeaderWorkspace', "You trust this workspace");
}
}
return localize('untrustedHeader', "You are in Restricted Mode");
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private getHeaderTitleIconClassNames(trusted: boolean): string[] {
return shieldIcon.classNamesArray;
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private getFeaturesHeaderText(trusted: boolean): [string, string] {
let title: string = '';
let subTitle: string = '';
switch (this.workspaceService.getWorkbenchState()) {
case WorkbenchState.EMPTY: {
title = trusted ? localize('trustedWindow', "In a Trusted Window") : localize('untrustedWorkspace', "In Restricted Mode");
subTitle = trusted ? localize('trustedWindowSubtitle', "You trust the authors of the files in the current window. All features are enabled:") :
localize('untrustedWindowSubtitle', "You do not trust the authors of the files in the current window. The following features are disabled:");
break;
}
case WorkbenchState.FOLDER: {
title = trusted ? localize('trustedFolder', "In a Trusted Folder") : localize('untrustedWorkspace', "In Restricted Mode");
subTitle = trusted ? localize('trustedFolderSubtitle', "You trust the authors of the files in the current folder. All features are enabled:") :
localize('untrustedFolderSubtitle', "You do not trust the authors of the files in the current folder. The following features are disabled:");
break;
}
case WorkbenchState.WORKSPACE: {
title = trusted ? localize('trustedWorkspace', "In a Trusted Workspace") : localize('untrustedWorkspace', "In Restricted Mode");
subTitle = trusted ? localize('trustedWorkspaceSubtitle', "You trust the authors of the files in the current workspace. All features are enabled:") :
localize('untrustedWorkspaceSubtitle', "You do not trust the authors of the files in the current workspace. The following features are disabled:");
break;
}
}
return [title, subTitle];
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
@debounce(100)
private async render() {
if (this.rendering) {
return;
}
this.rendering = true;
this.rerenderDisposables.clear();
const isWorkspaceTrusted = this.workspaceTrustManagementService.isWorkspaceTrusted();
this.rootElement.classList.toggle('trusted', isWorkspaceTrusted);
this.rootElement.classList.toggle('untrusted', !isWorkspaceTrusted);
// Header Section
this.headerTitleText.innerText = this.getHeaderTitleText(isWorkspaceTrusted);
this.headerTitleIcon.className = 'workspace-trust-title-icon';
this.headerTitleIcon.classList.add(...this.getHeaderTitleIconClassNames(isWorkspaceTrusted));
this.headerDescription.innerText = '';
const headerDescriptionText = append(this.headerDescription, $('div'));
headerDescriptionText.innerText = isWorkspaceTrusted ?
localize('trustedDescription', "All features are enabled because trust has been granted to the workspace.") :
localize('untrustedDescription', "{0} is in a restricted mode intended for safe code browsing.", product.nameShort);
const headerDescriptionActions = append(this.headerDescription, $('div'));
const headerDescriptionActionsText = localize({ key: 'workspaceTrustEditorHeaderActions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[Configure your settings]({0}) or [learn more](https://aka.ms/vscode-workspace-trust).", `command:workbench.trust.configure`);
for (const node of parseLinkedText(headerDescriptionActionsText).nodes) {
if (typeof node === 'string') {
append(headerDescriptionActions, document.createTextNode(node));
} else {
this.rerenderDisposables.add(this.instantiationService.createInstance(Link, headerDescriptionActions, { ...node, tabIndex: -1 }, {}));
}
}
this.headerContainer.className = this.getHeaderContainerClass(isWorkspaceTrusted);
this.rootElement.setAttribute('aria-label', `${localize('root element label', "Manage Workspace Trust")}: ${this.headerContainer.innerText}`);
// Settings
const restrictedSettings = this.configurationService.restrictedSettings;
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
const settingsRequiringTrustedWorkspaceCount = restrictedSettings.default.filter(key => {
const property = configurationRegistry.getConfigurationProperties()[key];
// cannot be configured in workspace
if (property.scope === ConfigurationScope.APPLICATION || property.scope === ConfigurationScope.MACHINE) {
return false;
}
// If deprecated include only those configured in the workspace
if (property.deprecationMessage || property.markdownDeprecationMessage) {
if (restrictedSettings.workspace?.includes(key)) {
return true;
}
if (restrictedSettings.workspaceFolder) {
for (const workspaceFolderSettings of restrictedSettings.workspaceFolder.values()) {
if (workspaceFolderSettings.includes(key)) {
return true;
}
}
}
return false;
}
return true;
}).length;
// Features List
this.renderAffectedFeatures(settingsRequiringTrustedWorkspaceCount, this.getExtensionCount());
// Configuration Tree
this.workspaceTrustedUrisTable.updateTable();
this.bodyScrollBar.getDomNode().style.height = `calc(100% - ${this.headerContainer.clientHeight}px)`;
this.bodyScrollBar.scanDomNode();
this.rootElement.style.visibility = '';
this.rendering = false;
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private getExtensionCount(): number {
const set = new Set<string>();
const inVirtualWorkspace = isVirtualWorkspace(this.workspaceService.getWorkspace());
const localExtensions = this.extensionWorkbenchService.local.filter(ext => ext.local).map(ext => ext.local!);
for (const extension of localExtensions) {
const enablementState = this.extensionEnablementService.getEnablementState(extension);
if (enablementState !== EnablementState.EnabledGlobally && enablementState !== EnablementState.EnabledWorkspace &&
enablementState !== EnablementState.DisabledByTrustRequirement && enablementState !== EnablementState.DisabledByExtensionDependency) {
continue;
}
if (inVirtualWorkspace && this.extensionManifestPropertiesService.getExtensionVirtualWorkspaceSupportType(extension.manifest) === false) {
continue;
}
if (this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(extension.manifest) !== true) {
set.add(extension.identifier.id);
continue;
}
const dependencies = getExtensionDependencies(localExtensions, extension);
if (dependencies.some(ext => this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(ext.manifest) === false)) {
set.add(extension.identifier.id);
}
}
return set.size;
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private createHeaderElement(parent: HTMLElement): void {
this.headerContainer = append(parent, $('.workspace-trust-header', { tabIndex: '0' }));
this.headerTitleContainer = append(this.headerContainer, $('.workspace-trust-title'));
this.headerTitleIcon = append(this.headerTitleContainer, $('.workspace-trust-title-icon'));
this.headerTitleText = append(this.headerTitleContainer, $('.workspace-trust-title-text'));
this.headerDescription = append(this.headerContainer, $('.workspace-trust-description'));
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private createConfigurationElement(parent: HTMLElement): void {
this.configurationContainer = append(parent, $('.workspace-trust-settings', { tabIndex: '0' }));
const configurationTitle = append(this.configurationContainer, $('.workspace-trusted-folders-title'));
configurationTitle.innerText = localize('trustedFoldersAndWorkspaces', "Trusted Folders & Workspaces");
this.workspaceTrustedUrisTable = this._register(this.instantiationService.createInstance(WorkspaceTrustedUrisTable, this.configurationContainer));
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private createAffectedFeaturesElement(parent: HTMLElement): void {
this.affectedFeaturesContainer = append(parent, $('.workspace-trust-features'));
this.trustedContainer = append(this.affectedFeaturesContainer, $('.workspace-trust-limitations.trusted', { tabIndex: '0' }));
this.untrustedContainer = append(this.affectedFeaturesContainer, $('.workspace-trust-limitations.untrusted', { tabIndex: '0' }));
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private async renderAffectedFeatures(numSettings: number, numExtensions: number): Promise<void> {
clearNode(this.trustedContainer);
clearNode(this.untrustedContainer);
// Trusted features
const [trustedTitle, trustedSubTitle] = this.getFeaturesHeaderText(true);
this.renderLimitationsHeaderElement(this.trustedContainer, trustedTitle, trustedSubTitle);
const trustedContainerItems = this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY ?
[
localize('trustedTasks', "Tasks are allowed to run"),
localize('trustedDebugging', "Debugging is enabled"),
localize('trustedExtensions', "All extensions are enabled")
] :
[
localize('trustedTasks', "Tasks are allowed to run"),
localize('trustedDebugging', "Debugging is enabled"),
localize('trustedSettings', "All workspace settings are applied"),
localize('trustedExtensions', "All extensions are enabled")
];
this.renderLimitationsListElement(this.trustedContainer, trustedContainerItems, checkListIcon.classNamesArray);
// Restricted Mode features
const [untrustedTitle, untrustedSubTitle] = this.getFeaturesHeaderText(false);
this.renderLimitationsHeaderElement(this.untrustedContainer, untrustedTitle, untrustedSubTitle);
const untrustedContainerItems = this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY ?
[
localize('untrustedTasks', "Tasks are not allowed to run"),
localize('untrustedDebugging', "Debugging is disabled"),
localize({ key: 'untrustedExtensions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} extensions]({1}) are disabled or have limited functionality", numExtensions, `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}`)
] :
[
localize('untrustedTasks', "Tasks are not allowed to run"),
localize('untrustedDebugging', "Debugging is disabled"),
numSettings ? localize({ key: 'untrustedSettings', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} workspace settings]({1}) are not applied", numSettings, 'command:settings.filterUntrusted') : localize('no untrustedSettings', "Workspace settings requiring trust are not applied"),
localize({ key: 'untrustedExtensions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} extensions]({1}) are disabled or have limited functionality", numExtensions, `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}`)
];
this.renderLimitationsListElement(this.untrustedContainer, untrustedContainerItems, xListIcon.classNamesArray);
if (this.workspaceTrustManagementService.isWorkspaceTrusted()) {
if (this.workspaceTrustManagementService.canSetWorkspaceTrust()) {
this.addDontTrustButtonToElement(this.untrustedContainer);
} else {
this.addTrustedTextToElement(this.untrustedContainer);
}
} else {
if (this.workspaceTrustManagementService.canSetWorkspaceTrust()) {
this.addTrustButtonToElement(this.trustedContainer);
}
}
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private createButtonRow(parent: HTMLElement, actions: Action | Action[], enabled?: boolean): void {
const buttonRow = append(parent, $('.workspace-trust-buttons-row'));
const buttonContainer = append(buttonRow, $('.workspace-trust-buttons'));
const buttonBar = this.rerenderDisposables.add(new ButtonBar(buttonContainer));
if (actions instanceof Action) {
actions = [actions];
}
for (const action of actions) {
const button =
action instanceof ChoiceAction && action.menu?.length ?
buttonBar.addButtonWithDropdown({
title: true,
actions: action.menu ?? [],
contextMenuProvider: this.contextMenuService
}) :
buttonBar.addButton();
button.label = action.label;
button.enabled = enabled !== undefined ? enabled : action.enabled;
this.rerenderDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
action.run();
}));
this.rerenderDisposables.add(attachButtonStyler(button, this.themeService));
}
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private addTrustButtonToElement(parent: HTMLElement): void {
const trustActions = [
new Action('workspace.trust.button.action.grant', localize('trustButton', "Trust"), undefined, true, async () => {
await this.workspaceTrustManagementService.setWorkspaceTrust(true);
})
];
if (this.workspaceTrustManagementService.canSetParentFolderTrust()) {
const workspaceIdentifier = toWorkspaceIdentifier(this.workspaceService.getWorkspace()) as ISingleFolderWorkspaceIdentifier;
const { name } = splitName(splitName(workspaceIdentifier.uri.fsPath).parentPath);
const trustMessageElement = append(parent, $('.trust-message-box'));
trustMessageElement.innerText = localize('trustMessage', "Trust the authors of all files in the current folder or its parent '{0}'.", name);
trustActions.push(new Action('workspace.trust.button.action.grantParent', localize('trustParentButton', "Trust Parent"), undefined, true, async () => {
await this.workspaceTrustManagementService.setParentFolderTrust(true);
}));
}
this.createButtonRow(parent, trustActions);
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private addDontTrustButtonToElement(parent: HTMLElement): void {
this.createButtonRow(parent, new Action('workspace.trust.button.action.deny', localize('dontTrustButton', "Don't Trust"), undefined, true, async () => {
await this.workspaceTrustManagementService.setWorkspaceTrust(false);
}));
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private addTrustedTextToElement(parent: HTMLElement): void {
if (this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY) {
return;
}
const textElement = append(parent, $('.workspace-trust-untrusted-description'));
if (!this.workspaceTrustManagementService.isWorkspaceTrustForced()) {
textElement.innerText = this.workspaceService.getWorkbenchState() === WorkbenchState.WORKSPACE ? localize('untrustedWorkspaceReason', "This workspace is trusted via the bolded entries in the trusted folders below.") : localize('untrustedFolderReason', "This folder is trusted via the bolded entries in the the trusted folders below.");
} else {
textElement.innerText = localize('trustedForcedReason', "This window is trusted by nature of the workspace that is opened.");
}
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private renderLimitationsHeaderElement(parent: HTMLElement, headerText: string, subtitleText: string): void {
const limitationsHeaderContainer = append(parent, $('.workspace-trust-limitations-header'));
const titleElement = append(limitationsHeaderContainer, $('.workspace-trust-limitations-title'));
const textElement = append(titleElement, $('.workspace-trust-limitations-title-text'));
const subtitleElement = append(limitationsHeaderContainer, $('.workspace-trust-limitations-subtitle'));
textElement.innerText = headerText;
subtitleElement.innerText = subtitleText;
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
private renderLimitationsListElement(parent: HTMLElement, limitations: string[], iconClassNames: string[]): void {
const listContainer = append(parent, $('.workspace-trust-limitations-list-container'));
const limitationsList = append(listContainer, $('ul'));
for (const limitation of limitations) {
const limitationListItem = append(limitationsList, $('li'));
const icon = append(limitationListItem, $('.list-item-icon'));
const text = append(limitationListItem, $('.list-item-text'));
icon.classList.add(...iconClassNames);
const linkedText = parseLinkedText(limitation);
for (const node of linkedText.nodes) {
if (typeof node === 'string') {
append(text, document.createTextNode(node));
} else {
this.rerenderDisposables.add(this.instantiationService.createInstance(Link, text, { ...node, tabIndex: -1 }, {}));
}
}
}
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
MethodDeclaration |
layout(dimension: Dimension): void {
if (!this.isVisible()) {
return;
}
this.workspaceTrustedUrisTable.layout();
this.layoutParticipants.forEach(participant => {
participant.layout();
});
this.bodyScrollBar.scanDomNode();
} | AE1020/vscode | src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts | TypeScript |
FunctionDeclaration |
export function Root() {
const store = createStore(reducers);
return (
<BrowserRouter>
<Provider store={store}>
<Application />
</Provider>
</BrowserRouter>
);
} | LuisSaybe/seoullatte | web/js/page/root/index.tsx | TypeScript |
ArrowFunction |
async (req: Request, res: Response) => {
const { user, error, errorCode } = await UserServiceInstance.findById(
req.userId
);
if (error && errorCode) return res.status(errorCode).json({ error });
return res.status(200).json(user);
} | vipulchodankar/express-typescript-mongodb-boilerplate | src/controllers/user.ts | TypeScript |
ArrowFunction |
async (req: Request, res: Response) => {
const data: Partial<IUser> = req.body;
// Don't allow updating other fields
const allowedData = userSchema.update.noUnknown().cast(data);
const { user, error, errorCode } = await UserServiceInstance.update(
req.userId,
allowedData
);
if (error && errorCode) return res.status(errorCode).json({ error });
return res.status(200).json({ user, message: "Successfully updated user" });
} | vipulchodankar/express-typescript-mongodb-boilerplate | src/controllers/user.ts | TypeScript |
ArrowFunction |
async (req: Request, res: Response) => {
const { error, errorCode } = await UserServiceInstance.delete(req.userId);
if (error && errorCode) return res.status(errorCode).json({ error });
return res.status(200).json({ message: "Successfully deleted user" });
} | vipulchodankar/express-typescript-mongodb-boilerplate | src/controllers/user.ts | TypeScript |
ArrowFunction |
() => {
test.each([null, 'string', {}])(
'Throws when middleware is not an array (%j)',
(value) => {
// Act
const act = () => new HttpClient(value as [HippityMiddleware])
// Assert
expect(act).toThrow(new TypeError('Middleware stack must be an array'))
}
)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(value) => {
// Act
const act = () => new HttpClient(value as [HippityMiddleware])
// Assert
expect(act).toThrow(new TypeError('Middleware stack must be an array'))
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => new HttpClient(value as [HippityMiddleware]) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
it('Throws exception when send is called with no middleware registered', async () => {
// Arrange
const sut = new HttpClient()
// Act
const act = sut.send({})
// Assert
await expect(act).rejects.toThrow(
new Error(
'Reached end of pipeline. Use a middleware which terminates the pipeline.'
)
)
})
it('Throws if no middleware terminates', async () => {
// Arrange
const sut = new HttpClient().use((r, n) => n(r))
// Act
const act = sut.send({})
// Assert
await expect(act).rejects.toThrow(
new Error(
'Reached end of pipeline. Use a middleware which terminates the pipeline.'
)
)
})
it('Calls middleware in reverse order', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '2'
return n(r)
})
.use((r, n) => {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('321')
})
it('Calls terminator last', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '0'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '1'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('10')
})
it('Lets middleware switch request', async () => {
// Arrange
const middleware = jest.fn(() =>
Promise.resolve({ status: 200, success: true })
)
const sut = new HttpClient()
.use(middleware)
.use((_, n) => n({ changed: true }))
// Act
await sut.send({})
// Assert
expect(middleware).toHaveBeenCalledWith(
{ changed: true },
expect.any(Function)
)
})
it('Does not call middleware if one terminates earlier in the pipeline', async () => {
// Arrange
const middleware = jest.fn()
const sut = new HttpClient()
.use(middleware)
.use(() => Promise.resolve({ status: 200, success: true }))
// Act
await sut.send({})
// Assert
expect(middleware).not.toHaveBeenCalled()
})
it('Uses current request if middleware calls next without a request', async () => {
// Arrange
const middleware = jest.fn(() =>
Promise.resolve({ status: 200, success: true })
)
const sut = new HttpClient().use((_, n) => n()).use(middleware)
// Act
await sut.send({ changed: false })
// Assert
expect(middleware).toHaveBeenCalledWith(
{ changed: false },
expect.any(Function)
)
})
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const sut = new HttpClient()
// Act
const act = sut.send({})
// Assert
await expect(act).rejects.toThrow(
new Error(
'Reached end of pipeline. Use a middleware which terminates the pipeline.'
)
)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const sut = new HttpClient().use((r, n) => n(r))
// Act
const act = sut.send({})
// Assert
await expect(act).rejects.toThrow(
new Error(
'Reached end of pipeline. Use a middleware which terminates the pipeline.'
)
)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(r, n) => n(r) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '2'
return n(r)
})
.use((r, n) => {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('321')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(r, n) => {
order += '2'
return n(r)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(r, n) => {
order += '3'
return n(r)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '0'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '1'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('10')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
order += '0'
return Promise.resolve({ status: 200, success: true })
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(r, n) => {
order += '1'
return n(r)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const middleware = jest.fn(() =>
Promise.resolve({ status: 200, success: true })
)
const sut = new HttpClient()
.use(middleware)
.use((_, n) => n({ changed: true }))
// Act
await sut.send({})
// Assert
expect(middleware).toHaveBeenCalledWith(
{ changed: true },
expect.any(Function)
)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() =>
Promise.resolve({ status: 200, success: true }) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(_, n) => n({ changed: true }) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const middleware = jest.fn()
const sut = new HttpClient()
.use(middleware)
.use(() => Promise.resolve({ status: 200, success: true }))
// Act
await sut.send({})
// Assert
expect(middleware).not.toHaveBeenCalled()
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => Promise.resolve({ status: 200, success: true }) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const middleware = jest.fn(() =>
Promise.resolve({ status: 200, success: true })
)
const sut = new HttpClient().use((_, n) => n()).use(middleware)
// Act
await sut.send({ changed: false })
// Assert
expect(middleware).toHaveBeenCalledWith(
{ changed: false },
expect.any(Function)
)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(_, n) => n() | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
it('Returns body of result', async () => {
// Arrange
const sut = new HttpClient().use(() => {
return Promise.resolve({ status: 200, success: true, body: 'body' })
})
// Act
const response = await sut.$send({ GET: 'foo' })
// Assert
expect(response).toBe('body')
})
test('Requires validation', async () => {
// Arrange
const sut = new HttpClient().use(() =>
Promise.resolve({
success: false,
status: 200,
message: 'OK',
body: true,
})
)
// Act
const act = sut.$send({ method: 'DELETE' })
// Assert
await expect(act).rejects.toThrow(
new Error(
'Response does not indicate success\n\n' +
'Request: {\n "method": "DELETE"\n}\n\n' +
'Response: {\n "status": 200,\n "message": "OK",\n "body": true\n}'
)
)
})
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const sut = new HttpClient().use(() => {
return Promise.resolve({ status: 200, success: true, body: 'body' })
})
// Act
const response = await sut.$send({ GET: 'foo' })
// Assert
expect(response).toBe('body')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
return Promise.resolve({ status: 200, success: true, body: 'body' })
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
const sut = new HttpClient().use(() =>
Promise.resolve({
success: false,
status: 200,
message: 'OK',
body: true,
})
)
// Act
const act = sut.$send({ method: 'DELETE' })
// Assert
await expect(act).rejects.toThrow(
new Error(
'Response does not indicate success\n\n' +
'Request: {\n "method": "DELETE"\n}\n\n' +
'Response: {\n "status": 200,\n "message": "OK",\n "body": true\n}'
)
)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() =>
Promise.resolve({
success: false,
status: 200,
message: 'OK',
body: true,
}) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
it('Adds middleware to be called in reverse order', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(function a() {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use(function b(r, n) {
order += '2'
return n(r)
})
.use(function c(r, n) {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('321')
})
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(function a() {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use(function b(r, n) {
order += '2'
return n(r)
})
.use(function c(r, n) {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('321')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
it('Adds middleware to run before all others', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '2'
return n(r)
})
.use((r, n) => {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('321')
})
it('Adds middleware to run after all others but before terminating middleware', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '2'
return n(r)
})
.useAt(-1, (r, n) => {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('231')
})
it('Adds only middleware', async () => {
// Arrange
let order = ''
const sut = new HttpClient().useAt(-1, () => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('1')
})
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.use((r, n) => {
order += '2'
return n(r)
})
.useAt(-1, (r, n) => {
order += '3'
return n(r)
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('231')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient().useAt(-1, () => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
// Act
await sut.send({})
// Assert
expect(order).toEqual('1')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
() => {
it('Registers middleware when true', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.if(true, (c) =>
c.use((r, n) => {
order += '2'
return n(r)
})
)
// Act
await sut.send({})
// Assert
expect(order).toEqual('21')
})
it('Does not register middleware when false', async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.if(false, (c) =>
c.use((r, n) => {
order += '2'
return n(r)
})
)
// Act
await sut.send({})
// Assert
expect(order).toEqual('1')
})
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.if(true, (c) =>
c.use((r, n) => {
order += '2'
return n(r)
})
)
// Act
await sut.send({})
// Assert
expect(order).toEqual('21')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(c) =>
c.use((r, n) => {
order += '2'
return n(r)
}) | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
(r, n) => {
order += '2'
return n(r)
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
async () => {
// Arrange
let order = ''
const sut = new HttpClient()
.use(() => {
order += '1'
return Promise.resolve({ status: 200, success: true })
})
.if(false, (c) =>
c.use((r, n) => {
order += '2'
return n(r)
})
)
// Act
await sut.send({})
// Assert
expect(order).toEqual('1')
} | berkeleybross/hippity | src/client/http-client.test.ts | TypeScript |
ArrowFunction |
({ className }) => (
<main className={className}>
<h1>About</h1>
<AboutMDX />
</main> | aa-0921/gatsby-portfolio-first | src/pages/about.tsx | TypeScript |
ArrowFunction |
({ path }: { path: string }): JSX.Element => (
<>
<SEO title='about' | aa-0921/gatsby-portfolio-first | src/pages/about.tsx | TypeScript |
ArrowFunction |
(data: CharacterStore[]) => {
return data.map((data) => {
const character = new CharacterStore();
for (const key of Object.keys(data)) {
// @ts-ignore
character[key] = data[key];
}
const inventory = new InventoryStore(character, {
unit: data.inventory.unit,
coins: data.inventory.coins,
});
const attributes = new CharacterAttributesStore(character);
const skills = new CharacterSkillsStore(character);
const notes = new CharacterNotesStore();
attributes.values = data.attributes.values.map(
(attribute) => new CharacterAttribute(attribute, character)
);
skills.values = data.skills.values.map(
(skill) => new CharacterSkill(skill, character)
);
inventory.items = data.inventory.items.map(
(item) => new InventoryItem(item)
);
notes.values = data.notes.values.map(
(note) => new CharacterNote(note.text, note.date, note.id)
);
character.inventory = inventory;
character.attributes = attributes;
character.skills = skills;
character.notes = notes;
return character;
});
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(data) => {
const character = new CharacterStore();
for (const key of Object.keys(data)) {
// @ts-ignore
character[key] = data[key];
}
const inventory = new InventoryStore(character, {
unit: data.inventory.unit,
coins: data.inventory.coins,
});
const attributes = new CharacterAttributesStore(character);
const skills = new CharacterSkillsStore(character);
const notes = new CharacterNotesStore();
attributes.values = data.attributes.values.map(
(attribute) => new CharacterAttribute(attribute, character)
);
skills.values = data.skills.values.map(
(skill) => new CharacterSkill(skill, character)
);
inventory.items = data.inventory.items.map(
(item) => new InventoryItem(item)
);
notes.values = data.notes.values.map(
(note) => new CharacterNote(note.text, note.date, note.id)
);
character.inventory = inventory;
character.attributes = attributes;
character.skills = skills;
character.notes = notes;
return character;
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(attribute) => new CharacterAttribute(attribute, character) | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(skill) => new CharacterSkill(skill, character) | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(item) => new InventoryItem(item) | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(note) => new CharacterNote(note.text, note.date, note.id) | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(characters: CharacterStore[]) => {
return characters;
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(c) => c.id !== id | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ArrowFunction |
(c) => c.id === id | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
ClassDeclaration |
export class RootStore {
@format<any, any>(
(data: CharacterStore[]) => {
return data.map((data) => {
const character = new CharacterStore();
for (const key of Object.keys(data)) {
// @ts-ignore
character[key] = data[key];
}
const inventory = new InventoryStore(character, {
unit: data.inventory.unit,
coins: data.inventory.coins,
});
const attributes = new CharacterAttributesStore(character);
const skills = new CharacterSkillsStore(character);
const notes = new CharacterNotesStore();
attributes.values = data.attributes.values.map(
(attribute) => new CharacterAttribute(attribute, character)
);
skills.values = data.skills.values.map(
(skill) => new CharacterSkill(skill, character)
);
inventory.items = data.inventory.items.map(
(item) => new InventoryItem(item)
);
notes.values = data.notes.values.map(
(note) => new CharacterNote(note.text, note.date, note.id)
);
character.inventory = inventory;
character.attributes = attributes;
character.skills = skills;
character.notes = notes;
return character;
});
},
(characters: CharacterStore[]) => {
return characters;
}
)
characters: CharacterStore[] = [];
@ignore
selectedCharacterId: string = '';
selectCharacter(id: string) {
if (this.characterById(id)) {
this.selectedCharacterId = id;
}
}
@ignore
get currentCharacter(): CharacterStore | null {
return this.characterById(this.selectedCharacterId) || null;
}
language: string = 'de';
constructor() {
makeAutoObservable(this);
}
createCharacter(name: string) {
const character = new CharacterStore(name);
this.characters.push(character);
return character;
}
removeCharacter(id: string) {
this.characters = this.characters.filter((c) => c.id !== id);
}
characterById(id: string) {
return this.characters.find((c) => c.id === id);
}
setLanguage(lang: string) {
this.language = lang;
i18n.changeLanguage(lang);
}
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
MethodDeclaration |
selectCharacter(id: string) {
if (this.characterById(id)) {
this.selectedCharacterId = id;
}
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
MethodDeclaration |
createCharacter(name: string) {
const character = new CharacterStore(name);
this.characters.push(character);
return character;
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
MethodDeclaration |
removeCharacter(id: string) {
this.characters = this.characters.filter((c) => c.id !== id);
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
MethodDeclaration |
characterById(id: string) {
return this.characters.find((c) => c.id === id);
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
MethodDeclaration |
setLanguage(lang: string) {
this.language = lang;
i18n.changeLanguage(lang);
} | ph1p/rp-character-manager | src/store/root.ts | TypeScript |
FunctionDeclaration |
function alignToGrid(boxes: Box[], viewportWidth: number) {
if (viewportWidth === 0) {
return;
}
// Make Dagre's layout more "grid compatible" by centering each row and
// wrapping rows so they don't scroll offscreen
const splitWidth = viewportWidth - 40;
const itemsPerRow = Math.round(splitWidth / 280);
const itemWidth = (splitWidth - (itemsPerRow - 1) * PADDING) / itemsPerRow;
const rows: {top: number; items: Box[]}[] = [];
for (const box of boxes) {
if (rows[rows.length - 1]?.top === box.layout.top) {
rows[rows.length - 1].items.push(box);
} else {
rows.push({items: [box], top: box.layout.top});
}
}
let x = -1;
let y = INSET;
for (const {items} of rows) {
const centeringOffset =
items.length < itemsPerRow ? (splitWidth - items.length * (itemWidth + PADDING)) / 2 : 0;
for (const box of items) {
x++;
if (x >= itemsPerRow) {
y += box.layout.height + PADDING;
x = 0;
}
box.layout.width = itemWidth;
box.layout.left = INSET + centeringOffset + x * (itemWidth + PADDING);
box.layout.top = y;
}
y += items[0].layout.height + PADDING;
x = -1;
}
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
FunctionDeclaration |
function flattenToGrid(boxes: Box[], viewportWidth: number) {
if (viewportWidth === 0) {
return;
}
// Try to arrange the bundles so the downstream ones are generally lower in the grid.
// Algorithm: Iterate through the folders and insert each into the result set such that
// it is before things that depend on it and after things that it depends on.
// If we can't satisfy these (bi-directional deps are possible), we put at the midpoint.
const splitWidth = viewportWidth - 40;
const itemsPerRow = Math.round(splitWidth / 280);
const itemWidth = (splitWidth - (itemsPerRow - 1) * PADDING) / itemsPerRow;
let x = -1;
let y = INSET;
const centeringOffset =
boxes.length < itemsPerRow ? (splitWidth - boxes.length * (itemWidth + PADDING)) / 2 : 0;
boxes.forEach((box) => {
x++;
if (x >= itemsPerRow) {
x = 0;
y += box.layout.height + PADDING;
}
box.layout.top = y;
box.layout.left = INSET + centeringOffset + x * (itemWidth + PADDING);
box.layout.width = itemWidth;
});
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
FunctionDeclaration |
function expandBoxes(layout: Layout, expanded: string | null, viewportWidth: number) {
// Find the box we want to expand
const boxIdx = layout.boxes.findIndex((b) => b.id === expanded);
if (boxIdx === -1) {
return {boxes: layout.boxes, shadows: []};
}
const boxes: Box[] = JSON.parse(JSON.stringify(layout.boxes));
const box = boxes[boxIdx]!;
const shadow = {
top: box.layout.top + box.layout.height + PADDING / 2,
height: 0,
};
const toPushDown = boxes.filter((b) => b.layout.top >= shadow.top);
const contentsWithChildren: {[id: string]: string[]} = {};
box.contentIds.forEach((c) => (contentsWithChildren[c] = []));
const contentsEdges = uniqBy(
layout.edges
.filter((e) => contentsWithChildren[e.from] && contentsWithChildren[e.to])
.map((e) => ({
from: contentsWithChildren[e.from] ? e.from : layout.bundleForAssetId[e.from],
to: contentsWithChildren[e.to] ? e.to : layout.bundleForAssetId[e.to],
})),
JSON.stringify,
);
const contents =
contentsEdges.length > 0 && box.contentIds.length < 100
? runMinimalDagreLayout(contentsWithChildren, contentsEdges)
: {
boxes: Object.entries(contentsWithChildren).map(([bundleId, contentIds]) => ({
id: bundleId,
contentIds,
layout: {top: 0, left: 0, width: 250, height: 108},
})),
};
if (contentsEdges.length === 0 || contents.boxes.length > 10) {
flattenToGrid(contents.boxes, viewportWidth);
} else {
alignToGrid(contents.boxes, viewportWidth);
}
// Add the nodes for the childern
boxes.splice(boxIdx, 0, ...contents.boxes);
for (const box of contents.boxes) {
box.layout.top += shadow.top;
}
// Push the nodes beneath the shadow down
const contentBottom = Math.max(...contents.boxes.map((b) => b.layout.top + b.layout.height));
shadow.height = contentBottom - shadow.top + PADDING / 2;
toPushDown.forEach((box) => (box.layout.top += shadow.height));
return {boxes, shadows: [shadow]};
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
FunctionDeclaration |
function useAssetGridLayout(assetGraphData: GraphData | null, viewportWidth: number) {
return React.useMemo(() => {
if (!assetGraphData) {
return {bundles: {}, bundleForAssetId: {}, boxes: [], edges: []};
}
const assetIds = Object.keys(assetGraphData.nodes);
const bundles = identifyBundles(assetIds);
const bundleForAssetId: {[assetId: string]: string} = {};
for (const [bundleId, childrenIds] of Object.entries(bundles)) {
childrenIds.forEach((c) => (bundleForAssetId[c] = bundleId));
}
const unbundledAssetIds = assetIds.filter((id) => !bundleForAssetId[id]);
if (unbundledAssetIds.length) {
bundles[NONE_BUNDLE] = unbundledAssetIds;
bundles[NONE_BUNDLE].forEach((id) => (bundleForAssetId[id] = NONE_BUNDLE));
}
const edges = flatMap(Object.entries(assetGraphData.downstream), ([from, downstreams]) =>
Object.keys(downstreams).map((to) => ({from, to})),
);
const {boxes} = runMinimalDagreLayout(
bundles,
uniqBy(
edges.map((e) => ({from: bundleForAssetId[e.from], to: bundleForAssetId[e.to]})),
JSON.stringify,
),
);
if (boxes.length > 10) {
flattenToGrid(boxes, viewportWidth);
} else {
alignToGrid(boxes, viewportWidth);
}
return {bundles, bundleForAssetId, boxes, edges};
}, [assetGraphData, viewportWidth]);
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
() => {
const params = useParams();
const explorerPath = instanceAssetsExplorerPathFromString(params[0]);
const {assetGraphData} = useAssetGraphData(null, explorerPath.opsQuery || '*');
return (
<Box
flex={{direction: 'column', justifyContent: 'stretch'}} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(
bundles: {[prefixId: string]: string[]},
edges: {from: string; to: string}[],
) => {
const g = new dagre.graphlib.Graph({compound: true});
g.setGraph({
rankdir: 'TB',
marginx: 0,
marginy: 0,
nodesep: 20,
edgesep: 10,
ranksep: 20,
});
g.setDefaultEdgeLabel(() => ({}));
for (const [node, contentIds] of Object.entries(bundles)) {
g.setNode(node, {width: 250, height: contentIds.length ? 40 : 108});
}
for (const edge of edges) {
g.setEdge({v: edge.from, w: edge.to}, {weight: 1});
}
dagre.layout(g);
const boxes = Object.entries(bundles).map(([bundleId, contentIds]) => {
const {x, y, width, height} = g.node(bundleId);
return {id: bundleId, contentIds, layout: {top: y, left: x, width, height}};
});
// Note: This is important for other algorithms we run later, but we want to
// do it in the layer that is cached.
boxes.sort((a, b) => a.id.localeCompare(b.id));
return {boxes};
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
() => ({}) | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
([bundleId, contentIds]) => {
const {x, y, width, height} = g.node(bundleId);
return {id: bundleId, contentIds, layout: {top: y, left: x, width, height}};
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(a, b) => a.id.localeCompare(b.id) | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(box) => {
x++;
if (x >= itemsPerRow) {
x = 0;
y += box.layout.height + PADDING;
}
box.layout.top = y;
box.layout.left = INSET + centeringOffset + x * (itemWidth + PADDING);
box.layout.width = itemWidth;
} | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(b) => b.id === expanded | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(b) => b.layout.top >= shadow.top | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(c) => (contentsWithChildren[c] = []) | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(e) => contentsWithChildren[e.from] && contentsWithChildren[e.to] | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(e) => ({
from: contentsWithChildren[e.from] ? e.from : layout.bundleForAssetId[e.from],
to: contentsWithChildren[e.to] ? e.to : layout.bundleForAssetId[e.to],
}) | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
([bundleId, contentIds]) => ({
id: bundleId,
contentIds,
layout: {top: 0, left: 0, width: 250, height: 108},
}) | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
ArrowFunction |
(b) => b.layout.top + b.layout.height | unlearnai/dagster | js_modules/dagit/packages/core/src/assets/InstanceAssetGrid.tsx | TypeScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.