language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class SearchBar extends Component { constructor(props) { super(props); //super is calling the parent method (Component) this.state = {term: ''}; //whenever we use state we initialize it by creating a new object and assigning it to this.state } render() { return ( <div className="search-bar"> Search: <input value={this.state.term} //when we tell input that its value is provided by this.state.term, we turn the input into what is called a controlled component. A controlled component has its value set by state, so its value only changes when its state changes. onChange={(event) => this.onInputChange(event.target.value)}/> </div> ); } onInputChange(term) { this.setState({term}); this.props.onSearchTermChange(term); } //use this.state.term here because we are nor modifying or manipulating the value of term, but we are just referencing it, like saying hey here is what the value is, so it's okay to reference it like this, but don't do anything here like {this.state.term = '5'} where your modifying it (that is what this.setState is for!!! //We always manipulate our state with this.setState, it informs React the state is changing and this is what the new state is. // Only in the constructor we have this.state = an object, but to change our state everywhere else inside our component we use this.setState }
JavaScript
class ParseError { /** * @constructor * @param {string} message Error message */ constructor(message) { this.name = this.constructor.name; this.message = message; this.stack = (new Error(message)).stack; } }
JavaScript
class Paypal { MakePayment(user, amountInDollars) { console.log(`${user} made payment of ${amountInDollars}$ with PayPal`); } }
JavaScript
class PotentialOperationsResult { constructor(operations, reason) { this.operations = operations || []; if (reason) { this.reason = reason; } } }
JavaScript
class App extends Component { getChildContext () { return { muiTheme: getMuiTheme(MyRawTheme),}; } render() { //console.log(this.props); return ( <div style={{height:'100%',width:'100%'}}> {this.props.children} <Footer> </Footer> </div> ); } componentDidMount() { console.log('App initialized. (App component mounted , do some fetching data)'); } }
JavaScript
class WorkspaceTreeDataProvider { constructor() { this._onDidChangeTreeData = new vscode.EventEmitter(); this.onDidChangeTreeData = this._onDidChangeTreeData.event; this.extensionConfig; this.workspaceStorageDirectory; this.targetIconUri; this.getConfigs(); } // Gets user set configuration values. getConfigs() { return resolveConfigs(this.refresh.bind(this)) .then((configs) => { this.extensionConfig = configs; this.workspaceStorageDirectory = ( configs.workspaceStorageDirectory ); }) .catch((err) => vscode.window.showErrorMessage(err)); } // Rebuilds the Tree of workspaces and sub-folders. // Repopulates the Workspace Explorer view. refresh(targetIconUri) { this.getConfigs(); this.targetIconUri = targetIconUri; this._onDidChangeTreeData.fire(); } // Gets the parent of the current workspace file or folder. getParent(element) { return element.parent; } // Gets vscode Tree Items representing a workspace or folder. getTreeItem(element) { // Check if item is using an icon that must be force reloaded due // to a change icon action initiated by the user who overwrote the // original icon file. let useNewUri = false; if (this.targetIconUri) { const partialIconPath = this.targetIconUri.fsPath.replace( path.extname(this.targetIconUri.fsPath), '', ); const partialWorkspacePath = element.workspaceFileNameAndFilePath.replace( path.extname(element.workspaceFileNameAndFilePath), '', ); if (partialIconPath === partialWorkspacePath) { useNewUri = true; } } const treeItem = new WorkspaceTreeItem( element.label, element.workspaceFileNameAndFilePath, element.collapsableState, this.extensionConfig, useNewUri, ); if (useNewUri) { this.targetIconUri = ''; } return treeItem; } // This runs on activation and any time a collapsed item is expanded. async getChildren(element) { if (this.workspaceStorageDirectory === undefined) { return []; } if (element === undefined) { return findChildren(this.workspaceStorageDirectory); } return findChildren(element.workspaceFileNameAndFilePath); } }
JavaScript
class SentimentData { constructor(id) { this.id = id; this.is_positive = false; this.is_negative = false; this.is_love = false; this.is_anger = false; this.is_hatred = false; this.is_neutral = false; this.has_appeard = false; this.has_tagged = false; } get_data() { return { "id": this.id, "is_positive": this.is_positive, "is_negative": this.is_negative, "is_neutral": this.is_neutral, "is_love": this.is_love, "is_hatred": this.is_hatred, "is_anger": this.is_anger, "has_appeard": this.has_appeard, "has_tagged": this.has_tagged } } }
JavaScript
class TscTaskProvider { constructor(lazyClient) { this.lazyClient = lazyClient; this.tsconfigProvider = new tsconfigProvider_1.default(); } dispose() { this.tsconfigProvider.dispose(); } provideTasks(token) { return __awaiter(this, void 0, void 0, function* () { const rootPath = vscode.workspace.rootPath; if (!rootPath) { return []; } const command = yield this.getCommand(); const projects = yield this.getAllTsConfigs(token); return projects.map(configFile => { const configFileName = path.relative(rootPath, configFile); const identifier = { type: 'typescript', tsconfig: configFileName }; const buildTask = new vscode.Task(identifier, `build ${configFileName}`, 'tsc', new vscode.ShellExecution(`${command} -p "${configFile}"`), '$tsc'); buildTask.group = vscode.TaskGroup.Build; return buildTask; }); }); } resolveTask(_task) { return undefined; } getAllTsConfigs(token) { return __awaiter(this, void 0, void 0, function* () { const out = new Set(); const configs = (yield this.getTsConfigForActiveFile(token)).concat(yield this.getTsConfigsInWorkspace()); for (const config of configs) { if (yield exists(config)) { out.add(config); } } return Array.from(out); }); } getTsConfigForActiveFile(token) { return __awaiter(this, void 0, void 0, function* () { const editor = vscode.window.activeTextEditor; if (editor) { if (path.basename(editor.document.fileName).match(/^tsconfig\.(.\.)?json$/)) { return [editor.document.fileName]; } } const file = this.getActiveTypeScriptFile(); if (!file) { return []; } const res = yield this.lazyClient().execute('projectInfo', { file, needFileNameList: false }, token); if (!res || !res.body) { return []; } const { configFileName } = res.body; if (configFileName && !tsconfig_1.isImplicitProjectConfigFile(configFileName)) { return [configFileName]; } return []; }); } getTsConfigsInWorkspace() { return __awaiter(this, void 0, void 0, function* () { return Array.from(yield this.tsconfigProvider.getConfigsForWorkspace()); }); } getCommand() { return __awaiter(this, void 0, void 0, function* () { const platform = process.platform; if (platform === 'win32' && (yield exists(path.join(vscode.workspace.rootPath, 'node_modules', '.bin', 'tsc.cmd')))) { return path.join('.', 'node_modules', '.bin', 'tsc.cmd'); } else if ((platform === 'linux' || platform === 'darwin') && (yield exists(path.join(vscode.workspace.rootPath, 'node_modules', '.bin', 'tsc')))) { return path.join('.', 'node_modules', '.bin', 'tsc'); } else { return 'tsc'; } }); } getActiveTypeScriptFile() { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; if (document && (document.languageId === 'typescript' || document.languageId === 'typescriptreact')) { return this.lazyClient().normalizePath(document.uri); } } return null; } }
JavaScript
class TypeScriptTaskProviderManager { constructor(lazyClient) { this.lazyClient = lazyClient; this.taskProviderSub = undefined; this.disposables = []; vscode.workspace.onDidChangeConfiguration(this.onConfigurationChanged, this, this.disposables); this.onConfigurationChanged(); } dispose() { if (this.taskProviderSub) { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } this.disposables.forEach(x => x.dispose()); } onConfigurationChanged() { let autoDetect = vscode.workspace.getConfiguration('typescript.tsc').get('autoDetect'); if (this.taskProviderSub && autoDetect === 'off') { this.taskProviderSub.dispose(); this.taskProviderSub = undefined; } else if (!this.taskProviderSub && autoDetect === 'on') { this.taskProviderSub = vscode.workspace.registerTaskProvider('typescript', new TscTaskProvider(this.lazyClient)); } } }
JavaScript
class InternalOpenGateAPI { /** * @param {{ url: string,port: string,version: string,apiKey: string}} _options - this is configuration about Opengate North API. * @param {AmpliaREST} ampliaREST - this is a backend selected to manage a request to Opengate North API. */ constructor(northAmpliaREST, southAmpliaREST) { if (this.constructor === InternalOpenGateAPI) { throw new Error("Cannot construct Abstract instances directly"); } if (typeof northAmpliaREST !== "object") { throw new Error("Must instance mandatory parameter: northAmpliaREST"); } if (typeof southAmpliaREST !== "object") { throw new Error("Must instance mandatory parameter: southAmpliaREST"); } this.Napi = northAmpliaREST; this.Sapi = southAmpliaREST; this.EX = Expression; this.SE = SelectElement; this.operations = new Operations(this); this.alarms = new AlarmActions(this) this.entityBuilder = new EntityBuilder(this); } /** * This return a util to find a user * @return {UserFinder} */ newUserFinder() { return new UserFinder(this); } /** * This return a util to find a organization * @return {OrganizationFinder} */ newOrganizationFinder() { return new OrganizationFinder(this); } /** * This return a util to find a channel * @return {ChannelFinder} */ newChannelFinder() { return new ChannelFinder(this); } /** * This return a AreasSearchBuilder to build a specific AreasSearch * @return {AreasSearchBuilder} */ areasSearchBuilder() { return new AreasSearchBuilder(this); } /** * This return a DatasetsCatalogSearchBuilder to build a specific DatasetsCatalogSearc * @return {DatasetsCatalogSearchBuilder} */ datasetsCatalogSearchBuilder() { return new DatasetsCatalogSearchBuilder(this); } /** * This return a BulkSearchBuilder to build a specific BulkSearchBuilder * @return {BulkSearchBuilder} */ bulkSearchBuilder() { return new BulkSearchBuilder(this); } /** * This return a util to find and download a bulk * @return {BulkFinder} */ newBulkFinder() { return new BulkFinder(this); } /** * This return a util to find a area * @return {AreaFinder} */ newAreaFinder() { return new AreaFinder(this); } /** * This return a util to find a operation * @return {OperationFinder} */ newOperationFinder() { return new OperationFinder(this); } /** * This return a util to find Rule Configurations * @return {RuleConfigurationsFinder} */ newRuleConfigurationsFinder() { return new RuleConfigurationsFinder(this); } /** * This return a util to find Rule Configurations Templates * @return {RuleConfigurationsCatalog} */ newRuleConfigurationsCatalog() { return new RuleConfigurationsCatalog(this); } /** * This return a util to update a Rule Configuration * @return {RuleConfigurations} */ ruleConfigurationBuilder(organization, channel, name, ruleConfigObj) { return new RuleConfigurations(this, organization, channel, name, ruleConfigObj); } /** * This return a util to launch actions on a rule * @param {!string} organization - organization name of the rule * @param {!string} channel - channel name of the rule * @param {!string} name - rule name * @return {RuleConfigurationsActions} */ // newRuleConfigurationsActions(organization, channel, name) { // return new RuleConfigurationsActions(this, organization, channel, name); // } /** * This return a util to find a certificate * @return {CertificateFinder} */ newCertificateFinder() { return new CertificateFinder(this); } /** * This return a util to find a device * @return {DeviceFinder} */ newDeviceFinder() { return new DeviceFinder(this); } /** * This return a util to find a ticket * @return {TicketFinder} */ newTicketFinder() { return new TicketFinder(this); } /** * This return a util to find a Subscription * @return {SubscriptionsFinder} */ newSubscriptionsFinder() { return new SubscriptionsFinder(this); } /** * This return a util to find a Subscriber * @return {SubscribersFinder} */ newSubscribersFinder() { return new SubscribersFinder(this); } newEntityFinder() { return new EntityFinder(this); } /** * This return a util to create your own filter to make searching * @return {FilterBuilder} */ newFilterBuilder() { return new FilterBuilder(); } /** * This return a util to create your own select to make searching * @return {SelectBuilder} */ newSelectBuilder() { return new SelectBuilder(); } /** * This return a util to find devices by a defined filter * @return {QuickSearch} */ newQuickSearch(param, limit, type) { return new QuickSearch(this, param, limit, type); } /** * Create custom search with custom url and raw filter * @return {RawSearchBuilder} */ rawSearchBuilder() { return new RawSearchBuilder(this); } /** * This return a UsersSearchBuilder to build a specific UsersSearch * @return {UsersSearchBuilder} */ usersSearchBuilder() { return new UsersSearchBuilder(this); } /** * This return a DomainsSearchBuilder to build a specific DomainsSearch * @return {DomainsSearchBuilder} */ domainsSearchBuilder() { return new DomainsSearchBuilder(this); } /** * This return a DevicesSearchBuilder to build a specific DeviceSearch * @return {DevicesSearchBuilder} */ devicesSearchBuilder() { return new DevicesSearchBuilder(this); } /** * This return a AssetsSearchBuilder to build a specific AssetSearch * @return {AssetsSearchBuilder} */ assetsSearchBuilder() { return new AssetsSearchBuilder(this); } /** * This return a SubscribersSearchBuilder to build a specific DeviceSearch * @return {SubscribersSearchBuilder} */ subscribersSearchBuilder() { return new SubscribersSearchBuilder(this); } /** * This return a SubscriptionsSearchBuilder to build a specific DeviceSearch * @return {SubscriptionsSearchBuilder} */ subscriptionsSearchBuilder() { return new SubscriptionsSearchBuilder(this); } /** * This return a TicketsSearchBuilder to build a specific TicketSearch */ ticketsSearchBuilder() { return new TicketsSearchBuilder(this); } /** * This return a CommunicationsModuleTypeSearchBuilder to build a specific CommunicationsModuleTypeSearch * @return {CommunicationsModuleTypeSearchBuilder} */ communicationsModuleTypeSearchBuilder() { return new CommunicationsModuleTypeSearchBuilder(this); } /** * This return a FieldsDefinitionSearchBuilder to build a specific FieldsDefinitionSearchBuilder * @return {FieldsDefinitionSearchBuilder} */ fieldsDefinitionSearchBuilder() { return new FieldsDefinitionSearchBuilder(this); } /** * This return a MobilePhoneProviderSearchBuilder to build a specific MobilePhoneProviderTypeSearch * @return {MobilePhoneProviderSearchBuilder} */ mobilePhoneProviderSearchBuilder() { return new MobilePhoneProviderSearchBuilder(this); } /** * This return a IoTDatastreamPeriodSearchBuilder to build a specific IoTDatastreamPeriodSearchBuilder * @return {IoTDatastreamPeriodSearchBuilder} */ ioTDatastreamPeriodSearchBuilder() { return new IoTDatastreamPeriodSearchBuilder(this); } /** * This return a ResourceTypeSearchBuilder to build a specific ResourceTypeSearchBuilder * @return {ResourceTypeSearchBuilder} */ resourceTypeSearchBuilder() { return new ResourceTypeSearchBuilder(this); } /** * This return a AllowedResourceTypeSearchBuilder to build a specific AllowedResourceTypeSearchBuilder * @return {AllowedResourceTypeSearchBuilder} */ allowedResourceTypeSearchBuilder() { return new AllowedResourceTypeSearchBuilder(this); } /** * This return a IoTDatastreamAccessSearchBuilder to build a specific IoTDatastreamAccessSearchBuilder * @return {IoTDatastreamAccessSearchBuilder} */ ioTDatastreamAccessSearchBuilder() { return new IoTDatastreamAccessSearchBuilder(this); } /** * This return a IoTDatastreamStoragePeriodSearchBuilder to build a specific IoTDatastreamStoragePeriodSearchBuilder * @return {IoTDatastreamStoragePeriodSearchBuilder} */ ioTDatastreamStoragePeriodSearchBuilder() { return new IoTDatastreamStoragePeriodSearchBuilder(this); } /** * This return a TicketSeveritySearchBuilder to build a specific TicketSeveritySearchBuilder * @return {TicketSeveritySearchBuilder} */ ticketSeveritySearchBuilder() { return new TicketSeveritySearchBuilder(this); } /** * This return a TicketPrioritySearchBuilder to build a specific TicketPrioritySearchBuilder * @return {TicketPrioritySearchBuilder} */ ticketPrioritySearchBuilder() { return new TicketPrioritySearchBuilder(this); } /** * This return a TicketStatusSearchBuilder to build a specific TicketStatusSearchBuilder * @return {TicketStatusSearchBuilder} */ ticketStatusSearchBuilder() { return new TicketStatusSearchBuilder(this); } /** * This return a RuleConfigurationSeveritySearchBuilder to build a specific RuleConfigurationSeveritySearchBuilder * @return {RuleConfigurationSeveritySearchBuilder} */ // ruleConfigurationSeveritySearchBuilder() { // return new RuleConfigurationSeveritySearchBuilder(this); // } /** * This return a RulesSearchBuilder to build a specific RulesSearch * @return {RulesSearchBuilder} */ rulesSearchBuilder() { return new RulesSearchBuilder(this); } /** * This return a TasksSearchBuilder to build a specific TasksSearch * @return {TasksSearchBuilder} */ tasksSearchBuilder() { return new TasksSearchBuilder(this); } /** * This return a OperationsSearchBuilder to build a specific ExecutionssSearch * @return {OperationsSearchBuilder} */ operationsSearchBuilder() { return new OperationsSearchBuilder(this); } /** * This return a ExecutionsSearchBuilder to build a specific ExecutionsSearch * @return {ExecutionsSearchBuilder} */ executionsSearchBuilder() { return new ExecutionsSearchBuilder(this); } /** * This return a AlarmsSearchBuilder to build a specific AlarmsSearch * @return {AlarmsSearchBuilder} */ alarmsSearchBuilder() { return new AlarmsSearchBuilder(this); } /** * This return a DatastreamsSearchBuilder to build a specific DatastreamsSearchBuilder * @return {DatastreamsSearchBuilder} */ datastreamsSearchBuilder() { return new DatastreamsSearchBuilder(this); } /** * This return a DatamodelsSearchBuilder to build a specific DatamodelsSearchBuilder * @return {DatamodelsSearchBuilder} */ datamodelsSearchBuilder() { return new DatamodelsSearchBuilder(this); } /** * This return a FeedsSearchBuilder to build a specific FeedsSearchBuilder * @return {FeedsSearchBuilder} */ feedsSearchBuilder() { return new FeedsSearchBuilder(this); } /** * This return a DatapointsSearchBuilder to build a specific DatapointsSearchBuilder * @return {DatapointsSearchBuilder} */ datapointsSearchBuilder() { return new DatapointsSearchBuilder(this); } /** * This return a BundlesSearchBuilder to build a specific BundlesSearchBuilder * @return {BundlesSearchBuilder} */ bundlesSearchBuilder() { return new BundlesSearchBuilder(this); } /** * This return a CertificatesSearchBuilder to build a specific CertificatesSearchBuilder * @return {CertificatesSearchBuilder} */ certificatesSearchBuilder() { return new CertificatesSearchBuilder(this); } /** * */ basicTypesSearchBuilder() { return new BasicTypesSearchBuilder(this); } /** * This return a EntitiesSearchBuilder to build a specific EntitiesSearch * @return {EntitiesSearchBuilder} */ entitiesSearchBuilder() { return new EntitiesSearchBuilder(this); } /** * This return a DatasetEntitiesSearchBuilder to build a specific DatasetEntitiesSearch * @return {DatasetEntitiesSearchBuilder} */ datasetEntitiesSearchBuilder(organization, dataset) { return new DatasetEntitiesSearchBuilder(this, organization, dataset); } /** * This return a PlansSearchBuilder to build a specific PlansSearchBuilder * @return {PlansSearchBuilder} */ plansSearchBuilder() { return new PlansSearchBuilder(this); } /** * This return a BundlesBuilder to build a specific BundlesBuilder * @return {Bundles} */ bundlesBuilder() { return new Bundles(this); } /** * This return a util to find a bundle * @return {BundleFinder} */ newBundleFinder() { return new BundleFinder(this); } /** * This return a OrganizationsBuilder to build a specific OrganizationsBuilder * @return {Organizations} */ organizationsBuilder() { return new Organizations(this); } /** * This return a DomainsBuilder to build a specific DomainsBuilder * @return {Domain} */ domainsBuilder() { return new Domain(this); } /** * This return a util to find a domain * @return {DomainFinder} */ newDomainFinder() { return new DomainFinder(this); } /** * This return a util to create a user * @return {User} */ usersBuilder() { return new Users(this); } /** * This return a util to create a certificate * @return {Certificates} */ certificatesBuilder() { return new Certificates(this); } /** * This return a HardwaresSearchBuilder to build a specific HardwaresSearchBuilder * @return {HardwaresSearchBuilder} */ hardwaresSearchBuilder() { return new HardwaresSearchBuilder(this); } /** * This return a SoftwaresSearchBuilder to build a specific SoftwaresSearchBuilder * @return {SoftwaresSearchBuilder} */ softwaresSearchBuilder() { return new SoftwaresSearchBuilder(this); } /** * This return a OperationalStatusSearchBuilder to build a specific OperationalStatusSearchBuilder * @return {OperationalStatusSearchBuilder} */ operationalStatusSearchBuilder() { return new OperationalStatusSearchBuilder(this); } /** * This return a ServiceGroupSearchBuilder to build a specific ServiceGroupSearchBuilder * @return {ServiceGroupSearchBuilder} */ serviceGroupSearchBuilder() { return new ServiceGroupSearchBuilder(this); } /** * This return a AdministrativeStateSearchBuilder to build a specific AdministrativeStateSearchBuilder * @return {AdministrativeStateSearchBuilder} */ administrativeStateSearchBuilder() { return new AdministrativeStateSearchBuilder(this); } /** * This return a DevicesSouth to build a specific DevicesSouth * @return {DeviceMessage} */ deviceMessageBuilder() { return new DeviceMessage(this); } /** * This return a datastreamBuilder to build a specific Datastream * @return {Datastream} */ datastreamBuilder() { return new Datastream(this); } /** * This return a datapointsBuilder to build a specific Datapoint * @return {Datapoint} */ datapointsBuilder() { return new Datapoint(this); } /** * @return {Hardware} */ hardwareMessageBuilder() { return new Hardware(this); } /** * @return {Software} */ softwareMessageBuilder() { return new Software(this); } /** * @return {Storage} */ storageMessageBuilder() { return new Storage(this); } /** * @return {Usage} */ usageMessageBuilder() { return new Usage(this); } /** * @return {PowerSupply} */ powerSupplyMessageBuilder() { return new PowerSupply(this); } /** * @return {CommsModuleMessage} */ commsModuleMessageMessageBuilder() { return new CommsModuleMessage(this); } /** * @return {SubscriberMessage} */ subscriberMessageBuilder() { return new SubscriberMessage(this); } /** * @return {SubscriptionMessage} */ subscriptionMessageBuilder() { return new SubscriptionMessage(this); } /** * @return {Mobile} */ mobileMessageMessageBuilder() { return new Mobile(this); } /** * This return a util to operation actions on an operation * @param {!string} operationId - identifier of operation * @return {OperationActions} */ newOperationActions(operationId) { return new OperationActions(this, operationId); } /** * This return a util to manage actions over periodicities * @param {!string} taskId - identifier of operation * @return {PeriodicityActions} */ newPeriodicityActions(taskId) { return new PeriodicityActions(this, taskId); } /** * This return a WorkgroupRelationsBuilder to build a specific workgroup relation * @return {WorkgroupRelations} */ workgroupRelationsBuilder() { return new WorkgroupRelations(this); } /** * This return a WorkgroupRelationsFinder * @return {WorkgroupRelationsFinder} */ newWorkgroupRelationsFinder() { return new WorkgroupRelationsFinder(this); } /** * This return a WorkgroupsBuilder to build a specific workgroup * @return {Workgroups} */ workgroupsBuilder() { return new Workgroups(this); } /** * This return a util to find a workgroup * @return {WorkgroupFinder} */ newWorkgroupFinder() { return new WorkgroupFinder(this); } /** * This return a WorkgroupsSearchBuilder to build a specific WorkgroupsSearch * @return {WorkgroupsSearchBuilder} */ workgroupsSearchBuilder() { return new WorkgroupsSearchBuilder(this); } /** * This return a ChannelsBuilder to build a specific WorkgroupsSearch * @return {Channels} */ channelsBuilder() { return new Channels(this); } /** * This return a AreasBuilder to build a specific area * @return {Areas} */ areasBuilder() { return new Areas(this); } /** * This return a ChannelsSearchBuilder to build a specific ChannelsSearch * @return {ChannelsSearchBuilder} */ channelsSearchBuilder() { return new ChannelsSearchBuilder(this); } /** * This return a UserProfilesSearchBuilder to build a specific UserProfilesSearchBuilder * @return {UserProfilesSearchBuilder} */ userProfilesSearchBuilder() { return new UserProfilesSearchBuilder(this); } /** * This return a Datamodels to build a specific Datamodels * @return {Datamodels} */ datamodelsBuilder(organization) { return new Datamodels(this, organization); } /** * This return a DatamodelsHelper to build a specific DatamodelsHelper * @return {DatamodelsHelper} */ datamodelsHelper(organization, datamodel) { return new DatamodelsHelper(this, organization, datamodel); } /** * This return a util to find a datamodel * @return {DatamodelsFinder} */ newDatamodelsFinder() { return new DatamodelsFinder(this); } /** * This return a datastream to build a specific Datastream * @return {DatastreamsBuilder} */ datastreamsBuilder() { return new DatastreamsBuilder(this); } /** * This return a Qrating to build a specific Qrating * @return {QratingsBuilder} */ qratingsBuilder() { return new QratingsBuilder(this); } /** * This return a CountryCodesSearchBuilder to build a specific CountryCodesSearchBuilder * @return {CountryCodesSearchBuilder} */ countryCodesSearchBuilder() { return new CountryCodesSearchBuilder(this); } /** * This return a TimezoneSearchBuilder to build a specific TimezoneSearchBuilder * @return {TimezoneSearchBuilder} */ timezoneSearchBuilder() { return new TimezoneSearchBuilder(this); } /** * This return a UserLanguagesSearchBuilder to build a specific UserLanguagesSearchBuilder * @return {UserLanguagesSearchBuilder} */ userLanguagesSearchBuilder() { return new UserLanguagesSearchBuilder(this); } }
JavaScript
class Colours { constructor() { this.start = { r:0, g:0, b:0}; this.end = {r:255, g:255, b:255}; } startx(r, g, b) { this.start = { r:r, g:g, b:b }; } starty(rgb) { this.start = this.hexToRgb(rgb); } endx(r, g, b) { this.end = { r:r, g:g, b:b }; } endy(rgb) { this.end = this.hexToRgb(rgb); } componentToHex(c) { var hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } rgbToHex(colour) { return "#" + this.componentToHex(colour.r) + this.componentToHex(colour.g) + this.componentToHex(colour.b); } hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } range(count) { var rint = (this.end.r - this.start.r) / count, gint = (this.end.g - this.start.g) / count, bint = (this.end.b - this.start.b) / count, colours = [ this.rgbToHex(this.start) ], c = 0; for (c=1; c<count-1; c++) { colours.push(this.rgbToHex({ r: Math.round(this.start.r + c*rint), g: Math.round(this.start.g + c*gint), b: Math.round(this.start.b + c*bint) })); } colours.push(this.rgbToHex(this.end)); return colours; } }
JavaScript
class URLTokenBaseHTTPClient { constructor(tokenHeader, baseServer, port, defaultHeaders = {}) { this.defaultHeaders = defaultHeaders; const baseServerURL = new url_parse_1.default(baseServer, {}); if (typeof port !== 'undefined') { baseServerURL.set('port', port.toString()); } if (baseServerURL.protocol.length === 0) { throw new Error('Invalid base server URL, protocol must be defined.'); } this.baseURL = baseServerURL; this.tokenHeader = tokenHeader; } /** * Compute the URL for a path relative to the instance's address * @param relativePath - A path string * @returns A URL string */ addressWithPath(relativePath) { const address = new url_parse_1.default(path_1.default.posix.join(this.baseURL.pathname, relativePath), this.baseURL); return address.toString(); } /** * Convert a superagent response to a valid BaseHTTPClientResponse * Modify the superagent response * @private */ static superagentToHTTPClientResponse(res) { if (res.body instanceof ArrayBuffer) { // Handle the case where the body is an arraybuffer which happens in the browser res.body = new Uint8Array(res.body); } return res; } /** * Make a superagent error more readable. For more info, see https://github.com/visionmedia/superagent/issues/1074 */ static formatSuperagentError(err) { if (err.response) { try { const decoded = JSON.parse(Buffer.from(err.response.body).toString()); // eslint-disable-next-line no-param-reassign err.message = `Network request error. Received status ${err.response.status}: ${decoded.message}`; } catch (err2) { // ignore any error that happened while we are formatting the original error } } return err; } async get(relativePath, query, requestHeaders = {}) { const r = request .get(this.addressWithPath(relativePath)) .set(this.tokenHeader) .set(this.defaultHeaders) .set(requestHeaders) .responseType('arraybuffer') .query(query); try { const res = await r; return URLTokenBaseHTTPClient.superagentToHTTPClientResponse(res); } catch (err) { throw URLTokenBaseHTTPClient.formatSuperagentError(err); } } async post(relativePath, data, query, requestHeaders = {}) { const r = request .post(this.addressWithPath(relativePath)) .set(this.tokenHeader) .set(this.defaultHeaders) .set(requestHeaders) .query(query) .serialize((o) => o) // disable serialization from superagent .responseType('arraybuffer') .send(Buffer.from(data)); // Buffer.from necessary for superagent try { const res = await r; return URLTokenBaseHTTPClient.superagentToHTTPClientResponse(res); } catch (err) { throw URLTokenBaseHTTPClient.formatSuperagentError(err); } } async delete(relativePath, data, query, requestHeaders = {}) { const r = request .delete(this.addressWithPath(relativePath)) .set(this.tokenHeader) .set(this.defaultHeaders) .set(requestHeaders) .query(query) .serialize((o) => o) // disable serialization from superagent .responseType('arraybuffer') .send(Buffer.from(data)); // Buffer.from necessary for superagent try { const res = await r; return URLTokenBaseHTTPClient.superagentToHTTPClientResponse(res); } catch (err) { throw URLTokenBaseHTTPClient.formatSuperagentError(err); } } }
JavaScript
class AudioPlayer { /** * Default constructor * * @param {Object[]} clips - The audio clips to play * @param {string} clips[].src - The audio source * @param {boolean} clips[].loop - Should we loop the audio clip */ constructor (clips) { // Be sure to copy this.clips = Array.from(clips); this.audio = document.getElementById('ado'); // For now disable the audio // this.audio.volume = 0; } /** * Play a new audio clip * * @param {Object} clip - The new audio source * @param {string} clip.src - The source of this clip * @param {boolean} clip.loop - Should we loop this clip * @return {Promise} */ play (clip) { return new Promise((resolve) => { // Stop anything that might be playing // this.audio.stop(); // Set the new source this.audio.src = clip.src; this.audio.loop = clip.loop; this.audio.muted = false; if (clip.muted) { this.audio.muted = true; } // Load it this.audio.load(); // Play it! this.audio.play(); this.audio.onended = () => { resolve(); }; }); } /** * Keep track of which clip to play */ stateLoop () { const clip = this.clips.shift(); if (clip !== undefined) { if (clip.loop) { // Eventually advance will be called this.play(clip); } else { // Call stateloop when the clip is done playing this.play(clip).then(() => { this.stateLoop(); }); } } } /** * Force the next audio clip to play * * @param {number} numToSkip - The number of audio clips to skip */ advance (numToSkip = 0) { for (let i = 0; i < numToSkip; i++) { this.clips.shift(); } this.stateLoop(); } /** * Start playing the audio for this scene */ start () { this.stateLoop(); } }
JavaScript
class OrderView { constructor(rootNode, nodesPool, childNodeType) { /** * The root node to manage with. * * @type {HTMLElement} */ this.rootNode = rootNode; /** * Factory for newly created DOM elements. * * @type {Function} */ this.nodesPool = nodesPool; /** * Holder for sizing and positioning of the view. * * @type {ViewSizeSet} */ this.sizeSet = new ViewSizeSet(); /** * Node type which the order view will manage while rendering the DOM elements. * * @type {String} */ this.childNodeType = childNodeType.toUpperCase(); /** * The visual index of currently processed row. * * @type {Number} */ this.visualIndex = 0; /** * The list of DOM elements which are rendered for this render cycle. * * @type {HTMLElement[]} */ this.collectedNodes = []; } /** * Sets the size for rendered elements. It can be a size for rows, cells or size for row * headers etc. it depends for what table renderer this instance was created. * * @param {Number} size * @returns {OrderView} */ setSize(size) { this.sizeSet.setSize(size); return this; } /** * Sets the offset for rendered elements. The offset describes the shift between 0 and * the first rendered element according to the scroll position. * * @param {Number} offset * @returns {OrderView} */ setOffset(offset) { this.sizeSet.setOffset(offset); return this; } /** * Checks if this instance of the view shares the root node with another instance. This happens only once when * a row (TR) as a root node is managed by two OrderView instances. If this happens another DOM injection * algorithm is performed to achieve consistent order. * * @returns {Boolean} */ isSharedViewSet() { return this.sizeSet.isShared(); } /** * Returns rendered DOM element based on visual index. * * @param {Number} visualIndex * @returns {HTMLElement} */ getNode(visualIndex) { return visualIndex < this.collectedNodes.length ? this.collectedNodes[visualIndex] : null; } /** * Returns currently processed DOM element. * * @returns {HTMLElement} */ getCurrentNode() { const length = this.collectedNodes.length; return length > 0 ? this.collectedNodes[length - 1] : null; } /** * Returns rendered child count for this instance. * * @returns {Number} */ getRenderedChildCount() { const { rootNode, sizeSet } = this; let childElementCount = 0; if (this.isSharedViewSet()) { let element = rootNode.firstElementChild; while (element) { if (element.tagName === this.childNodeType) { childElementCount += 1; } else if (sizeSet.isPlaceOn(WORKING_SPACE_TOP)) { break; } element = element.nextElementSibling; } } else { childElementCount = rootNode.childElementCount; } return childElementCount; } /** * Setups and prepares all necessary properties and start the rendering process. * This method has to be called only once (at the start) for the render cycle. */ start() { this.collectedNodes.length = 0; this.visualIndex = 0; const { rootNode, sizeSet } = this; const isShared = this.isSharedViewSet(); const { nextSize } = sizeSet.getViewSize(); let childElementCount = this.getRenderedChildCount(); while (childElementCount < nextSize) { const newNode = this.nodesPool(); if (!isShared || (isShared && sizeSet.isPlaceOn(WORKING_SPACE_BOTTOM))) { rootNode.appendChild(newNode); } else { rootNode.insertBefore(newNode, rootNode.firstChild); } childElementCount += 1; } const isSharedPlacedOnTop = (isShared && sizeSet.isPlaceOn(WORKING_SPACE_TOP)); while (childElementCount > nextSize) { rootNode.removeChild(isSharedPlacedOnTop ? rootNode.firstChild : rootNode.lastChild); childElementCount -= 1; } } /** * Renders the DOM element based on visual index (which is calculated internally). * This method has to be called as many times as the size count is met (to cover all previously rendered DOM elements). */ render() { const { rootNode, sizeSet } = this; let visualIndex = this.visualIndex; if (this.isSharedViewSet() && sizeSet.isPlaceOn(WORKING_SPACE_BOTTOM)) { visualIndex += sizeSet.sharedSize.nextSize; } let node = rootNode.childNodes[visualIndex]; if (node.tagName !== this.childNodeType) { const newNode = this.nodesPool(); rootNode.replaceChild(newNode, node); node = newNode; } this.collectedNodes.push(node); this.visualIndex += 1; } /** * Ends the render process. * This method has to be called only once (at the end) for the render cycle. */ end() { } }
JavaScript
class Flags { constructor() { this.data = {}; } init(data) { this.data = data; } get(key, defaultValue) { return key in this.data ? this.data[key] : defaultValue; } reset = () => { this.data = {}; } }
JavaScript
class HomeView extends React.Component { state = { } componentDidMount () { } render () { console.log(this.props) return ( <React.Fragment> <App /> </React.Fragment> ) } }
JavaScript
class SearchInput extends Component { constructor(props) { super(props); this.state = { value: '' }; this.onInputChange = this.onInputChange.bind(this); } onInputChange(event) { // filter data at every keystroke in the input form // lifting up state here, we are calling `filterData` // which was passed in `props` from its parent component this.props.filterData(event.target.value); event.preventDefault(); } render() { return ( <div className='searchInput'> <input className='searchInput__input' type='text' placeholder='Type here to search' onChange={this.onInputChange} /> </div> ); } }
JavaScript
class RuntimeClass { constructor(desc) { this.apiVersion = RuntimeClass.apiVersion; this.handler = desc.handler; this.kind = RuntimeClass.kind; this.metadata = desc.metadata; } }
JavaScript
class RuntimeClassList { constructor(desc) { this.apiVersion = RuntimeClassList.apiVersion; this.items = desc.items.map((i) => new RuntimeClass(i)); this.kind = RuntimeClassList.kind; this.metadata = desc.metadata; } }
JavaScript
class MeteorFileCollection extends FileCollection { /** * @constructor MeteorFileCollection * @param {String} name The name you want to use to refer to the FileCollection. * Be sure to use the same name in Node and browser code so that they can * communicate over DDP. * @param {Object} options * @param {Mongo.Collection} options.collection The collection to use * @param {DDPConnection} options.DDP The DDP connection to use * * Additional options documented in FileCollection class */ constructor(name, options) { const { collection, DDP, ...opts } = options; super(name, opts); if (!collection) throw new Error(`MeteorFileCollection "${name}": You must pass the "collection" option`); if (!DDP) throw new Error(`MeteorFileCollection "${name}": You must pass the "DDP" option`); this.DDP = DDP; this.mongoCollection = collection; } /** * @method _insert * @param {Object} doc An object to be sent to the server over DDP to be inserted. * @returns {Promise<Object>} A Promise that resolves with the inserted object. */ _insert(doc) { return new Promise((resolve, reject) => { this.DDP.call(`FileCollection/INSERT/${this.name}`, { doc }, (error, insertedDoc) => { if (error) { reject(error); } else { resolve(insertedDoc); } }); }); } /** * @method _update * @param {String} id A FileRecord ID * @param {Object} modifier An object to be sent to the server over DDP to be used as the update modifier. * @returns {Promise<Object>} A Promise that resolves with the updated object. */ _update(id, modifier) { return new Promise((resolve, reject) => { this.DDP.call(`FileCollection/UPDATE/${this.name}`, { _id: id, modifier }, (error, updatedDoc) => { if (error) { reject(error); } else { resolve(updatedDoc); } }); }); } /** * @method _remove * @param {String} id A FileRecord ID * @returns {Promise<Number>} A Promise that resolves with 1 if success */ _remove(id) { return new Promise((resolve, reject) => { this.DDP.call(`FileCollection/REMOVE/${this.name}`, { _id: id }, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); } /** * @method _findOne * @param {Object|String} id A FileRecord ID or MongoDB selector * @param {Object} options Options object to be passed through to Meteor's findOne * @returns {Promise<Object|undefined>} A Promise that resolves with the document or undefined */ async _findOne(...args) { return this._findOneLocal(...args); } /** * @method _find * @param {Object|String} selector A FileRecord ID or MongoDB selector * @param {Object} options Options object to be passed through to Meteor's findOne * @returns {Promise<Cursor>} A Promise that resolves with the Meteor find cursor */ async _find(...args) { return this._findLocal(...args); } /** * @method _findOneLocal * @param {Object|String} id A FileRecord ID or MongoDB selector * @param {Object} options Options object to be passed through to Meteor's findOne * @returns {Object|undefined} The document or undefined */ _findOneLocal(selector, options) { return this.mongoCollection.findOne(selector || {}, options || {}); } /** * @method _findLocal * @param {Object|String} selector A FileRecord ID or MongoDB selector * @param {Object} options Options object to be passed through to Meteor's findOne * @returns {Cursor} The Meteor find cursor */ _findLocal(selector, options) { return this.mongoCollection.find(selector || {}, options || {}); } }
JavaScript
class Appointment extends Component{ constructor(props) { super(props); this.state = { Name: "", date: new Date(), option: "Yes", Department: [{name: "Pediatrics", Doctor: ["Geri O'Leary", "Khalil Bailey", "Laura Bellini", "Yohan Campito", "Alyssa Chan"]}, {name: "Maternity", Doctor: ["Ranen Carter", "James Chu", "Kristina Cooper", "Michael Dore"]}, {name: "Geriatrics", Doctor: ["Sarah Eaton", "Paul Giampa", "Jill Gupta"]}, {name: "Psychiatrics", Doctor: ["Mohammed Gupta", "Alexia Hirt", "Patricia Ivey", "Jacob Jones", "Ronny Capelli", "Zach Blanco"]}, {name: "Dermatology", Doctor: ["Elena Kunz", "Lenonard Lu", "Craig Matthews"]}], defaultDept: "--Choose Department--", Doctor: [], defaultDoc: "--Choose Doctor--" }; this.handleDateChange = this.handleDateChange.bind(this); // this.handleVisitChange = this.handleVisitChange.bind(this); // this.handleDeptChange = this.handleDeptChange.bind(this); // this.handleDocChange = this.handleDocChange.bind(this); } handleNameChange = event => { this.setState({ Name: event.target.value }); } handleDateChange (date) { this.setState({ date: date }); } handleVisitChange = event => { this.setState({ option: event.target.value }); } handleDeptChange = event => { this.setState({defaultDept: event.target.value}); this.setState({Doctor: this.state.Department.find(dept => dept.name === event.target.value).Doctor}) } handleDocChange = event => { this.setState({defaultDoc: event.target.value}); } onFormSubmit = (event) => { // to prevent page reload on form submit event.preventDefault(); this.props.handleSubmit(this.state); this.setState({ Name: "", date: new Date(), option: "Yes", Department: [{name: "Pediatrics", Doctor: ["Geri O'Leary", "Khalil Bailey", "Laura Bellini", "Yohan Campito", "Alyssa Chan"]}, {name: "Maternity", Doctor: ["Ranen Carter", "James Chu", "Kristina Cooper", "Michael Dore"]}, {name: "Geriatrics", Doctor: ["Sarah Eaton", "Paul Giampa", "Jill Gupta"]}, {name: "Psychiatrics", Doctor: ["Mohammed Gupta", "Alexia Hirt", "Patricia Ivey", "Jacob Jones", "Ronny Capelli", "Zach Blanco"]}, {name: "Dermatology", Doctor: ["Elena Kunz", "Lenonard Lu", "Craig Matthews"]}], defaultDept: "--Choose Department--", Doctor: [], defaultDoc: "--Choose Doctor--" }); } render(){ return( <form onSubmit = {this.onFormSubmit}> <label>Name:</label> <input type="text" onChange= {this.handleNameChange} value={this.state.Name} ></input> <div> <strong>Department and Doctor</strong> <div> <label>Department</label> <select placeholder="Department" value={this.state.defaultDept} onChange={this.handleDeptChange}> <option>--Choose Department--</option> {this.state.Department.map((e,key) => {return <option key = {key}>{e.name}</option>})} </select> </div> <div> <label>Doctor</label> <select placeholder="Doctor" value={this.state.defaultDoc} onChange={this.handleDocChange}> <option>--Choose Doctor--</option> {this.state.Doctor.map((e,key) => {return <option key = {key} >{e}</option>})} </select> </div> </div> <div> <strong>Appointment Date</strong> <DatePicker selected={this.state.date} onChange={this.handleDateChange} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="Time" dateFormat="MMMM d, yyyy h:mm aa" minDate={new Date()} /> </div> <div> <strong>First Time Visit?</strong> <nav> <input type="radio" value= "Yes" checked={this.state.option === "Yes"} onChange={this.handleVisitChange}/>Yes <input type="radio" value= "No" checked={this.state.option === "No"} onChange={this.handleVisitChange}/>No </nav> </div> <button onClick = {this.onFormSubmit}>Submit</button> </form> ) } }
JavaScript
class AbstractFullDetailsView extends Component { render() { const { path, definition, curations, harvest, modalView, isMobile, visible, previewDefinition, readOnly, session, inspectedCuration, component } = this.props const { changes } = this.state return modalView ? ( <Modal closable={false} footer={null} // if it's mobile do not center the Modal centered={!isMobile} destroyOnClose={true} visible={visible} width={isMobile ? '95%' : '85%'} className="fullDetaiView__modal" > {visible && ( <FullDetailComponent curations={curations} definition={definition} harvest={harvest} path={path} readOnly={readOnly} modalView={modalView} onChange={this.onChange} handleClose={this.handleClose} handleSave={this.handleSave} handleRevert={this.handleRevert} previewDefinition={previewDefinition} changes={changes} applyCurationSuggestion={this.applyCurationSuggestion} getCurationData={this.getCurationData} inspectedCuration={inspectedCuration} component={component} /> )} </Modal> ) : ( <> <FullDetailComponent curations={curations} definition={definition} harvest={harvest} path={path} readOnly={readOnly} modalView={false} onChange={this.onChange} changes={changes} previewDefinition={previewDefinition} handleRevert={this.handleRevert} applyCurationSuggestion={this.applyCurationSuggestion} getCurationData={this.getCurationData} inspectedCuration={inspectedCuration} component={component} renderContributeButton={ <div className="d-contents"> {!isEmpty(changes) && ( <Button className="revert-btn mr-2" disabled={isEmpty(changes) || isEmpty(harvest.item)} onClick={e => this.handleRevert()} > Revert </Button> )} <Button className="contribute-btn" disabled={isEmpty(changes) || isEmpty(harvest.item)} onClick={this.doPromptContribute} > Contribute </Button> </div> } /> <ContributePrompt ref={this.contributeModal} onLogin={this.handleLogin} actionHandler={this.doContribute} definitions={get(definition, 'item.coordinates') ? [get(definition, 'item.coordinates')] : []} /> </> ) } }
JavaScript
class AcceptReplInputAction extends editorExtensions_1.EditorAction { constructor() { super({ id: 'repl.action.acceptInput', label: nls.localize({ key: 'actions.repl.acceptInput', comment: ['Apply input from the debug console input box'] }, "REPL Accept Input"), alias: 'REPL Accept Input', precondition: debug_1.CONTEXT_IN_DEBUG_REPL, kbOpts: { kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus, primary: 3 /* Enter */, weight: 100 /* EditorContrib */ } }); } run(accessor, editor) { suggestController_1.SuggestController.get(editor).acceptSelectedSuggestion(false, true); accessor.get(IPrivateReplService).acceptReplInput(); } }
JavaScript
class Sortie extends WorldstateObject { /** * @param {Object} data The data for all daily sorties * @param {Object} deps The dependencies object * @param {MarkdownSettings} deps.mdConfig The markdown settings * @param {Translator} deps.translator The string translator * @param {TimeDateFunctions} deps.timeDate The time and date functions * @param {Object} deps.sortieData The data used to parse sorties * @param {SortieVariant} deps.SortieVariant The sortie variant parser * @param {string} deps.locale Locale to use for translations */ constructor(data, { mdConfig, translator, timeDate, sortieData, SortieVariant, locale, }) { super(data, { timeDate }); const opts = { mdConfig, translator, timeDate, sortieData, SortieVariant, locale, }; /** * The markdown settings * @type {MarkdownSettings} * @private */ this.mdConfig = mdConfig; Object.defineProperty(this, 'mdConfig', { enumerable: false, configurable: false }); /** * The time and date functions * @type {TimeDateFunctions} * @private */ this.timeDate = timeDate; Object.defineProperty(this, 'timeDate', { enumerable: false, configurable: false }); /** * The date and time at which the sortie starts * @type {Date} */ this.activation = timeDate.parseDate(data.Activation); /** * The date and time at which the sortie ends * @type {Date} */ this.expiry = timeDate.parseDate(data.Expiry); /** * The sortie's reward pool * @type {string} */ this.rewardPool = translator.languageString(data.Reward, locale); /** * The sortie's variants * @type {Array.<SortieVariant>} */ this.variants = data.Variants.map((v) => new SortieVariant(v, opts)); /** * The sortie's boss * @type {string} */ this.boss = translator.sortieBoss(data.Boss, locale); /** * The sortie's faction * @type {string} */ this.faction = translator.sortieFaction(data.Boss, locale); /** * The sortie's faction * @type {string} */ this.factionKey = translator.sortieFaction(data.boss, 'en'); /** * Whether or not this is expired (at time of object creation) * @type {boolean} */ this.expired = this.isExpired(); /** * ETA string (at time of object creation) * @type {String} */ this.eta = this.getETAString(); } /** * Get the sortie's boss * @returns {string} */ getBoss() { return this.boss; } /** * Get the sortie's faction * @returns {string} */ getFaction() { return this.faction; } /** * Gets a string indicating how long it will take for the sortie to end * @returns {string} */ getETAString() { return this.timeDate.timeDeltaToString(this.timeDate.fromNow(this.expiry)); } /** * Get whether or not the sortie has expired * @returns {boolean} */ isExpired() { return this.timeDate.fromNow(this.expiry) < 0; } /** * Returns the sortie's string representation * @returns {string} */ toString() { if (this.isExpired()) { return `${this.mdConfig.codeMulti}There's currently no sortie${this.mdConfig.lineEnd}` + `${this.mdConfig.blockEnd}`; } const variantString = this.variants.map((v) => v.toString()).join(''); return `${this.mdConfig.codeMulti}${this.getBoss()}: ends in ${this.getETAString()}` + `${this.mdConfig.doubleReturn}${variantString}${this.mdConfig.blockEnd}`; } }
JavaScript
class GeocoderMapbox { getClient() { const libLoaded = typeof window !== 'undefined' && window.mapboxgl && window.mapboxSdk; if (!libLoaded) { throw new Error('Mapbox libraries are required for GeocoderMapbox'); } if (!this._client) { this._client = window.mapboxSdk({ accessToken: window.mapboxgl.accessToken, countries: ['us'], }); } return this._client; } // Public API // /** * Search places with the given name. * * @param {String} search query for place names * * @return {Promise<{ search: String, predictions: Array<Object>}>} * results of the geocoding, should have the original search query * and an array of predictions. The format of the predictions is * only relevant for the `getPlaceDetails` function below. */ getPlacePredictions(search) { return this.getClient() .geocoding.forwardGeocode({ query: search, limit: 5, language: [config.locale], countries: ['us'] }) .send() .then(response => { return { search, predictions: response.body.features, }; }); } /** * Get the ID of the given prediction. */ getPredictionId(prediction) { return prediction.id; } /** * Get the address text of the given prediction. */ getPredictionAddress(prediction) { if (prediction.predictionPlace) { // default prediction defined above return prediction.predictionPlace.address; } // prediction from Mapbox geocoding API return prediction.place_name; } /** * Fetch or read place details from the selected prediction. * * @param {Object} prediction selected prediction object * * @return {Promise<util.propTypes.place>} a place object */ getPlaceDetails(prediction) { if (this.getPredictionId(prediction) === CURRENT_LOCATION_ID) { return userLocation().then(latlng => { return { address: '', origin: latlng, bounds: locationBounds(latlng, config.maps.search.currentLocationBoundsDistance), }; }); } if (prediction.predictionPlace) { return Promise.resolve(prediction.predictionPlace); } return Promise.resolve({ address: this.getPredictionAddress(prediction), origin: placeOrigin(prediction), bounds: placeBounds(prediction), }); } }
JavaScript
class PricePVPC20TD extends Endpoint { constructor(startDate, endDate) { const url = "https://api.esios.ree.es/indicators/1001"; const params = { start_date: startDate.toISOString(), end_date: endDate.toISOString() } super(url, params); } }
JavaScript
class ThresholdWatch extends BaseWatch { constructor(props = {}) { props.id = props.id || uuid.v4(); props.type = WATCH_TYPES.THRESHOLD; super(props); this.index = props.index; this.timeField = props.timeField; this.triggerIntervalSize = props.triggerIntervalSize || DEFAULT_VALUES.TRIGGER_INTERVAL_SIZE; this.triggerIntervalUnit = props.triggerIntervalUnit || DEFAULT_VALUES.TRIGGER_INTERVAL_UNIT; this.aggType = props.aggType || DEFAULT_VALUES.AGG_TYPE; this.aggField = props.aggField; this.termSize = props.termSize || DEFAULT_VALUES.TERM_SIZE; this.termField = props.termField; this.thresholdComparator = props.thresholdComparator || DEFAULT_VALUES.THRESHOLD_COMPARATOR; this.timeWindowSize = props.timeWindowSize || DEFAULT_VALUES.TIME_WINDOW_SIZE; this.timeWindowUnit = props.timeWindowUnit || DEFAULT_VALUES.TIME_WINDOW_UNIT; //NOTE: The threshold must be of the appropriate type, i.e.,number/date. //Conversion from string must occur by consumer when assigning a //value to this property. this.threshold = props.threshold || DEFAULT_VALUES.THRESHOLD; } get hasTermsAgg() { return Boolean(this.termField); } get termOrder() { return this.thresholdComparator === COMPARATORS.GREATER_THAN ? SORT_ORDERS.DESCENDING : SORT_ORDERS.ASCENDING; } get titleDescription() { const staticPart = `Send an alert when a specific condition is met.`; if (isNaN(this.triggerIntervalSize)) { return staticPart; } const timeUnitLabel = getTimeUnitsLabel(this.triggerIntervalUnit, this.triggerIntervalSize); return `${staticPart} This will run every ${this.triggerIntervalSize} ${timeUnitLabel}.`; } get upstreamJson() { const result = super.upstreamJson; Object.assign(result, { index: this.index, timeField: this.timeField, triggerIntervalSize: this.triggerIntervalSize, triggerIntervalUnit: this.triggerIntervalUnit, aggType: this.aggType, aggField: this.aggField, termSize: this.termSize, termField: this.termField, thresholdComparator: this.thresholdComparator, timeWindowSize: this.timeWindowSize, timeWindowUnit: this.timeWindowUnit, threshold: this.threshold }); return result; } static fromUpstreamJson(upstreamWatch) { return new ThresholdWatch(upstreamWatch); } get DEFAULT_VALUES() { return DEFAULT_VALUES; } static typeName = 'Threshold Alert'; static iconClass = ''; static selectMessage = 'Send an alert on a specific condition'; static isCreatable = true; static selectSortOrder = 1; }
JavaScript
class PerpetualFinance { constructor(network = 'mainnet') { this.providerUrl = XDAI_PROVIDER; this.network = network; this.provider = new Ethers.providers.JsonRpcProvider(this.providerUrl); this.gasLimit = GAS_LIMIT; this.contractAddressesUrl = CONTRACT_ADDRESSES; this.amm = {}; this.priceCache = {}; this.cacheExpirary = {}; this.pairAmountCache = {}; switch (network) { case 'mainnet': this.contractAddressesUrl += 'production.json'; break; case 'kovan': this.contractAddressesUrl += 'staging.json'; break; default: { const err = `Invalid network ${network}`; logger.error(err); throw Error(err); } } this.loadedMetadata = this.load_metadata(); } async load_metadata() { try { const metadata = await fetch(this.contractAddressesUrl).then((res) => res.json() ); const layer2 = Object.keys(metadata.layers.layer2.contracts); for (var key of layer2) { if (metadata.layers.layer2.contracts[key].name === 'Amm') { this.amm[key] = metadata.layers.layer2.contracts[key].address; } else { this[key] = metadata.layers.layer2.contracts[key].address; } } this.layer2AmbAddr = metadata.layers.layer2.externalContracts.ambBridgeOnXDai; this.xUsdcAddr = metadata.layers.layer2.externalContracts.usdc; this.loadedMetadata = true; return true; } catch (err) { return false; } } async update_price_loop() { if (Object.keys(this.cacheExpirary).length > 0) { for (let pair in this.cacheExpirary) { if (this.cacheExpirary[pair] <= Date.now()) { delete this.cacheExpirary[pair]; delete this.priceCache[pair]; } } for (let pair in this.cacheExpirary) { let amm = new Ethers.Contract( this.amm[pair], AmmArtifact.abi, this.provider ); await Promise.allSettled([ amm.getInputPrice(0, { d: Ethers.utils.parseUnits( this.pairAmountCache[pair], DEFAULT_DECIMALS ), }), amm.getOutputPrice(0, { d: Ethers.utils.parseUnits( this.pairAmountCache[pair], DEFAULT_DECIMALS ), }), ]).then((values) => { if (!Object.prototype.hasOwnProperty.call(this.priceCache, pair)) { this.priceCache[pair] = []; } this.priceCache[pair][0] = this.pairAmountCache[pair] / Ethers.utils.formatUnits(values[0].value.d); this.priceCache[pair][1] = Ethers.utils.formatUnits(values[1].value.d) / this.pairAmountCache[pair]; }); } } setTimeout(this.update_price_loop.bind(this), 10000); // update every 10 seconds } // get XDai balance async getXdaiBalance(wallet) { try { const xDaiBalance = await wallet.getBalance(); return Ethers.utils.formatEther(xDaiBalance); } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error xDai balance lookup'); return reason; } } // get XDai USDC balance async getUSDCBalance(wallet) { try { const layer2Usdc = new Ethers.Contract( this.xUsdcAddr, TetherTokenArtifact.abi, wallet ); let layer2UsdcBalance = await layer2Usdc.balanceOf(wallet.address); const layer2UsdcDecimals = await layer2Usdc.decimals(); return Ethers.utils.formatUnits(layer2UsdcBalance, layer2UsdcDecimals); } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error balance lookup'); return reason; } } // get allowance async getAllowance(wallet) { // instantiate a contract and pass in provider for read-only access const layer2Usdc = new Ethers.Contract( this.xUsdcAddr, TetherTokenArtifact.abi, wallet ); try { const allowanceForClearingHouse = await layer2Usdc.allowance( wallet.address, this.ClearingHouse ); return Ethers.utils.formatUnits( allowanceForClearingHouse, DEFAULT_DECIMALS ); } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error allowance lookup'); return reason; } } // approve async approve(wallet, amount) { try { // instantiate a contract and pass in wallet const layer2Usdc = new Ethers.Contract( this.xUsdcAddr, TetherTokenArtifact.abi, wallet ); const tx = await layer2Usdc.approve( this.ClearingHouse, Ethers.utils.parseUnits(amount, DEFAULT_DECIMALS) ); // TO-DO: We may want to supply custom gasLimit value above return tx.hash; } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error approval'); return reason; } } //open Position async openPosition(side, margin, levrg, pair, minBaseAmount, wallet) { try { const quoteAssetAmount = { d: Ethers.utils.parseUnits(margin, DEFAULT_DECIMALS), }; const leverage = { d: Ethers.utils.parseUnits(levrg, DEFAULT_DECIMALS) }; const minBaseAssetAmount = { d: Ethers.utils.parseUnits(minBaseAmount, DEFAULT_DECIMALS), }; const clearingHouse = new Ethers.Contract( this.ClearingHouse, ClearingHouseArtifact.abi, wallet ); const tx = await clearingHouse.openPosition( this.amm[pair], side, quoteAssetAmount, leverage, minBaseAssetAmount, { gasLimit: this.gasLimit } ); return tx; } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error opening position'); return reason; } } //close Position async closePosition(wallet, pair, minimalQuote) { try { const minimalQuoteAsset = { d: Ethers.utils.parseUnits(minimalQuote, DEFAULT_DECIMALS), }; const clearingHouse = new Ethers.Contract( this.ClearingHouse, ClearingHouseArtifact.abi, wallet ); const tx = await clearingHouse.closePosition( this.amm[pair], minimalQuoteAsset, { gasLimit: this.gasLimit } ); return tx; } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error closing position'); return reason; } } //get active position async getPosition(wallet, pair) { try { const positionValues = {}; const clearingHouse = new Ethers.Contract( this.ClearingHouse, ClearingHouseArtifact.abi, wallet ); let premIndex = 0; await Promise.allSettled([ clearingHouse.getPosition(this.amm[pair], wallet.address), clearingHouse.getLatestCumulativePremiumFraction(this.amm[pair]), clearingHouse.getPositionNotionalAndUnrealizedPnl( this.amm[pair], wallet.address, Ethers.BigNumber.from(PNL_OPTION_SPOT_PRICE) ), ]).then((values) => { positionValues.openNotional = Ethers.utils.formatUnits( values[0].value.openNotional.d, DEFAULT_DECIMALS ); positionValues.size = Ethers.utils.formatUnits( values[0].value.size.d, DEFAULT_DECIMALS ); positionValues.margin = Ethers.utils.formatUnits( values[0].value.margin.d, DEFAULT_DECIMALS ); positionValues.cumulativePremiumFraction = Ethers.utils.formatUnits( values[0].value.lastUpdatedCumulativePremiumFraction.d, DEFAULT_DECIMALS ); premIndex = Ethers.utils.formatUnits( values[1].value.d, DEFAULT_DECIMALS ); positionValues.pnl = Ethers.utils.formatUnits( values[2].value.unrealizedPnl.d, DEFAULT_DECIMALS ); positionValues.positionNotional = Ethers.utils.formatUnits( values[2].value.positionNotional.d, DEFAULT_DECIMALS ); }); positionValues.entryPrice = Math.abs( positionValues.openNotional / positionValues.size ); positionValues.fundingPayment = (premIndex - positionValues.cumulativePremiumFraction) * positionValues.size; // * -1 return positionValues; } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error getting active position'); return reason; } } //get active margin async getActiveMargin(wallet) { try { const clearingHouseViewer = new Ethers.Contract( this.ClearingHouseViewer, ClearingHouseViewerArtifact.abi, wallet ); const activeMargin = await clearingHouseViewer.getPersonalBalanceWithFundingPayment( this.xUsdcAddr, wallet.address ); return activeMargin / (1e18).toString(); } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error getting active position'); return reason; } } // get Price async getPrice(side, amount, pair) { try { let price; this.cacheExpirary[pair] = Date.now() + UPDATE_PERIOD; this.pairAmountCache[pair] = amount; if (!Object.prototype.hasOwnProperty.call(this.priceCache, pair)) { const amm = new Ethers.Contract( this.amm[pair], AmmArtifact.abi, this.provider ); if (side === 'buy') { price = await amm.getInputPrice(0, { d: Ethers.utils.parseUnits(amount, DEFAULT_DECIMALS), }); price = amount / Ethers.utils.formatUnits(price.d); } else { price = await amm.getOutputPrice(0, { d: Ethers.utils.parseUnits(amount, DEFAULT_DECIMALS), }); price = Ethers.utils.formatUnits(price.d) / amount; } } else { if (side === 'buy') { price = this.priceCache[pair][0]; } else { price = this.priceCache[pair][1]; } } return price; } catch (err) { logger.error(err); let reason; err.reason ? (reason = err.reason) : (reason = 'error getting Price'); return reason; } } // get getFundingRate async getFundingRate(pair) { try { let funding = {}; const amm = new Ethers.Contract( this.amm[pair], AmmArtifact.abi, this.provider ); await Promise.allSettled([ amm.getUnderlyingTwapPrice(3600), amm.getTwapPrice(3600), amm.nextFundingTime(), ]).then((values) => { funding.indexPrice = parseFloat( Ethers.utils.formatUnits(values[0].value.d) ); funding.markPrice = parseFloat( Ethers.utils.formatUnits(values[1].value.d) ); funding.nextFundingTime = parseInt(values[2].value.toString()); }); funding.rate = (funding.markPrice - funding.indexPrice) / 24 / funding.indexPrice; return funding; } catch (err) { logger.error(err)(); let reason; err.reason ? (reason = err.reason) : (reason = 'error getting fee'); return reason; } } }
JavaScript
class ComparatorRule extends Rule { constructor() { super(); this._cmps = [(a, b) => a === b]; } /** * Adds a comparator function to use for comparing the two values. * @param {Function} fn */ addComparator(fn) { this._cmps.push(fn); } /** * Compares `a` and `b`, returning true if they're equal. This loops * through all comparators we have and returns true if ANY of them * return true. * * @param {*} a * @param {*} b * @return {Boolean} */ compare(a, b) { for (let i = 0; i < this._cmps.length; i++) { if (this._cmps[i](a, b)) { return true; } } return false; } }
JavaScript
class Toolbar extends Container { static get $name() { return 'Toolbar'; } // Factoryable type name static get type() { return 'toolbar'; } static get configurable() { return { defaultType : 'button', /** * Custom CSS class to add to toolbar widgets * @config {String} * @category CSS */ widgetCls : null, layout : 'default' }; } createWidget(widget) { if (widget === '->') { widget = { type : 'widget', cls : 'b-toolbar-fill' }; } else if (widget === '|') { widget = { type : 'widget', cls : 'b-toolbar-separator' }; } else if (typeof widget === 'string') { widget = { type : 'widget', cls : 'b-toolbar-text', html : widget }; } const result = super.createWidget(widget); if (this.widgetCls) { result.element.classList.add(this.widgetCls); } return result; } }
JavaScript
class Broadcaster { /** * This function initialises paramters for Broadcaster * @memberof Broadcaster */ constructor(ip, broadcast_address, port, messagingServer, messagingClient){ this.ip = ip; this.broadcast_address = broadcast_address; this.port = port; this.broadcaster = null; this.messagingServer = messagingServer; this.messagingClient = messagingClient; } /** * This function fires up the Mulitcast service * @memberof Broadcaster */ init(){ this.broadcaster = _dgram.createSocket({type: 'udp4', reuseAddr: true}); this.broadcaster.bind(this.port); this.broadcaster.on('listening', this.listenerFn.bind(this)); this.broadcaster.on('message', this.on_message_receive.bind(this)); } /** * Function that gets called when the multicast service listens for messages on the port. * * @listens event:listening * @memberof Broadcaster */ listenerFn(){ this.broadcaster.addMembership(this.broadcast_address, this.ip); console.log(`* Multicast Server listening on: ${this.ip}:${this.port}`); console.log(`* Running server discovery`); // Prepare discovery message let messageBuffer = Buffer.from(JSON.stringify({origin: this.ip, body: BROADCAST_MESSAGE_REQUEST_MSG_SERVER}) ); this.send_message(messageBuffer); } /** * Function to send the message over Multicast * * @param {Buffer} message Message to send over the multicast * @memberof Broadcaster */ send_message(message){ this.broadcaster.send(message, 0, message.length, this.port, this.broadcast_address, ()=>{ console.info('* Sending message') }); } /** * This method gets called when the multicast service listens for messages on the port. * * @listens event:message * @memberof Broadcaster * * @param {Buffer} messageBuffer Message received over Multicast * @param {rinfo} [rinfo] Information about host from where the message originated */ on_message_receive(messageBuffer, rinfo){ let message = JSON.parse(messageBuffer.toString()); if(message.origin === this.ip){ return; } switch(message.body){ // If someone is requesting information about Messaging server case BROADCAST_MESSAGE_REQUEST_MSG_SERVER: // If we are indeed messaging server if(WS_SERVER_FLAG){ // the timeout is added to avoid any conflicts setTimeout(()=>{ // Send acknowledgement. Yes this is messaging server. let response = Buffer.from( JSON.stringify({origin: this.ip, body: BROADCAST_MESSAGE_ACK_MSG_SERVER}) ); this.broadcaster.send(response,0,response.length, this.port, this.broadcast_address); },100); } break; case BROADCAST_MESSAGE_ACK_MSG_SERVER: console.log(` -> Websockets Server discovered at: ${message.origin}`); console.log(` -> Closing local Messaging Server.`); this.messagingServer.setWSFlag(false); // reinit messaging client //this.messagingClient break; default: console.log('Broadcast Receiver received unrecognized message!'); break; } } }
JavaScript
class DisneylandParisWaltDisneyStudios extends DisneyParis { /** * Create a new DisneylandParisWaltDisneyStudios object */ constructor(options = {}) { options.name = options.name || 'Walt Disney Studios - Disneyland Paris'; options.timezone = options.timezone || 'Europe/Paris'; // set park's location as it's entrance options.latitude = options.latitude || 48.868271; options.longitude = options.longitude || 2.780719; // Disney API configuration for Disneyland Paris Walt Disney Studios options.parkId = options.parkId || 'P2'; // inherit from base class super(options); } }
JavaScript
class Leg { // questo metodo viene chiamato quando "istanzio" la classe, creando un oggetto constructor(name, scene) { // spessore gamba const thickness = 0.2; // altezza coscia const tighHeight = 1; // altezza stinco const calfHeight = 1.2; // lunghezza piede const footLength = thickness*2; // radice let root = this.root = new BABYLON.Mesh(name, scene); // materiale let material = new BABYLON.StandardMaterial(name+"-mat", scene); material.diffuseColor.set(0.63,0.75,0.8); material.specularColor.set(0.1,0.1,0.1); // coscia (n.b. l'altezza del box è un po' più piccola di tighHeight // per motivi estetici) let tigh = this.tigh = BABYLON.MeshBuilder.CreateBox(name+'-tigh', { width:thickness, depth:thickness, height:tighHeight * 0.8 }, scene); tigh.parent = root; tigh.material = material; // per comodità voglio che l'origine della coscia sia nel punto più alto (articolazione dell'anca) // così i movimenti sono più facili tigh.bakeTransformIntoVertices(BABYLON.Matrix.Translation(0,-tighHeight/2,0)); // parte bassa della gamba (n.b. anche in questo caso il box è un po' // più corto) let calf = this.calf = BABYLON.MeshBuilder.CreateBox(name+'-calf', { width:thickness, depth:thickness, height:calfHeight * 0.8 }, scene); calf.material = material; // la parte bassa ha origine in corrispondenza dell'articolazione del ginocchio // è figlia della coscia calf.bakeTransformIntoVertices(BABYLON.Matrix.Translation(0,-calfHeight/2,0)); calf.position.y = -tighHeight; calf.parent = tigh; // piede let foot = this.foot = BABYLON.MeshBuilder.CreateBox(name+'-foot', { width:footLength, height:0.1, depth:thickness }, scene); foot.material = material; foot.bakeTransformIntoVertices(BABYLON.Matrix.Translation(footLength/2,-0.05,0)); foot.position.y = -calfHeight; foot.parent = calf; // fine del costruttore } // questo metodo muove le articolazioni in modo che il piede si trovi // a coordinate x,y (nel sistema di riferimento di root, cioè dell'intera gamba) setFootPosition(x,y) { let theta = Math.atan2(x,-y); let d = (new BABYLON.Vector3(x,y,0)).length(); let beta = Math.acos(d/2); this.tigh.rotation.z = theta + beta; this.calf.rotation.z = -(Math.PI - 2*(Math.PI/2 - beta)); // voglio che il piede resti sostanzialmente orizzontale, // quindi lo ruoto in modo // da contrastare la rotazione che arriva da calf e tigh let gamma = -(this.tigh.rotation.z + this.calf.rotation.z); // per motivi estetici altero la posizione del piede in funzione // dell'angolo beta gamma -= beta * 3 - 1.98; this.foot.rotation.z = +gamma; } }
JavaScript
class Book{ constructor(title,author,year,gender){ this.title = title; this.author = author; this.year = year; this.gender = gender; } bookiInfo(){ return `${this.title} is a book of ${this.gender} wrote by ${this.author} in the year ${this.year}`; } getAuthor(){ return this.author; } getGender(){ return this.gender; } }
JavaScript
class Vector { /** * @constructor * @param {Number} [x=0] X coordinate * @param {Number} [y=0] Y coordinate */ constructor(x, y) { /** * @type {Number} */ this.x = x || 0; /** * @type {Number} */ this.y = y || ((y !== 0) ? this.x : 0); } /** * Set vector values. * @method set * @memberof Vector# * @param {number} [x=0] Position of the point on the x axis * @param {number} [y=0] Position of the point on the y axis * @return {Vector} Vector itself for chaining. */ set(x, y) { this.x = x || 0; this.y = y || ((y !== 0) ? this.x : 0); return this; } /** * Clone this vector. * @method clone * @memberof Vector# * @return {Vector} The cloned vector. */ clone() { return Vector.create(this.x, this.y); } /** * Copy values from another vector. * @method copy * @memberof Vector# * @param {Vector} v Vector to copy from. * @return {Vector} Self for chaining. */ copy(v) { this.x = v.x; this.y = v.y; return this; } /** * Add to vector values. * @method add * @memberof Vector# * @param {number|Vector} x Number or `Vector` to add to self. * @param {number} [y] Number to add to `y`. * @return {Vector} Self for chaining. */ add(x, y) { this.x += x instanceof Vector ? x.x : x; this.y += x instanceof Vector ? x.y : (y || ((y !== 0) ? x : 0)); return this; } /** * Subtract from vector values. * @method subtract * @memberof Vector# * @param {number|Vector} x Number or `Vector` to subtract from. * @param {number} [y] Number to subtract from `y`. * @return {Vector} Self for chaining. */ subtract(x, y) { this.x -= x instanceof Vector ? x.x : x; this.y -= x instanceof Vector ? x.y : (y || ((y !== 0) ? x : 0)); return this; } /** * Multiply self with another vector or 2 numbers. * @method multiply * @memberof Vector# * @param {number|Vector} x Number or `Vector` to multiply. * @param {number} [y] Number to multiply to `y`. * @return {Vector} Self for chaining. */ multiply(x, y) { this.x *= x instanceof Vector ? x.x : x; this.y *= x instanceof Vector ? x.y : (y || ((y !== 0) ? x : 0)); return this; } /** * Divide self by another vector or 2 numbers. * @method divide * @memberof Vector# * @param {number|Vector} x Number or `Vector` to divide. * @param {number} [y] Number to divide by. * @return {Vector} Self for chaining. */ divide(x, y) { this.x /= x instanceof Vector ? x.x : x; this.y /= x instanceof Vector ? x.y : (y || ((y !== 0) ? x : 0)); return this; } /** * Get distance of two vectors. * @method distance * @memberof Vector# * @param {Vector} vector Target vector to calculate distance from. * @return {number} Distance. */ distance(vector) { const x = vector.x - this.x; const y = vector.y - this.y; return Math.sqrt(x * x + y * y); } /** * Get squared euclidian distance of two vectors. * @method squaredDistance * @memberof Vector# * @param {Vector} vector Target vector to calculate distance from. * @return {number} Squared distance value. */ squaredDistance(vector) { const x = vector.x - this.x; const y = vector.y - this.y; return x * x + y * y; } /** * Get length of vector. * @method length * @memberof Vector# * @return {number} Length of this vector. */ length() { return Math.sqrt(this.squaredLength()); } /** * Get squared length of vector. * @method squaredLength * @memberof Vector# * @return {number} Squared length of this vector. */ squaredLength() { return this.x * this.x + this.y * this.y; } /** * Dot operation with another vector. * @method dot * @memberof Vector# * @param {Vector} [vector] Vector to dot with. * @return {number} Result of dot operation. */ dot(vector) { if (vector instanceof Vector) { return this.x * vector.x + this.y * vector.y; } else { return this.x * this.x + this.y * this.y; } } /** * Get normalized dot of vector. * @method dotNormalized * @memberof Vector# * @param {Vector} [vector] Vector to dot with * @return {number} Result of the dot operation. */ dotNormalized(vector) { const len1 = this.length(); const x1 = this.x / len1; const y1 = this.y / len1; if (vector instanceof Vector) { const len2 = vector.length(); const x2 = vector.x / len2; const y2 = vector.y / len2; return x1 * x2 + y1 * y2; } else { return x1 * x1 + y1 * y1; } } /** * Rotate vector in radians. * @method rotate * @memberof Vector# * @param {number} angle Angle to rotate. * @return {Vector} Self for chaining. */ rotate(angle) { const c = Math.cos(angle); const s = Math.sin(angle); const x = this.x * c - this.y * s; const y = this.y * c + this.x * s; this.x = x; this.y = y; return this; } /** * Normalize vector. * @method normalize * @memberof Vector# * @return {Vector} Self for chaining */ normalize() { const len = this.length(); this.x /= len || 1; this.y /= len || 1; return this; } /** * Limit vector values. * @method limit * @memberof Vector# * @param {Vector} vector Clamp this vector to a limitation(vector) * @return {Vector} Self for chaining. */ limit(vector) { this.x = clamp(this.x, -vector.x, vector.x); this.y = clamp(this.y, -vector.y, vector.y); return this; } /** * Get angle vector angle or angle between two vectors. * @method angle * @memberof Vector# * @param {Vector} [vector] Target vector to calculate with, angle of self is returned when it is not provided. * @return {number} Angle between self and target. */ angle(vector) { if (vector) { return Math.atan2(vector.y - this.y, vector.x - this.x); } else { return Math.atan2(this.y, this.x); } } /** * Get angle between two vectors from origin. * @method angleFromOrigin * @memberof Vector# * @param {Vector} vector The vector to calculate angle from. * @return {number} Angle. */ angleFromOrigin(vector) { return Math.atan2(vector.y, vector.x) - Math.atan2(this.y, this.x); } /** * Round vector values. * @method round * @memberof Vector# * @return {Vector} Self for chaining */ round() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; } /** * Returns true if the given point is equal to this point * @method equals * @memberof Vector# * @param {Vector} vector Vector to compare to. * @return {boolean} Whether the two vectors are equal */ equals(vector) { return (vector.x === this.x) && (vector.y === this.y); } /** * Change this vector to be perpendicular to what it was before. (Effectively * roatates it 90 degrees in a clockwise direction) * @method perp * @memberof Vector# * @return {Vector} Self for chaining. */ perp() { const x = this.x; this.x = this.y; this.y = -x; return this; } /** * Reverse this vector * @method reverse * @memberof Vector# * @return {Vector} Self for chaining. */ reverse() { this.x = -this.x; this.y = -this.y; return this; } /** * Project this vector on to another vector. * @method project * @memberof Vector# * @param {Vector} other The vector to project onto * @return {Vector} Self for chaining. */ project(other) { const amt = this.dot(other) / other.squaredLength(); this.x = amt * other.x; this.y = amt * other.y; return this; } /** * Project this vector onto a vector of unit length. This is slightly more efficient * than `project` when dealing with unit vectors. * @method projectN * @memberof Vector# * @param {Vector} other The unit vector to project onto * @return {Vector} Self for chaining. */ projectN(other) { const amt = this.dot(other); this.x = amt * other.x; this.y = amt * other.y; return this; } /** * Reflect this vector on an arbitrary axis. * @method reflect * @memberof Vector# * @param {Vector} axis The vector representing the axis * @return {Vector} Self for chaining. */ reflect(axis) { const x = this.x; const y = this.y; this.project(axis).multiply(2); this.x -= x; this.y -= y; return this; } /** * Reflect this vector on an arbitrary axis (represented by a unit vector). This is * slightly more efficient than `reflect` when dealing with an axis that is a unit vector. * @method reflectN * @memberof Vector# * @param {Vector} axis The unit vector representing the axis * @return {Vector} Self for chaining. */ reflectN(axis) { const x = this.x; const y = this.y; this.projectN(axis).multiply(2); this.x -= x; this.y -= y; return this; } slide(normal) { n.copy(normal); this.subtract( n.multiply( v.copy(this).dot(n) ) ); return this; } /** * Check whether the direction from self to other vector is clockwise. * @method sign * @memberof Vector# * @param {Vector} vector Vector to calculate from * @return {number} Result (1 = CW, -1 = CCW) */ sign(vector) { return (this.y * vector.x > this.x * vector.y) ? -1 : 1; } }
JavaScript
class HttpsTunnelServer extends EventEmitter { constructor(options) { super(); if (!options.key || !options.cert) { throw new Error('missing or invalid options'); } this._options = Object.assign({ requestCert: true, rejectUnauthorized: true, port: 443, proxyPort: 8080, }, options); this._ctrlSocket = null; this._clientSockets = new Map(); this._httpsServer = null; this._io = null; this._proxyServer = null; this._isReady = false; } // HTTP CONNECTION response with empty body static get httpConnectRes() { return [ 'HTTP/1.1 200 Connection Established', 'Proxy-agent: Node-VPN', '\r\n'] .join('\r\n'); } // discard all request to proxy server except HTTP/1.1 CONNECT method static requestHandler() { return (req, res) => { res.writeHead(405, {'Content-Type': 'text/plain'}); res.end('Method not allowed'); }; } /** * Create the HTTPS server and HTTP proxy and start listening. */ listen() { this.createHttpsServer(); this.createHttpProxyServer(); } emitReady() { if (!this._isReady && this._httpsServer && this._httpsServer.listening && this._proxyServer && this._proxyServer.listening) { this._isReady = true; this.emit('ready'); } } get isReady() { return this._isReady; } createHttpsServer() { this._httpsServer = https.createServer(this._options, HttpsTunnelServer.requestHandler); this._io = socketIo(this._httpsServer); this._httpsServer.listen(this._options.port, (err) => { if (!err) { this.emitReady(); } }); this._io.on('connection', (socket) => { this._ctrlSocket = socket; socket.on('disconnect', (reason) => { this._ctrlSocket = null; this.emit('agent-disconnect', reason); }); socket.on('createTunnel_timeout', (data) => { this.createTunnelTimeoutHandler(data); }); socket.on('createTunnel_error', (data) => { this.createTunnelErrorHandler(data); }); socket.on('createAgentTunnel_error', (data) => { this.createAgentTunnelErrorHandler(data); }); this.emit('agent-connect', { remoteAddress: socket.conn.remoteAddress, id: socket.conn.id }); }); // HTTPS Proxy for agent to create new tunnel this._httpsServer.on('connect', (req, agentSocket, head) => { this.onAgentTunnelConnection(req, agentSocket, head); }); this._httpsServer.on('error', (err) => { this.emit('error', new NestedError('Error in HTTPS Server.', err)); }); } onAgentTunnelConnection(req, agentSocket, head) { const tunnelId = req.url; if (!tunnelId) { let errMsg = `No tunnelId in request`; agentSocket.end(`HTTP/1.1 400 ${errMsg}\r\n`); agentSocket.destroy(); return; } let clientSocket = this._clientSockets.get(tunnelId); if (!clientSocket || clientSocket.destroyed) { let errMsg = `No client socket for tunnelId: ${tunnelId} or socket is destroyed`; agentSocket.end(`HTTP/1.1 400 ${errMsg}\r\n`); agentSocket.destroy(); return; } const agentErrorHandler = (err) => { if (clientSocket && !clientSocket.destroyed) { clientSocket.end(`HTTP/1.1 500 ${err.message}\r\n`); clientSocket.destroy(); } this.emit('error', new NestedError(`Agent tunnel error. Tunnel Id: ${tunnelData.id}.`, err)); }; const agentEndHandler = () => { if (clientSocket && !clientSocket.destroyed) { clientSocket.end(); clientSocket.destroy(); } }; const clientErrorHandler = (err) => { if (agentSocket && !agentSocket.destroyed) { agentSocket.end(`HTTP/1.1 500 ${err.message}\r\n`); agentSocket.destroy(); } this.emit('error', new NestedError(`Client error. Tunnel Id: ${tunnelData.id}.`, err)); }; const clientEndHandler = () => { if (agentSocket && !agentSocket.destroyed) { agentSocket.end(); agentSocket.destroy(); } }; const clientCloseHandler = () => { this._clientSockets.delete(tunnelId); }; clientSocket.on('error', clientErrorHandler); clientSocket.on('end', clientEndHandler); clientSocket.on('close', clientCloseHandler); agentSocket.on('error', agentErrorHandler); agentSocket.on('end', agentEndHandler); agentSocket.write(HttpsTunnelServer.httpConnectRes); clientSocket.write(HttpsTunnelServer.httpConnectRes); clientSocket.pipe(agentSocket, {end: false}); agentSocket.pipe(clientSocket, {end: false}); this.emit('tunnel-completed', tunnelId); } onClientConnect(req, clientSocket) { if (!this._ctrlSocket) { clientSocket.end('HTTP/1.1 500 No agent connected\r\n'); clientSocket.destroy(); return; } const { port, hostname } = url.parse(`//${req.url}`, false, true); // extract destination host and port from CONNECT request if (!hostname) { clientSocket.end('HTTP/1.1 400 Bad Request\r\n'); clientSocket.destroy(); return; } let tunnelData = { id: uuidv1(), hostName: hostname, port: port || 443 }; this.emit('tunnel-request', tunnelData); this._clientSockets.set(tunnelData.id, clientSocket); this._ctrlSocket.emit('createTunnel', tunnelData); } createHttpProxyServer() { this._proxyServer = http.createServer(HttpsTunnelServer.requestHandler); this._proxyServer.listen(this._options.proxyPort, (err) => { if (!err) { this.emitReady(); } }); // HTTPS proxy for clients to create new tunnel this._proxyServer.on('connect', (req, clientSocket) => { this.onClientConnect(req, clientSocket); }); this._proxyServer.on('error', (err) => { this.emit('error', new NestedError('Error in HTTP Proxy Server.', err)); }); } createTunnelTimeoutHandler(data) { let clientSocket = this._clientSockets.get(data.tunnelData.id); clientSocket.end(`HTTP/1.1 504 connect ETIMEDOUT ${data.tunnelData.hostName}:${data.tunnelData.port}\r\n`); clientSocket.destroy(); this._clientSockets.delete(data.tunnelData.id); this.emit('error', new Error(`Agent connection to target timed out. Tunnel ID: ${data.tunnelData.id}.`)); } createTunnelErrorHandler(data) { this.emit('error', new Error(data.err)); } createAgentTunnelErrorHandler(data) { this.emit('error', new Error(data.err)); } }
JavaScript
class V1ContainerStateTerminated { static getAttributeTypeMap() { return V1ContainerStateTerminated.attributeTypeMap; } }
JavaScript
class TouchDraw extends PointerInteraction { /** * @param {TouchDrawOptions=} opt_options TouchDrawOptions. */ constructor(opt_options) { const options = opt_options ? opt_options : {}; super(/** @type {PointerInteraction.Options} */ (options)); /** * Reference source used to calculate proposed drawing handles. * @type {VectorSource} * @private */ this.source_ = options.referenceSource ? options.referenceSource : null; /** * Destination source for the drawn features. * @type {VectorSource} * @private */ this.target_ = options.destinationSource ? options.destinationSource : null; if (options.source) { this.source_ = options.source; this.target_ = options.source; } this.unitConversions_ = options.unitConversions || DefaultTouchDrawUnitConversions; this.selectedUnit_ = options.selectedUnit || 'm'; this.internalState_ = TouchDrawStates.PROPOSING_HANDLES; this.overlay_ = new VectorLayer({ source: createAlwaysVisibleVectorSource(), updateWhileInteracting: true }); this.interestingSegmentsFeature_ = new Feature({ geometry: new MultiLineString([]), }); this.interestingSegmentsFeature_.setStyle(new Style({ stroke: new Stroke({ color: '#ffcc33', width: 2, zIndex: 100, }), })); this.overlay_.getSource().addFeature(this.interestingSegmentsFeature_); this.overlay_.on('postrender', this.handleOverlayPostRender_.bind(this)); this.addEventListener(getChangeEventType('active'), this.updateState_); } /** * @param {ol.PluggableMap} map Map. */ setMap(map) { super.setMap(map); this.updateState_(); } /** * @private */ updateState_() { const map = this.getMap(); const active = this.getActive(); if (!map || !active) { this.abortDrawing(); } this.overlay_.setMap(active ? map : null); } /** * @inheritDoc * @api */ changed() { super.changed(); this.overlay_.changed(); } handleDownEvent(evt) { const getCircularReplacer = () => { const seen = new WeakSet(); return (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; }; }; const map = evt.map; const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) { if (feature.get('isOrthogonalMovementHandle')) { return feature; } }); if (feature && feature.get('isOrthogonalMovementHandle')) { this.activeHandle_ = feature; this.activeHandle_.handleDownEvent(evt); if (this.internalState_ === TouchDrawStates.PROPOSING_HANDLES) { this.internalState_ = TouchDrawStates.DRAWING; this.draftingState_ = new TouchDrawFeatureDraftingState({ map, overlay: this.overlay_, initialTouchDrawHandle: feature, unitConversions: this.unitConversions_, selectedUnit: this.selectedUnit_, }); this.draftingState_.once(TouchDrawEventType.DRAWEND, (e) => this.handleDrawEnd_(e)); this.draftingState_.once(TouchDrawEventType.DRAWABORT, (e) => this.handleDrawAbort_(e)); this.dispatchEvent(new TouchDrawEvent(TouchDrawEventType.DRAWSTART, this.draftingState_.draftFeature_)); } return true; } return !!feature; } handleUpEvent(evt) { if (this.activeHandle_) { this.activeHandle_.handleUpEvent(evt); this.activeHandle_ = null; return true; } return false; } handleDragEvent(evt) { if (this.activeHandle_) { this.activeHandle_.handleDragEvent(evt); return true; } } handleDrawEnd_(event) { const draftFeature = this.draftingState_ && this.draftingState_.draftFeature_; this.abortDrawing(); if (!draftFeature) { return; } // First dispatch event to allow full set up of feature this.dispatchEvent(event); if (this.target_) { this.target_.addFeature(draftFeature); } } handleDrawAbort_(event) { this.abortDrawing(); this.dispatchEvent(event); } abortDrawing() { if (this.draftingState_) { this.draftingState_.cancelDraft(); this.draftingState_ = null; } this.internalState_ = TouchDrawStates.PROPOSING_HANDLES; // Reset our overlay this.overlay_.getSource().clear(); this.interestingSegmentsFeature_.getGeometry().setCoordinates([]); this.overlay_.getSource().addFeature(this.interestingSegmentsFeature_); // Reset this so the next post render event will recalculate new touch handles this.lastSourceRevision_ = null; this.changed(); } /** * Handle post render events for our overlay layer * @private */ handleOverlayPostRender_() { if (this.internalState_ === TouchDrawStates.PROPOSING_HANDLES) { this.handleOverlayPostRenderHandleProposals_(); } } /** * Handle drawing handle proposals post render. * @private */ handleOverlayPostRenderHandleProposals_() { const map = this.getMap(); const viewExtent = map.getView().calculateExtent(map.getSize()); const viewExtentUnchanged = viewExtent === this.lastViewExtent_ || JSON.stringify(viewExtent) === JSON.stringify(this.lastViewExtent_); const sourceUnchanged = this.source_.getRevision() === this.lastSourceRevision_; // No need to recalculate the overlay geometry if nothing has changed if (viewExtentUnchanged && sourceUnchanged) { return; } this.lastViewExtent_ = viewExtent; this.lastSourceRevision_ = this.source_.getRevision(); this.overlay_.getSource().clear(); this.overlay_.getSource().addFeature(this.interestingSegmentsFeature_); const extentSize = getExtentSize(viewExtent); const extentDiagonalLength = Math.hypot(...extentSize); const extentFocusRegion = bufferExtent(boundingExtentFromCoordinates([getExtentCenter(viewExtent)]), extentDiagonalLength / 8); const screenAreasWithHandles = {}; const interestingSegmentLineStrings = []; const movementHandles = []; const vm = this; function findInterestingSegmentsFromLinearCoords(coords) { if (coords.length < 2) { return; } // TODO: Consider limiting total count of anchors for(var i = 0; (i + 1) < coords.length; i += 1) { const segmentInFocusRegion = cropLineSegmentByExtent(coords.slice(i, i + 2), extentFocusRegion); if (!segmentInFocusRegion) { continue; } const segmentExtentInFocusRegion = boundingExtentFromCoordinates(segmentInFocusRegion); if (isExtentEmpty(segmentExtentInFocusRegion)) { continue; } const segmentExtentSizeInFocusRegion = getExtentSize(segmentExtentInFocusRegion); const segmentLengthInFocusRegion = Math.hypot(...segmentExtentSizeInFocusRegion); if ((segmentLengthInFocusRegion / extentDiagonalLength) < 0.1) { continue; } const segmentInExtent = cropLineSegmentByExtent(coords.slice(i, i + 2), viewExtent); const ls = new LineString(segmentInExtent, 'XY'); const handleCoord = ls.getCoordinateAt(0.5); const handlePixel = map.getPixelFromCoordinate(handleCoord); const handleDesc = `${Math.floor(handlePixel[0] / 100)}x${Math.floor(handlePixel[1] / 100)}`; if (handleDesc in screenAreasWithHandles) { continue; } screenAreasWithHandles[handleDesc] = true; const handleMovementBasisVector = getOrthogonalBasisVector(handleCoord, segmentInExtent[1]); movementHandles.push(new OrthogonalMovementHandle({ geometry: new Point(handleCoord, 'XY'), movementBasisVector: handleMovementBasisVector, iconUrl: TOUCH_DRAW_HANDLE_ICON, originalSegmentCoords: coords.slice(i, i + 2), })); interestingSegmentLineStrings.push(ls); } } function findInterestingSegments(g) { if (typeof g.getType !== 'function') { return; } const gType = g.getType(); // 'Point', 'LineString', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection', 'Circle'. if (gType === 'LineString') { findInterestingSegmentsFromLinearCoords(g.getCoordinates()) } else if (gType === 'LinearRing') { const coords = g.getCoordinates(); if (coords.length >= 2) { coords.push(coords[0]); } findInterestingSegmentsFromLinearCoords(coords); } else if (gType === 'Polygon') { g.getLinearRings().map(findInterestingSegments); } else if (gType === 'MultiLineString') { g.getLineStrings().map(findInterestingSegments); } else if (gType === 'MultiPolygon') { g.getPolygons().map(findInterestingSegments); } else if (gType === 'GeometryCollection') { g.getGeometries().map(findInterestingSegments); } } this.source_.forEachFeatureInExtent(viewExtent, (feature) => { const geometry = feature.getGeometry(); if (typeof geometry.getLayout !== 'function' || geometry.getLayout() !== 'XY') { return; } findInterestingSegments(geometry); }); this.interestingSegmentsFeature_.getGeometry().setCoordinates([]); interestingSegmentLineStrings.forEach(ls => this.interestingSegmentsFeature_.getGeometry().appendLineString(ls)); this.overlay_.getSource().addFeatures(movementHandles); } }
JavaScript
class Uint64 { /** * Makes a new Uint64 from a Uint8Array * @param {Uint8Array} uintArray an array of bytes to be used to represent this 64 bit integer. */ constructor(uintArray = new Uint8Array(8)) { if (uintArray instanceof Uint8Array === false) { throw new TypeError("Uint64 source must be a Uint8Array, Uint64.from(bytes), Uint64.fromTypedArray, Uint64.fromArrayBuffer might suit your needs better.") } /** * @private * @type {Uint8Array} */ this.data = uintArray /** * An arraybuffer representation of this value. * @type {ArrayBuffer} */ this.buffer = this.data.buffer } /** * Creates a Uint64 from bytes * @param {number[]} bytes * @returns {Uint64} */ static from(...bytes) { const result = new Uint64() result.set(...bytes) return result } /** * Creates a Uint64 from the first 8 bytes of one of the binary forms. * @param {ArrayBuffer|Buffer|TypedArray} binary * @returns {Uint64} */ static fromBinary(binary) { return Uint64.fromArrayBuffer(toArrayBuffer(binary)) } /** * Creates a Uint64 from an array buffer. Potentially with a byte offset. * Only the first 8 bytes will be taken. * @param {ArrayBuffer} arrayBuffer * @param {number} byteOffset the starting position in the array buffer. Defaults to 0. * @returns {Uint64} */ static fromArrayBuffer(arrayBuffer, byteOffset = 0) { return new Uint64(new Uint8Array(arrayBuffer.slice(byteOffset, byteOffset + 8))) } /** * Modifies this Uint64 to represent the succeeding integer. If * this represents the largest integer the Uint64 can represent, it will wrap to 0. * @returns {Uint64} this, modified Uint64. */ inc() { for (let idx = this.data.length - 1; idx >= 0; --idx) { this.data[idx] += 1 if (this.data[idx] != 0) { break } } return this } /** * @returns {Uint64} a copy of this Uint64. */ clone() { const dst = new ArrayBuffer(this.data.byteLength) const uintArray = new Uint8Array(dst) uintArray.set(this.data) return new Uint64(uintArray) } /** * Set the last last bytes.length bytes. * @param {number[]} bytes the bytes to set. */ set(...bytes) { if (bytes[0] instanceof Uint64) { this.data.set(bytes[0].data, 0) } else { for (let i = 0; i < bytes.length; ++i) { this.data[this.data.length - bytes.length + i] = bytes[i] } } } /** * Returns an array buffer where this Uint64 is the first 8 bytes and * the passed buffer is the subsequent bytes. * @param {ArrayBuffer|Buffer|TypedArray} buffer the subsequent bytes. * @returns {ArrayBuffer} */ concat(buffer) { buffer = toArrayBuffer(buffer) const result = new Uint8Array(this.data.length + buffer.byteLength) result.set(this.data, 0) result.set(new Uint8Array(buffer), this.data.length) return result.buffer } /** * A string representation of this Uint64. This string representation is for debugging purposes * and does not form part of the public API. */ toString() { return binaryToHex(this.data) } }
JavaScript
class ScheduleFlyout extends Component { componentDidMount() { const userTimezone = moment.tz.guess(); this.setState({ scheduling: false, userTimezone: userTimezone, selectedTimezone: userTimezone, selectedTime: moment().format(UTC_FORMAT), timezones: moment.tz.names().map((el, i) => { return { value: el, html: el, }; }), }); } handleCancelPublish = () => { this.setState({ scheduling: true, }); this.props .dispatch( unpublish( this.props.item.meta.contentModelZUID, this.props.item.meta.ZUID, this.props.item.scheduling.ZUID, { version: this.props.item.scheduling.version } ) ) .finally(() => { this.setState({ scheduling: false, }); }); }; handleSchedulePublish = () => { this.setState({ scheduling: true, }); // Display timestamp to user in the selected timezone const tzTime = moment .tz(this.state.selectedTime, this.state.selectedTimezone) .format(DISPLAY_FORMAT); // Send to API as UTC string // Order tz > utc > format is important const utcTime = moment .tz(this.state.selectedTime, this.state.selectedTimezone) .utc() .format(UTC_FORMAT); this.props .dispatch( publish( this.props.item.meta.contentModelZUID, this.props.item.meta.ZUID, { publishAt: utcTime, version: this.props.item.meta.version, }, { localTime: tzTime, localTimezone: this.state.selectedTimezone, } ) ) .finally(() => { this.setState({ scheduling: false, }); }); }; handleChangePublish = (value) => { // Convert emited date object into the local time without timezone information // moment creates local time objects by default const selectedTime = moment(value).format(UTC_FORMAT); return this.setState({ selectedTime, }); }; handleChangeTimezone = (value) => { return this.setState({ selectedTimezone: value, }); }; render() { return ( this.props.isOpen && ( <Modal className={styles.Modal} type="global" open={true} onClose={this.props.toggleOpen} > {this.props.item.scheduling && this.props.item.scheduling.isScheduled ? ( <> <ModalContent> <Notice className={styles.Notice}> New versions can not be published while there is a version scheduled. </Notice> <p className={styles.Row}> Version {this.props.item.scheduling.version} is scheduled to publish on{" "} <em> {/* publishAt from API is in UTC. Order of moment > utc > local > format is important Since the API returns a UTC timestamp we need it in UTC before setting it to the users timezone and formatting. We can not display it in the selected timezone when it was created because that information is not persisted to the API so we always display it after the fact in the users current timezone */} {moment .utc(this.props.item.scheduling.publishAt) .tz(this.state.userTimezone) .format(DISPLAY_FORMAT)} </em>{" "} in the <em>{this.state.userTimezone}</em> timezone. </p> </ModalContent> <ModalFooter className={styles.ModalFooter}> <Button type="cancel" onClick={this.props.toggleOpen}> <FontAwesomeIcon icon={faBan} /> &nbsp;Cancel </Button> <Button type="warn" data-cy="UnschedulePublishButton" disabled={this.state.scheduling} onClick={this.handleCancelPublish} > <FontAwesomeIcon icon={faTrashAlt} /> &nbsp;Unschedule Version&nbsp; {this.props.item.scheduling.version} </Button> </ModalFooter> </> ) : ( <> <ModalContent> <div className={styles.Row}> <FieldTypeDropDown label="Timezone where this will be published" name="selectedTimezone" onChange={this.handleChangeTimezone} value={this.state.selectedTimezone} options={this.state.timezones} /> </div> <div className={styles.Row}> <FieldTypeDate type="date" name="publish" label="Publish date and time" future={true} value={this.state.selectedTime} datatype={"datetime"} onChange={this.handleChangePublish} /> </div> </ModalContent> <ModalFooter className={styles.ModalFooter}> <Button className={styles.Cancel} type="cancel" id="SchedulePublishClose" onClick={this.props.toggleOpen} > <FontAwesomeIcon icon={faBan} /> Cancel </Button> <Button type="save" data-cy="SchedulePublishButton" onClick={this.handleSchedulePublish} disabled={this.state.scheduling} > <FontAwesomeIcon icon={faCalendarPlus} /> Schedule Publishing Version {this.props.item.meta.version} </Button> </ModalFooter> </> )} </Modal> ) ); } }
JavaScript
class BannedImgs extends HTMLElement { #container = null; #fadeIn = true; #icon = { // eslint-disable-next-line max-len forbidden: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm10 12c0 2.397-.85 4.6-2.262 6.324l-14.062-14.062c1.724-1.412 3.927-2.262 6.324-2.262 5.514 0 10 4.486 10 10zm-20 0c0-2.397.85-4.6 2.262-6.324l14.062 14.062c-1.724 1.412-3.927 2.262-6.324 2.262-5.514 0-10-4.486-10-10z"/></svg>' }; #interval = null; #sdom = null; connectedCallback() { setTimeout(() => { this.style.display = 'block'; this.#sdom = this.attachShadow({ mode: 'open' }); this.#setupStyles(); this.#setupImgs(); setTimeout(this.#updateOpacity.bind(this), 2000); }, 0); } #setupImgs() { // Wrap all the images in a container we style with flex rules. const container = document.createElement('DIV'); container.setAttribute('opacity', 0); container.classList.add('container'); // Retrieve all the data elements and convert them into image elements. const datas = this.querySelectorAll('data'); datas.forEach((data) => { const wrapper = document.createElement('DIV'); const img = document.createElement('IMG'); wrapper.classList.add('img-wrapper'); wrapper.innerHTML = this.#icon.forbidden; img.src = data.getAttribute('value'); img.alt = data.innerHTML; data.remove(); wrapper.appendChild(img); container.appendChild(wrapper); }); // Keep a reference to the container and add everything to the Shadow DOM. this.#container = container; this.#sdom.appendChild(container); } #setupStyles() { const styles = document.createElement('STYLE'); styles.innerHTML = ` *, *:before, *:after { box-sizing: border-box; } .container { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; } .container.op1 svg { opacity: 0.10; } .container.op2 svg { opacity: 0.20; } .container.op3 svg { opacity: 0.30; } .container.op4 svg { opacity: 0.40; } .container.op5 svg { opacity: 0.50; } .container.op6 svg { opacity: 0.50; } .img-wrapper { position: relative; display: flex; align-items: center; justify-content: center; width: 150px; height: 150px; margin: 15px; overflow: hidden; } svg { position: absolute; fill: #eb4f4f; width: 100%; height: 100%; opacity: 0; } img { max-width: 80%; max-height: 80%; width: 80%; height: auto; } `; this.#sdom.appendChild(styles); } #updateOpacity() { const opacity = parseInt(this.#container.getAttribute('opacity'), 10); if (opacity === 7) { this.#fadeIn = false; clearInterval(this.#interval); setTimeout(() => { this.#interval = setInterval(this.#updateOpacity.bind(this), 180); }, 1000); } else if (opacity < 1) { this.#fadeIn = true; clearInterval(this.#interval); setTimeout(() => { this.#interval = setInterval(this.#updateOpacity.bind(this), 180); }, 2500); } /** * Handle removing and placing the correct class on the container element. * This is used with our styles to handle the fade in and out effect. */ if (this.#fadeIn && opacity <= 6) { this.#container.classList.remove(`op${opacity - 1}`); this.#container.classList.add(`op${opacity}`); this.#container.setAttribute('opacity', opacity + 1); } else { this.#container.classList.remove(`op${opacity - 1}`); this.#container.classList.add(`op${opacity - 2}`); this.#container.setAttribute('opacity', opacity - 1); } } }
JavaScript
class SyncStream extends closeable_1.default { constructor(syncStreamImpl) { super(); this.syncStreamImpl = syncStreamImpl; this.syncStreamImpl.attach(this); } // private props get uri() { return this.syncStreamImpl.uri; } get links() { return this.syncStreamImpl.links; } static get type() { return SyncStreamImpl.type; } get dateExpires() { return this.syncStreamImpl.dateExpires; } get type() { return SyncStreamImpl.type; } get lastEventId() { return null; } // public props, documented along with class description get sid() { return this.syncStreamImpl.sid; } get uniqueName() { return this.syncStreamImpl.uniqueName; } /** * Publish a Message to the Stream. The system will attempt delivery to all online subscribers. * @param {Object} value The body of the dispatched message. Maximum size in serialized JSON: 4KB. * A rate limit applies to this operation, refer to the [Sync API documentation]{@link https://www.twilio.com/docs/api/sync} for details. * @return {Promise<StreamMessage>} A promise which resolves after the message is successfully published * to the Sync service. Resolves irrespective of ultimate delivery to any subscribers. * @public * @example * stream.publishMessage({ x: 42, y: 123 }) * .then(function(message) { * console.log('Stream publishMessage() successful, message SID:' + message.sid); * }) * .catch(function(error) { * console.error('Stream publishMessage() failed', error); * }); */ async publishMessage(value) { this.ensureNotClosed(); return this.syncStreamImpl.publishMessage(value); } /** * Update the time-to-live of the stream. * @param {Number} ttl Specifies the TTL in seconds after which the stream is subject to automatic deletion. The value 0 means infinity. * @return {Promise<void>} A promise that resolves after the TTL update was successful. * @public * @example * stream.setTtl(3600) * .then(function() { * console.log('Stream setTtl() successful'); * }) * .catch(function(error) { * console.error('Stream setTtl() failed', error); * }); */ async setTtl(ttl) { this.ensureNotClosed(); return this.syncStreamImpl.setTtl(ttl); } /** * Permanently delete this Stream. * @return {Promise<void>} A promise which resolves after the Stream is successfully deleted. * @public * @example * stream.removeStream() * .then(function() { * console.log('Stream removeStream() successful'); * }) * .catch(function(error) { * console.error('Stream removeStream() failed', error); * }); */ async removeStream() { this.ensureNotClosed(); return this.syncStreamImpl.removeStream(); } /** * Conclude work with the stream instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this stream will continue operating and receiving events normally. * @public * @example * stream.close(); */ close() { super.close(); this.syncStreamImpl.detach(this.listenerUuid); } }
JavaScript
class GlobalRepository extends Base { /** * @param {EntityIdParser} entityIdParser */ constructor(sitesRepository, entityCategoriesRepository, entitiesRepository) { super(); // Check params assertParameter(this, 'sitesRepository', sitesRepository, true, SitesRepository); assertParameter(this, 'entityCategoriesRepository', entityCategoriesRepository, true, EntityCategoriesRepository); assertParameter(this, 'entitiesRepository', entitiesRepository, true, EntitiesRepository); // Assign this._sitesRepository = sitesRepository; this._entityCategoriesRepository = entityCategoriesRepository; this._entitiesRepository = entitiesRepository; } /** * @inheritDocs */ static get injections() { return { 'parameters': [SitesRepository, EntityCategoriesRepository, EntitiesRepository] }; } /** * @inheritDocs */ static get className() { return 'model/GlobalRepository'; } /** * @inheritDocs */ resolve(query) { const scope = this; const promise = co(function*() { let site; let entityCategory; let entity; const parts = query && query.length ? trimSlashesLeft(query).split('/') : ['*']; if (parts.length == 1) { // Check * if (query === '*') { site = yield scope._sitesRepository.getItems(); return { site: site }; } // Check site site = yield scope._sitesRepository.findBy({ '*': query }); if (site) { return { site: site }; } // Check category entityCategory = yield scope._entityCategoriesRepository.findBy({ '*': query }); if (entityCategory) { return { entityCategory: entityCategory }; } } if (parts.length == 2) { // Check site / category site = yield scope._sitesRepository.findBy({ name: parts[0].trim() }); if (site) { entityCategory = yield scope._entityCategoriesRepository.findBy({ '*': parts[1].trim() }); if (entityCategory) { return { site: site, entityCategory: entityCategory }; } } } if (parts.length == 1 || parts.length == 3) { // Check entity entity = yield scope._entitiesRepository.getById(query); if (entity) { return { entity: entity }; } } return undefined; }); return promise; } /** * @inheritDoc */ resolveSites(query) { const scope = this; const promise = co(function*() { // Check * if (query === '*') { return yield scope._sitesRepository.getItems(); } // Check site const site = yield scope._sitesRepository.findBy({ '*': query }); if (site) { return [site]; } return []; }); return promise; } /** * @returns {Promise<Object>} */ resolveEntity(siteQuery, entityQuery) { if (!siteQuery && !entityQuery) { return Promise.resolve(false); } const scope = this; const promise = co(function*() { metrics.start(scope.className + '::resolveEntity'); // Get site let site = (siteQuery instanceof Site) ? siteQuery : yield scope._sitesRepository.findBy({ '*': siteQuery }); if (!site && !siteQuery) { site = yield scope._sitesRepository.getFirst(); } if (!site) { metrics.stop(scope.className + '::resolveEntity'); /* istanbul ignore next */ scope.logger.debug('resolveEntity - could not determine site', siteQuery); return false; } // Get entity const entities = yield scope._entitiesRepository.getBySite(site); let result; for (const entity of entities) { if (entity.id.isEqualTo(entityQuery)) { result = entity; } } /* istanbul ignore next */ if (!result) { metrics.stop(scope.className + '::resolveEntity'); scope.logger.debug('resolveEntity - could not find entity', entityQuery); return false; } metrics.stop(scope.className + '::resolveEntity'); return result; }); return promise; } /** * @inheritDoc */ resolveEntities(query) { const scope = this; const promise = co(function*() { const result = []; const queryResult = yield scope.resolve(query); // Check if result if (!queryResult) { return result; } // Check site if (queryResult.site && !queryResult.entityCategory) { const sites = Array.isArray(queryResult.site) ? queryResult.site : [queryResult.site]; for (const site of sites) { const siteEntities = yield scope._entitiesRepository.getBySite(site); Array.prototype.push.apply(result, siteEntities); } } // Check category if (queryResult.entityCategory && !queryResult.site) { const entityCategories = Array.isArray(queryResult.entityCategory) ? queryResult.entityCategory : [queryResult.entityCategory]; for (const entityCategory of entityCategories) { const entityCategoryEntities = yield scope._entitiesRepository.getByCategory(entityCategory); Array.prototype.push.apply(result, entityCategoryEntities); } } // Check site + category if (queryResult.entityCategory && queryResult.site) { const siteEntityCategoryEntities = yield scope._entitiesRepository.getBySiteAndCategory(queryResult.site, queryResult.entityCategory); Array.prototype.push.apply(result, siteEntityCategoryEntities); } // Check entity if (queryResult.entity) { result.push(queryResult.entity); } return result; }); return promise; } /** * @returns {Promise<Object>} */ resolveMacro(siteQuery, macroQuery) { if (!siteQuery && !macroQuery) { return Promise.resolve(false); } const scope = this; const promise = co(function*() { metrics.start(scope.className + '::resolveMacro'); // Get site let site = (siteQuery instanceof Site) ? siteQuery : yield scope._sitesRepository.findBy({ '*': siteQuery }); if (!site && !siteQuery) { site = yield scope._sitesRepository.getFirst(); } if (!site) { metrics.stop(scope.className + '::resolveMacro'); /* istanbul ignore next */ scope.logger.debug('resolveMacro - could not determine site', siteQuery); return false; } // Get entities metrics.start(scope.className + '::resolveMacro - get entities'); const entities = yield scope._entitiesRepository.getBySite(site); metrics.stop(scope.className + '::resolveMacro - get entities'); // Find macro for (const entity of entities) { const macro = entity.documentation.find((doc) => { return doc.contentType === ContentType.JINJA && doc.name === macroQuery; }); if (macro) { metrics.stop(scope.className + '::resolveMacro'); return macro; } } /* istanbul ignore next */ scope.logger.debug('resolveMacro - could not find macro', macroQuery); metrics.stop(scope.className + '::resolveMacro'); return false; }); return promise; } /** * @param {String|model.site.Site} siteQuery * @param {String|model.documentation.DocumentationCallable} macroQuery * @returns {Promise<Object>} */ resolveEntityForMacro(siteQuery, macroQuery, findDefining) { const scope = this; const promise = co(function*() { // Get site let site = (siteQuery instanceof Site) ? siteQuery : yield scope._sitesRepository.findBy({ '*': siteQuery }); if (!site && !siteQuery) { site = yield scope._sitesRepository.getFirst(); } if (!site) { /* istanbul ignore next */ scope.logger.debug('resolveEntityForMacro - could not find site', siteQuery); return false; } // Get entities const entities = yield scope._entitiesRepository.getBySite(site); // Find entity const macroName = (macroQuery instanceof DocumentationCallable) ? macroQuery.name : macroQuery; for (const entity of entities) { // Find the macro const macro = entity.documentation.find((doc) => { return doc.contentType === ContentType.JINJA && doc.name === macroName; }); // We want the actual entity that defined the macro if (macro && findDefining && macro.site.name !== site.name) { return scope.resolveEntityForMacro(macro.site, macro.name, findDefining); } // Ok, found it if (macro) { return entity; } } /* istanbul ignore next */ scope.logger.debug('resolveEntityForMacro - could not find macro', macroQuery); return false; }); return promise; } }
JavaScript
class MidtransError extends Error { // private readonly httpStatusCode?: number // private readonly ApiResponse?: any // private readonly rawHttpClientData?: any constructor(options) { super(options.message); // Ensure the name of this error is the same as the class name this.name = this.constructor.name; // this.httpStatusCode = options.httpStatusCode // this.ApiResponse = options.ApiResponse // this.rawHttpClientData = options.rawHttpClientData // This clips the constructor invocation from the stack trace. Error.captureStackTrace(this, this.constructor); } }
JavaScript
class InlineButtonCallback extends mix(class {}).with(checkNotNull(['value', 'user'])) { /** * Constructor. * * @param {object} options - hash of parameters * @param {string} options.value - guid key for `user.state.inlineValues`, see {@link HistoryHash} * and {@link DriverOrderNew}. * @param {User} options.user - user * @param {Object} options.api - (optional) transport library api. */ constructor(options) { super(options); this.type = 'inline-button-callback'; Object.assign(this, options); } /** * Callback entry point. Calls handler against response. */ call() { const response = ((this.user.state.inlineValues || {}).hash || {})[this.value] || new EmptyResponse(); const handler = ResponseHandlerFactory.getHandler({ response, user: this.user, api: this.api }); handler.call(() => {}); } }
JavaScript
class Heal extends Damage { /** * Raise a given attribute * @param {Character} target * @fires Character#heal * @fires Character#healed */ commit(target) { this.finalAmount = this.evaluate(target); target.raiseAttribute(this.attribute, this.finalAmount); if (this.attacker) { /** * @event Character#heal * @param {Heal} heal * @param {Character} target */ this.attacker.emit('heal', this, target); } /** * @event Character#healed * @param {Heal} heal */ target.emit('healed', this); } }
JavaScript
class ApplicationKeyViewer extends React.Component { constructor(props) { super(props); this.state = { showCreateDialog: false, showRevokeDialog: false, selected: null, }; props.getAccounts(); this.revokeDialogHandler = this.revokeDialogHandler.bind(this); this.hideRevokeDialog = this.hideRevokeDialog.bind(this); } componentWillMount() { this.search(); } search() { this.props.query({ query: { ...this.props.filters }, }); } showCreateDialog() { this.setState({ showCreateDialog: true, }); } hideCreateDialog() { this.setState({ showCreateDialog: false, }); } showRevokeDialog(key) { this.setState({ showRevokeDialog: true, selected: key, }); } hideRevokeDialog() { this.setState({ showRevokeDialog: false, selected: null, }); } create(data) { this.props.checkApplicationName(data.applicationName) .then(exists => { if (exists) { message.warn(`An application with name ${data.applicationName} already exists`); } else { this.props.create(data) .then((data) => { this.hideCreateDialog(); this.search(); const result = copyToClipboard('copy-key', data.key); message.infoHtml( `The application key has been created successfully.${result ? '<br />The key has been copied to the clipboard.' : ''}` ); }) .catch(() => { message.error('An error has occurred'); }); } }) .catch(() => { message.error('Validation has failed'); }); } revokeDialogHandler(action) { const { selected: { id } } = this.state; switch (action.key) { case EnumRevokeAction.Revoke: this.props.revoke(id) .then(() => { this.hideRevokeDialog(); this.search(); }) .catch(() => { message.error('Operation has failed'); }); break; default: this.hideRevokeDialog(); break; } } renderRevokeDialog() { const { selected: { name } } = this.state; return ( <Dialog className="modal-dialog-centered" header={ <span> <i className={'fa fa-question mr-2'}></i>System Message </span> } modal={this.state.showRevokeDialog} handler={this.revokeDialogHandler} toggle={this.hideRevokeDialog} actions={[ { key: EnumRevokeAction.Revoke, label: 'Yes', iconClass: 'fa fa-trash', color: 'danger', }, { key: EnumRevokeAction.Cancel, label: 'No', iconClass: 'fa fa-undo', } ]} > <div>The application key <span className="font-weight-bold">{name}</span> will be revoked. Are you sure you want to continue?</div> </Dialog> ); } render() { return ( <React.Fragment> {this.state.showRevokeDialog && this.renderRevokeDialog() } {this.state.showCreateDialog && <ApplicationKeyForm accounts={this.props.accounts} create={(data) => this.create(data)} hide={() => this.hideCreateDialog()} visible={this.state.showCreateDialog} /> } <div className="animated fadeIn"> <Row> <Col className="col-12"> <Card> <CardBody className="card-body"> {this.props.lastUpdate && <Row className="mb-2"> <Col > <div className="small text-muted"> Last Update: <FormattedTime value={this.props.lastUpdate} day='numeric' month='numeric' year='numeric' /> </div> </Col> </Row> } <Row> <Col> <Filters create={() => this.showCreateDialog()} filters={this.props.filters} query={this.props.query} resetFilters={this.props.resetFilters} setFilter={this.props.setFilter} /> </Col> </Row> </CardBody> </Card> <Card> <CardBody className="card-body"> <Row className="mb-2"> <Col> <ApplicationKeys expanded={this.props.expanded} filters={this.props.filters} items={this.props.items} pager={this.props.pager} query={this.props.query} revoke={(key) => this.showRevokeDialog(key)} selected={this.props.selected} setExpanded={this.props.setExpanded} setPager={this.props.setPager} setSelected={this.props.setSelected} /> </Col> </Row> </CardBody> </Card> </Col> </Row > </div> <textarea id="copy-key" style={{ tabIndex: -1, ariaHidden: true, position: 'absolute', left: -9999 }} > </textarea> </React.Fragment> ); } }
JavaScript
class UtServer { /** * Create a new instance of uTorrent */ constructor(host, port = 8080, username, password) { /** * uTorrent information */ this.__host = ""; this.__port = 8080; this.__username = ""; this.__password = ""; this.__cookieJar = request_1.default.jar(); this.setAddress(host, port); this.setCredentials(username, password); } /** * Send an HTTP request */ sendRequest(options) { options.qs.token = this.__token; options.qsStringifyOptions = { arrayFormat: "repeat" }; return new Promise((resolve, reject) => { request_1.default(options, (error, response, body) => { error = utils_1.NetworkUtils.validateUtServerResponse(error, response, body); if (error) { reject(error); } else { resolve(body); } }); }); } /** * Send a request. If it fails, regenerate the token and try again. */ request(options, retry = true) { // Add auth credentials and set the proper URI options.auth = { user: this.__username, pass: this.__password, sendImmediately: false }; options.jar = this.__cookieJar; options.uri = `http://${this.__host}:${this.__port}/gui/${options.uri || ""}`; // Execute the request return new Promise((resolve, reject) => { this.sendRequest(options).then(resolve).catch((error) => { // If a token error occurred, then a new token should be generated and try again if (error instanceof errors_1.TokenError && retry) { this.fetchToken().then(() => { this.sendRequest(options).then(resolve).catch(reject); }).catch(reject); } else { reject(error); } }); }); } /** * Fetch a CSRF token */ fetchToken() { return new Promise((resolve, reject) => { let options = utils_1.NetworkUtils.defaultOptions({ uri: "token.html" }); this.request(options, false).then((body) => { let token = body.replace(/<[^<]*>/g, "").trim(); if (!token) { reject(new errors_1.TokenError("Failed to retrieve token")); } else { this.__token = token; resolve(token); } }).catch(reject); }); } /** * Execute an action on uTorrent */ execute(action, params = {}) { let options; if (action == types_1.Action.AddFile) { options = utils_1.NetworkUtils.formOptions(params, { qs: { action: action } }); } else { options = utils_1.NetworkUtils.defaultOptions({ qs: Object.assign(params, action == "list" ? { list: 1 } : { action: action }) }); } return this.request(options); } // Accessors/Mutators -------------------------------------------------------------------------- /** * Set the connection address */ setAddress(host, port) { this.setHost(host); this.setPort(port); return this; } /** * Set the login credentials */ setCredentials(username, password) { this.setUsername(username); this.setPassword(password); return this; } /** * Set the connection host */ setHost(host) { this.__host = host; return this; } /** * Set the login password */ setPassword(password) { this.__password = password || ""; } /** * Set the connection port */ setPort(port) { this.__port = port; return this; } /** * Set the login username */ setUsername(username) { this.__username = username || ""; } }
JavaScript
class LineItem { /** * Constructs a new <code>LineItem</code>. * @alias module:model/LineItem * @class * @param type {String} The line item display name for a charge item * @param amount {Number} The line item amount * @param currency {String} The currency for the amount */ constructor(type, amount, currency) { this['type'] = type;this['amount'] = amount;this['currency'] = currency; } /** * Constructs a <code>LineItem</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/LineItem} obj Optional instance to populate. * @return {module:model/LineItem} The populated <code>LineItem</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new LineItem(); if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('amount')) { obj['amount'] = ApiClient.convertToType(data['amount'], 'Number'); } if (data.hasOwnProperty('currency')) { obj['currency'] = ApiClient.convertToType(data['currency'], 'String'); } } return obj; } /** * The line item display name for a charge item * @member {String} type */ type = undefined; /** * The line item amount * @member {Number} amount */ amount = undefined; /** * The currency for the amount * @member {String} currency */ currency = undefined; }
JavaScript
class CommentEditForm extends Component { static propTypes = { comment: PropTypes.object.isRequired, showCommentEditForm: PropTypes.func.isRequired } state = { commentBody: '' } handleFormChange(event) { this.setState({ [event.target.name] : event.target.value}) } handleSubmit = (e) => { e.preventDefault() const { comment, makeUpdateCommentRequest, showCommentEditForm} = this.props const { commentBody } = this.state makeUpdateCommentRequest(comment.id, comment.parentId, commentBody) showCommentEditForm('') } render(){ const { showCommentEditForm, comment } = this.props return( <form className="form comment-edit-form" onSubmit={this.handleSubmit}> <div className="form__block"> <textarea name="commentBody" className="textarea" required autoFocus defaultValue={comment.body} onChange={event => this.handleFormChange(event)} /> </div> <div className="form__block"> <button className="btn btn--small btn--action" type="submit">Update</button> <button className="btn btn--small" onClick={()=>showCommentEditForm('')} type="button">Cancel</button> </div> </form> ) } }
JavaScript
class Token { constructor() { this.type = _base.state.type; this.contextualKeyword = _base.state.contextualKeyword; this.start = _base.state.start; this.end = _base.state.end; this.scopeDepth = _base.state.scopeDepth; this.isType = _base.state.isType; this.identifierRole = null; this.shadowsGlobal = false; this.isAsyncOperation = false; this.contextId = null; this.rhsEndIndex = null; this.isExpression = false; this.numNullishCoalesceStarts = 0; this.numNullishCoalesceEnds = 0; this.isOptionalChainStart = false; this.isOptionalChainEnd = false; this.subscriptStartIndex = null; this.nullishStartIndex = null; } // Initially false for all tokens, then may be computed in a follow-up step that does scope // analysis. // Initially false for all tokens, but may be set during transform to mark it as containing an // await operation. // For assignments, the index of the RHS. For export tokens, the end of the export. // For class tokens, records if the class is a class expression or a class statement. // Number of times to insert a `nullishCoalesce(` snippet before this token. // Number of times to insert a `)` snippet after this token. // If true, insert an `optionalChain([` snippet before this token. // If true, insert a `])` snippet after this token. // Tag for `.`, `?.`, `[`, `?.[`, `(`, and `?.(` to denote the "root" token for this // subscript chain. This can be used to determine if this chain is an optional chain. // Tag for `??` operators to denote the root token for this nullish coalescing call. }
JavaScript
class ChallengeList extends Component { render() { const manager = AsManager(this.props.user) // Show pinned challenges first const challengeCards = _sortBy( _map(this.props.challenges, challenge => ( <ChallengeCard {...this.props} key={challenge.id} challenge={challenge} isPinned={this.props.pinnedChallenges.indexOf(challenge.id) !== -1} /> )), challengeCard => !challengeCard.props.isPinned ) return ( <div className='admin__manage__managed-item-list challenge-list'> {!this.props.loadingChallenges && challengeCards.length === 0 ? <div className="challenge-list__no-results"> <FormattedMessage {...messages.noChallenges} /> </div> : challengeCards } {!this.props.suppressControls && manager.canWriteProject(this.props.project) && <div className="challenge-list__controls has-centered-children"> <button className="button is-green is-outlined new-challenge" onClick={() => this.props.history.push( `/admin/project/${this.props.project.id}/challenges/new`)}> <FormattedMessage {...messages.addChallengeLabel} /> </button> </div> } </div> ) } }
JavaScript
class Debugger extends React.Component { constructor() { super(); } render() { return ( <div id="debugger"> <Commands {...this.props} {...this.props.debug} /> <Pointers {...this.props.debug} /> <Stack {...this.props.debug} /> <IO {...this.props} {...this.props.debug} /> </div> ); } }
JavaScript
class Renderer extends ECS { /** * Creates a new renderer. * * @param {HTMLCanvasElement|WebGLRenderingContext} context - The canvas to create a context from, * or the context to use to draw. * @param {object} options - Options for the renderer. * @param {boolean} options.clearBeforeRender=true - Should we clear before each render? * @param {boolean} options.preserveDrawingBuffer=false - Enables drawing buffer preservation, * enable this if you need to call toDataUrl on the webgl context. */ constructor(context, options = {}) { super(); /** * The main rendering context used for drawing. * * @member {WebGLRenderingContext} */ this.gl = (context.nodeName ? GLContext.create(context) : context); /** * A unique ID for this renderer, useful for keying maps by renderer * * @member {number} */ this.uid = uid(); /** * Should we clear before each frame? * * @member {boolean} */ this.clearBeforeRender = typeof options.clearBeforeRender !== 'undefined' ? options.clearBeforeRender : true; /** * Should we preserve the drawing buffer each frame? * * @member {boolean} */ this.preserveDrawingBuffer = options.preserveDrawingBuffer || false; /** * Dispatched when context has been lost. * * @member {Signal} */ this.onContextLost = new Signal(); /** * Dispatched when context has been restored, but before the renderer * has initialized for the new context. * * If you are wanting to know when you should reinitialize your stuff * after a restore use {@link Renderer#onContextChange}. * * @member {Signal} */ this.onContextRestored = new Signal(); /** * Dispatched when context has changed. This happens when the renderer * initializes and then again if the context is restored, after we initialize * the context again. * * @member {Signal} */ this.onContextChange = new Signal(); /** * Dispatched each frame before rendering the object. * * @member {Signal} */ this.onBeforeRender = new Signal(); /** * Dispatched each frame after rendering the object. * * @member {Signal} */ this.onAfterRender = new Signal(); /** * An empty renderer. * * @member {ObjectRenderer} */ this.emptyRenderer = new ObjectRenderer(this); /** * The currently active object renderer. * * @member {ObjectRenderer} */ this.activeObjectRenderer = this.emptyRenderer; /** * The current state of the renderer. * * @member {WebGLState} */ this.state = new RenderState(this); /** * The root render target, that represents the screen. * * @member {RenderTarget} */ this.screen = null; this._boundOnContextLost = this._onContextLost.bind(this); this._boundOnContextRestored = this._onContextRestored.bind(this); this.gl.canvas.addEventListener('webglcontextlost', this._boundOnContextLost, false); this.gl.canvas.addEventListener('webglcontextrestored', this._boundOnContextRestored, false); // initialize for a new context this._initContext(); // create and add the default systems for (let i = 0; i < defaultSystems.length; ++i) { const system = new defaultSystems[i](this); this.addSystem(system); } } /** * Adds a system that will be created automatically when a renderer instance is created. * * Note: Calling this function registers a system to be automatically added in renderers * that you create *after* calling this. If you call this after creating a renderer, the * already created renderer will *not* contain this system automatically. * * @param {System} System - The system class to add (**not** an instance, but the class * itself) */ static addDefaultSystem(System) { defaultSystems.push(System); } /** * Removes a system so that it will no longer be created automatically when a renderer * instance is created. * * Note: Calling this function unregisters a system to be automatically added in renderers * that you create *after* calling this. If you call this after creating a renderer, the * already created renderer may contain this system automatically. * * @param {System} System - The system class to add (**not** an instance, but the class * itself) */ static removeDefaultSystem(System) { const idx = defaultSystems.indexOf(System); if (idx !== -1) { removeElements(defaultSystems, idx, 1); } } /** * Add a system to the renderer. * * @param {System} system - The system to add. * @param {boolean} skipSort - If true, will not sort the systems automatically. * Setting this to true requires you call {@link Renderer#sortSystems} manually. This * can be useful if you are adding a large batch of systems in a single frame and want * to delay the sorting until after they are all added. */ addSystem(system, skipSort = false) { super.addSystem(system); if (!skipSort) this.sortSystems(); } /** * Add an entity to the renderer. * * Note: Since adding an entity causes the entity list to be sorted (to ensure renderPriority * and grouping is correct), this method can be expensive when you have a large list. As such * it is recommended not to Add/Remove entities many times per frame. * * @param {Entity} entity - The entity to add. * @param {boolean} skipSort - If true, will not sort the entities automatically. * Setting this to true requires you call {@link Renderer#sortEntities} manually. This * can be useful if you are adding a large batch of entities in a single frame and want * to delay the sorting until after they are all added. */ addEntity(entity, skipSort) { super.addEntity(entity); if (!skipSort) this.sortEntities(); } /** * Sorts the systems by priority. If you change a system's priority after adding * it to the renderer then you will need to call this for it to be properly sorted. * */ sortSystems() { this.systems.sort(compareSystemsPriority); } /** * Sorts the entities by render priority and their group hint. If you change an * entity's priority after adding it to the renderer then you will need to call * this for it to take effect. * */ sortEntities() { this.entities.sort(compareRenderPriority); } /** * Renders a drawable object to the render target. * * @param {RenderTarget} target - The target to render to, defaults to the screen. * @param {boolean} clear - Should we clear the screen before rendering? * @param {Matrix2d} transform - An optional matrix transform to apply for this render. */ render(target = this.screen, clear = this.clearBeforeRender, transform = null) { // if no context, or context is lost, just bail. if (!this.gl || this.gl.isContextLost()) return; // tell everyone we are updating this.onBeforeRender.dispatch(); // set the target target.transform = transform; this.state.setRenderTarget(target); // start the active object renderer this.activeObjectRenderer.start(); // clear if we should if (clear) this.state.target.clear(); // process all the entites and their systems this.update(); // stop the active object renderer this.activeObjectRenderer.stop(); // tell everyone we updated this.onAfterRender.dispatch(); } /** * Sets the passed ObjectRenderer instance as the active object renderer. * * @param {ObjectRenderer} objectRenderer - The object renderer to use. */ setActiveObjectRenderer(objectRenderer) { if (this.activeObjectRenderer !== objectRenderer) { this.activeObjectRenderer.stop(); this.activeObjectRenderer = objectRenderer; this.activeObjectRenderer.start(); } } /** * Destroys this renderer and the related objects. * */ destroy() { // unbind canvas events this.gl.canvas.removeEventListener('webglcontextlost', this._boundOnContextLost, false); this.gl.canvas.removeEventListener('webglcontextrestored', this._boundOnContextRestored, false); this._boundOnContextLost = null; this._boundOnContextRestored = null; // destroy state this.state.destroy(); // detach and lose signals this.onContextLost.detachAll(); this.onContextLost = null; this.onContextRestored.detachAll(); this.onContextRestored = null; this.onContextChange.detachAll(); this.onContextChange = null; this.onBeforeRender.detachAll(); this.onBeforeRender = null; this.onAfterRender.detachAll(); this.onAfterRender = null; this.activeObjectRenderer = null; // finally lose context if (this.gl.getExtension('WEBGL_lose_context')) { this.gl.getExtension('WEBGL_lose_context').loseContext(); } this.gl = null; } /** * Initializes the WebGL context. * * @private */ _initContext() { const gl = this.gl; this.state.reset(); if (this.screen) { this.screen.destroy(); } this.screen = new RenderTarget(gl, gl.canvas.width, gl.canvas.height, RenderTarget.defaultScaleMode, true); this.state.setRenderTarget(this.screen); // this.resize(gl.canvas.width, gl.canvas.height); this.onContextChange.dispatch(this); } /** * Called when the underlying context is lost. * * @private * @param {WebGLContextEvent} event - The DOM event about the context being lost. */ _onContextLost(event) { event.preventDefault(); this.onContextLost.dispatch(this); } /** * Called when the underlying context is restored. * * @private */ _onContextRestored() { GLProgramCache.clear(); this._initContext(); this.onContextRestored.dispatch(this); } }
JavaScript
class Program { constructor(program) { this.WebGL_Program = program; // different uniform locations this.U_PIXELRATIO = null; this.U_RESOLUTION = null; this.U_ROTATION = null; this.U_SCALE = null; this.U_POSITION = null; this.U_PARENT_POS = null; this.U_PARENT_ROT = null; this.U_COLOR = null; this.U_TEXTURE = null; this.U_TIME = null; } setDefaultUniformLocations(gl, program) { this.U_PIXELRATIO = gl.getUniformLocation(program, 'u_pixelratio'); this.U_RESOLUTION = gl.getUniformLocation(program, 'u_resolution'); } setUniformLocationsBasic(gl, hasParent = false, texture = false, color = true) { const program = this.WebGL_Program; this.setDefaultUniformLocations(gl, program); this.U_ROTATION = gl.getUniformLocation(program, 'u_rotation'); this.U_SCALE = gl.getUniformLocation(program, 'u_scale'); this.U_POSITION = gl.getUniformLocation(program, 'u_position'); if (texture) { this.U_TEXTURE = gl.getUniformLocation(program, 'u_texture'); } if (color) { this.U_COLOR = gl.getUniformLocation(program, 'u_color'); } if (hasParent) { this.U_PARENT_POS = gl.getUniformLocation(program, 'u_parent_position'); this.U_PARENT_ROT = gl.getUniformLocation(program, 'u_parent_rotation'); } } setUniformLocationsPoints(gl) { const program = this.WebGL_Program; this.setDefaultUniformLocations(gl, program); this.U_SCALE = gl.getUniformLocation(program, 'u_scale'); } setUniformLocationsLines(gl) { const program = this.WebGL_Program; this.setDefaultUniformLocations(gl, program); this.U_COLOR = gl.getUniformLocation(program, 'u_color'); } setUniformLocationTime(gl) { this.U_TIME = gl.getUniformLocation(this.WebGL_Program, 'u_time'); } }
JavaScript
class Collection { /** * @param name: unique name for collection * @param schema: schema definition for validation in colleciton * @param indexByProp: unique index for each collection entry. this is going to be required. * @throws Error if invalid schema * @throws Error if unexpected error initializing page with unique id * @throws Error if invalid indexByProp */ constructor(name, schema, indexByProp) { this.$name = name; if (!indexByProp || !indexByProp.length) throw new Error(`Invalid indexByProp: ${indexByProp}. It should be a valid string naming the field that every entry is unique by.`); this.indexingProp = indexByProp; this._setSchema(schema); this.entries = new Map(); this._id = uuid(); let insertionAttempt = Collector.addCollection(this); if (!insertionAttempt) throw new Error(`Unexpected error initializing ${this.constructor.name} class with name ${name}. Ensure a collection with the same name has not already been created.`); } get id() { return this._id; } get name() { return this.$name; } /** * find an entry * @param matchObj: object - with one property (key), and associated value to retrieve entry by * @return matching entry or undefined */ findOne(matchObj) { const key = Object.keys(matchObj)[0]; return this._get(key, matchObj[key]); } /** * find all entries * @param matchObj: object - with one property (key), and associated value to retrieve entry by * @return array of matching entries or undefined */ find(matchObj) { const key = Object.keys(matchObj)[0]; return this._get(key, matchObj[key], true); } /** * @return iterable of all entries stored in collection */ findAll() { return Array.from(this.entries.values()); } /** * insert entry to collection * @param o: item to insert into collection * @throws Error if item does not validate against collection's schema * @return previous entry with the same value for its 'indexingProp' if exists */ insert(o) { if (!Collection.validateAgainstSchema(o, this)) throw new Error(`Invalid insertion item. ${o}`); const key = o[this.indexingProp]; const old = this.entries.get(key); this.entries.set(key, this._fillDefaultValues(o)); return old; } /** * remove entry from collection * NOTE: removal would be quicker if key is the unique indexing property * @param queryObject: has 1 key/value pair to match entries with * @return list of deleted entries or empty list */ remove(queryObject) { if (typeof queryObject != "object" || Array.isArray(queryObject)) throw new Error(`Invalid queryObject: ${queryObject}: This param must be an object with 1 key/value pair to match entries with.`); const key = Object.keys(queryObject)[0]; const value = queryObject[key]; if (typeof key != "string") throw new Error(`Invalid key: ${key}. This must be a string of the property to match value with`); let listOfRemovedEntries = []; if (key === this.indexingProp) { listOfRemovedEntries.push(this.entries.get(value)); this.entries.delete(value); } else { const entries = this.entries.entries(); for (let entry of entries) { if (entry[1][key] == value) { listOfRemovedEntries.push(entry[1]); this.entries.delete(entry[0]); } } }; return listOfRemovedEntries; } /* * update schema * @param schema: object -- schema * @throws Error if invalid schema * @return old schema */ _setSchema(schema) { if(!Collection.validateSchema(schema, [this.indexingProp])) throw new Error(`Invalid schema: ${schema}`); const old = this.schema; this.schema = schema; let propBreakdown = Object.keys(schema).reduce((accum, prop) => { if (typeof schema[prop].defaultValue != "undefined") { accum[0][prop] = true; } else if (schema[prop].required) { accum[1][prop] = true; } return accum; }, [{}, {}]); this.propsWithDefaults = propBreakdown[0]; this.requiredWithNoDefault = propBreakdown[1]; return old; } /** * looks through an entry's properties and fills missing properties with schema-defined default values * @param entry: object -- an entry object validated against schema already * @return entry object with missing properties filled in using schema-defined defaults */ _fillDefaultValues(entry) { let defaultDefinedProps = extend({}, this.propsWithDefaults); for (let prop in entry) { if (typeof entry[prop] != "undefined" && prop in defaultDefinedProps) delete defaultDefinedProps[prop]; }; // fill in remaining const schema = this.schema; for(let prop in defaultDefinedProps) entry[prop] = schema[prop].defaultValue; return entry; } /** * get an entry by key and value * NOTE: if key is the unique indexing property, then retrieval by value will be quicker * @param key: string -- key to compare value to for entry retrieval * @param value: value to match entry with * @param multi: boolean -- true if return in array form (return all matching entries) * @return matching entry/entries if found. undefined otherwise */ _get(key, value, multi) { if (key === this.indexingProp) { return multi? ((typeof this.entries.get(value) != "undefined" || undefined) && [this.entries.get(value)]): this.entries.get(value); } else { let returner = multi && []; const entries = this.entries.entries(); for (let entry of entries) { if (key in entry[1] && entry[1][key] === value) { if (!multi) return entry[1]; returner.push(entry[1]); } } return (returner.length || undefined) && returner; }; return; } /** * validate format of a schema object * @param schema: object -- schema EX: { "name": { "type": "string", "required": true, "defaultValue": "Monet", }, "emailAdresses": { "type": "[string]", "required": true, }, "preferredOpera": { "type": "object", "required": false, }, } NOTE: > valid types are: 'string', 'object', 'boolean', 'number' > types can be wrapped in arrays using square bracket wrappers (EX. '[string]') * @param requiredProps: optional [String] - list of fields required to be defined in schema * @return true if valid */ static validateSchema(schema, requiredProps = []) { if (typeof schema != "object" && !Array.isArray(schema)) { return false; }; if (!Array.isArray(requiredProps) || requiredProps.reduce((accum, str) => { return accum || typeof str != "string"; }, false)) { return false; }; const validTypes = new Set(VALID_TYPES); let requiredItems = requiredProps.reduce((accum, itemName) => { accum[itemName] = true; return accum; }, {}); // copy array into object for quick match and to ensure original param is not mutatedf for (let prop in schema) { let propDefinition = schema[prop]; if (typeof propDefinition != "object" || Array.isArray(propDefinition)) return false; if (!validTypes.has(propDefinition.type)) return false; if (typeof propDefinition.required !== "boolean" && typeof propDefinition.required !== "undefined") return false; if (typeof propDefinition.defaultValue != "undefined" && typeof propDefinition.defaultValue != propDefinition.type) return false; if (prop in requiredItems) { delete requiredItems[prop]; }; }; return Object.keys(schema).length > 0 && Object.keys(requiredItems).length === 0; } /** * validate an entry against currently set schema * NOTE: fill the default required properties using _fillDefaultValues(entry) method * @param o: variable to validate against schema * @param collectionInstance: collection to insert o into * @return true if valid */ static validateAgainstSchema(o, collectionInstance) { const schema = collectionInstance.schema; if (typeof o != "object" || Array.isArray(o)) return false; let requiredPropsWithNoDefaultValues = extend({}, collectionInstance.requiredWithNoDefault); let requiredPropsWithDefaultValues = collectionInstance.propsWithDefaults; for (let prop in o) { if (typeof o[prop] == "undefined" && prop in requiredPropsWithDefaultValues) continue; const propDefinition = schema[prop]; if (typeof propDefinition == "undefined") return false; if (propDefinition.required && (prop in requiredPropsWithNoDefaultValues)) delete requiredPropsWithNoDefaultValues[prop]; const isArray = propDefinition.type[0] === '['; const type = isArray ? propDefinition.type.slice(1, -1) : propDefinition.type; const propValue = o[prop]; if (isArray) { if (!Array.isArray(propValue)) return false; for(let item of propValue) { if(typeof item != type) return false; } } else if (typeof propValue != type) { return false; }; }; if (Object.keys(requiredPropsWithNoDefaultValues).length) return false; return true; } }
JavaScript
class AbstractStyle { /** * Constructor. * @param {string} layerId * @param {T} value * @param {T=} opt_oldValue */ constructor(layerId, value, opt_oldValue) { /** * The details of the command. * @type {?string} */ this.details = null; /** * Whether or not the command is asynchronous. * @type {boolean} */ this.isAsync = false; /** * Return the current state of the command. * @type {!State} */ this.state = State.READY; /** * The title of the command. * @type {?string} */ this.title = 'Change Style'; /** * @type {string} * @protected */ this.layerId = layerId; /** * @type {T} * @protected */ this.oldValue = opt_oldValue; /** * @type {T} * @protected */ this.value = value; /** * @type {?string} * @protected */ this.metricKey = null; } /** * @inheritDoc */ execute() { if (this.canExecute()) { this.state = State.EXECUTING; this.setValue(this.value); if (this.metricKey) { Metrics.getInstance().updateMetric(this.metricKey, 1); } this.state = State.SUCCESS; return true; } return false; } /** * @inheritDoc */ revert() { this.state = State.REVERTING; this.setValue(this.oldValue); this.state = State.READY; return true; } /** * Checks if the command is ready to execute. * * @return {boolean} */ canExecute() { if (this.state !== State.READY) { this.details = 'Command not in ready state.'; return false; } if (!this.layerId) { this.state = State.ERROR; this.details = 'Layer ID not provided.'; return false; } if (this.value === undefined) { this.state = State.ERROR; this.details = 'Value not provided'; return false; } return true; } /** * Gets the old value * * @return {T} the old value * @protected */ getOldValue() { return null; } /** * Update the old value on the command, if currently unset. Call this during initialization if the command sets class * properties in the constructor that are required by getOldValue. * @protected */ updateOldValue() { if (this.oldValue == null) { this.oldValue = this.getOldValue(); } } /** * Applies a value to the style config * * @param {Object} config The style config * @param {T} value The value to apply */ applyValue(config, value) {} /** * Fire events, cleanup, etc. * * @param {Object} config * @protected */ finish(config) { // intended for overriding classes - default to doing nothing } /** * Get the layer configuration. * * @param {ILayer} layer * @return {Object} * @protected */ getLayerConfig(layer) { if (instanceOf(layer, LayerClass.TILE)) { return /** @type {TileLayer} */ (layer).getLayerOptions(); } if (instanceOf(layer, LayerClass.VECTOR)) { return StyleManager.getInstance().getLayerConfig(/** @type {VectorLayer} */ (layer).getId()); } return null; } /** * Sets the value * * @param {T} value */ setValue(value) { asserts.assert(value != null, 'style value must be defined'); var layer = /** @type {VectorLayer} */ (this.getLayer()); asserts.assert(layer, 'layer must be defined'); var config = this.getLayerConfig(layer); asserts.assert(config, 'layer config must be defined'); this.applyValue(config, value); this.finish(config); } /** * Gets the layer by ID. * * @return {ILayer} */ getLayer() { const map = getMapContainer(); return map ? /** @type {ILayer} */ (map.getLayer(this.layerId)) : null; } }
JavaScript
class RotateBy extends ActionInterval { /** * PUBLIC METHODS * ----------------------------------------------------------------------------------------------------------------- */ /** * @constructor * @param {number} duration * @param {number} deltaAngle */ constructor(duration, deltaAngle) { super(duration); this._angle = deltaAngle; this._startAngle = 0; } /** * @desc Need to copy object with deep copy. Returns a clone of action. * @method * @public * @return {MANTICORE.animation.action.RotateBy} */ clone() { return this.doClone(RotateBy.create(this.duration, this._angle)); } /** * @method * @public * @param {PIXI.DisplayObject} target */ startWithTarget(target) { super.startWithTarget(target); this._startAngle = Math.toDegrees(target.rotation); } update(dt){ dt = this.computeEaseTime(dt); if (!this.hasTarget()) { return; } this.target.rotation = Math.toRadians(this._startAngle + this._angle * dt); } /** * @desc Returns a reversed action. * @method * @public * @return {MANTICORE.animation.action.RotateBy} */ reverse() { return this.doReverse(RotateBy.create(this.duration, -this._angle)); } /** * @desc Calls by pool when object get from pool. Don't call it only override. * @method * @public * @param {number} duration * @param {number} deltaAngle */ reuse(duration, deltaAngle) { this._angle = deltaAngle; this._startAngle = 0; super.reuse(duration); } /** * PROTECTED METHODS * ----------------------------------------------------------------------------------------------------------------- */ /** * @desc Clear data befor disuse and destroy. * @method * @protected */ clearData() { this._angle = 0; this._startAngle = 0; super.clearData(); } }
JavaScript
class Controllers { /** * Create a Controllers. * @param {DevSpacesManagementClient} client Reference to the service client. */ constructor(client) { this.client = client; this._get = _get; this._create = _create; this._deleteMethod = _deleteMethod; this._update = _update; this._listByResourceGroup = _listByResourceGroup; this._list = _list; this._listConnectionDetails = _listConnectionDetails; this._beginCreate = _beginCreate; this._beginDeleteMethod = _beginDeleteMethod; this._listByResourceGroupNext = _listByResourceGroupNext; this._listNext = _listNext; } /** * @summary Gets an Azure Dev Spaces Controller. * * Gets the properties for an Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error} - The error object. */ getWithHttpOperationResponse(resourceGroupName, name, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._get(resourceGroupName, name, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Gets an Azure Dev Spaces Controller. * * Gets the properties for an Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Controller} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName, name, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._get(resourceGroupName, name, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._get(resourceGroupName, name, options, optionalCallback); } } /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error} - The error object. */ createWithHttpOperationResponse(resourceGroupName, name, controller, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._create(resourceGroupName, name, controller, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Controller} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName, name, controller, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._create(resourceGroupName, name, controller, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._create(resourceGroupName, name, controller, options, optionalCallback); } } /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName, name, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._deleteMethod(resourceGroupName, name, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName, name, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._deleteMethod(resourceGroupName, name, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._deleteMethod(resourceGroupName, name, options, optionalCallback); } } /** * @summary Updates an Azure Dev Spaces Controller. * * Updates the properties of an existing Azure Dev Spaces Controller with the * specified update parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controllerUpdateParameters * * @param {object} [controllerUpdateParameters.tags] Tags for the Azure Dev * Spaces Controller. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error} - The error object. */ updateWithHttpOperationResponse(resourceGroupName, name, controllerUpdateParameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._update(resourceGroupName, name, controllerUpdateParameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Updates an Azure Dev Spaces Controller. * * Updates the properties of an existing Azure Dev Spaces Controller with the * specified update parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controllerUpdateParameters * * @param {object} [controllerUpdateParameters.tags] Tags for the Azure Dev * Spaces Controller. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Controller} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName, name, controllerUpdateParameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._update(resourceGroupName, name, controllerUpdateParameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._update(resourceGroupName, name, controllerUpdateParameters, options, optionalCallback); } } /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listByResourceGroup(resourceGroupName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listByResourceGroup(resourceGroupName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listByResourceGroup(resourceGroupName, options, optionalCallback); } } /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error} - The error object. */ listWithHttpOperationResponse(options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._list(options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ list(options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._list(options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._list(options, optionalCallback); } } /** * @summary Lists connection details for an Azure Dev Spaces Controller. * * Lists connection details for the underlying container resources of an Azure * Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerConnectionDetailsList>} - The deserialized result object. * * @reject {Error} - The error object. */ listConnectionDetailsWithHttpOperationResponse(resourceGroupName, name, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listConnectionDetails(resourceGroupName, name, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists connection details for an Azure Dev Spaces Controller. * * Lists connection details for the underlying container resources of an Azure * Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ControllerConnectionDetailsList} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ControllerConnectionDetailsList} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listConnectionDetails(resourceGroupName, name, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listConnectionDetails(resourceGroupName, name, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listConnectionDetails(resourceGroupName, name, options, optionalCallback); } } /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName, name, controller, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginCreate(resourceGroupName, name, controller, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Controller} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName, name, controller, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginCreate(resourceGroupName, name, controller, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginCreate(resourceGroupName, name, controller, options, optionalCallback); } } /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName, name, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginDeleteMethod(resourceGroupName, name, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName, name, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginDeleteMethod(resourceGroupName, name, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginDeleteMethod(resourceGroupName, name, options, optionalCallback); } } /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listByResourceGroupNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listByResourceGroupNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listByResourceGroupNext(nextPageLink, options, optionalCallback); } } /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error} - The error object. */ listNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listNext(nextPageLink, options, optionalCallback); } } }
JavaScript
class Scheduler { constructor (func, delay) { this.timer = null this.delay = delay this.now = Date.now() this.func = func this.cleared = false } get timeLeft () { if (this.cleared) return false return this.now + this.delay - Date.now() } plan () { this.timer = setTimeout(this.func, this.delay) } cancel () { clearTimeout(this.timer) this.cleared = true } }
JavaScript
class Button extends ActionItem { /** * @param {HTMLElement | JQuery} el * @param {Function} [fn] A function to call when the item is invoked * @param {*} [thisArg] The object to be used as the thisArg when invoking the attached action function */ constructor(el, fn, thisArg) { super(el, fn, thisArg); this.stopPropagation = false; this.stopImmediatePropagation = false; this.preventDefault = false; this._init(); } get type() { return 'button'; } _init() { let target = this._$el[0]; if (target != null && target.onclick != null) { this._extractOnClick(); } this._$el.on('click', this._click.bind(this)); } /** @param {MouseEvent} e */ _click(e) { if (this.preventDefault || this.tagName === 'a') e.preventDefault(); if (this.stopPropagation) e.stopPropagation(); if (this.stopImmediatePropagation) e.stopImmediatePropagation(); this.invoke(e); } /** @param {HTMLElement} el */ _extractOnClick(el) { const hardCodedOnClick = el.onclick; if (this._fn == null) { // If no action was passed in, simply assign the hard coded onclick function this._action = hardCodedOnClick; this._thisArg = el; } else { // If an explicit action was also passed in, the wrap it // in a function that first calls the hard coded onclick handler, // and then calls the action function const fn = this._fn; const me = this; this._fn = function (...args) { hardCodedOnClick.call(el, me._event); fn.call(me._thisArg, ...args); }; } } }
JavaScript
class Validator { /** * @ignore */ constructor() {} /** * Main function to be called * * @param {object} options * @param {object} referenceOptions * @param {object} subObject * @returns {boolean} * @static */ static validate(options, referenceOptions, subObject) { errorFound = false; allOptions = referenceOptions; let usedOptions = referenceOptions; if (subObject !== undefined) { usedOptions = referenceOptions[subObject]; } Validator.parse(options, usedOptions, []); return errorFound; } /** * Will traverse an object recursively and check every value * * @param {object} options * @param {object} referenceOptions * @param {Array} path | where to look for the actual option * @static */ static parse(options, referenceOptions, path) { for (const option in options) { if (Object.prototype.hasOwnProperty.call(options, option)) { Validator.check(option, options, referenceOptions, path); } } } /** * Check every value. If the value is an object, call the parse function on that object. * * @param {string} option * @param {object} options * @param {object} referenceOptions * @param {Array} path | where to look for the actual option * @static */ static check(option, options, referenceOptions, path) { if ( referenceOptions[option] === undefined && referenceOptions.__any__ === undefined ) { Validator.getSuggestion(option, referenceOptions, path); return; } let referenceOption = option; let is_object = true; if ( referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined ) { // NOTE: This only triggers if the __any__ is in the top level of the options object. // THAT'S A REALLY BAD PLACE TO ALLOW IT!!!! // TODO: Examine if needed, remove if possible // __any__ is a wildcard. Any value is accepted and will be further analysed by reference. referenceOption = "__any__"; // if the any-subgroup is not a predefined object in the configurator, // we do not look deeper into the object. is_object = Validator.getType(options[option]) === "object"; } else { // Since all options in the reference are objects, we can check whether // they are supposed to be the object to look for the __type__ field. // if this is an object, we check if the correct type has been supplied to account for shorthand options. } let refOptionObj = referenceOptions[referenceOption]; if (is_object && refOptionObj.__type__ !== undefined) { refOptionObj = refOptionObj.__type__; } Validator.checkFields( option, options, referenceOptions, referenceOption, refOptionObj, path ); } /** * * @param {string} option | the option property * @param {object} options | The supplied options object * @param {object} referenceOptions | The reference options containing all options and their allowed formats * @param {string} referenceOption | Usually this is the same as option, except when handling an __any__ tag. * @param {string} refOptionObj | This is the type object from the reference options * @param {Array} path | where in the object is the option * @static */ static checkFields( option, options, referenceOptions, referenceOption, refOptionObj, path ) { const log = function (message) { console.error( "%c" + message + Validator.printLocation(path, option), printStyle ); }; const optionType = Validator.getType(options[option]); const refOptionType = refOptionObj[optionType]; if (refOptionType !== undefined) { // if the type is correct, we check if it is supposed to be one of a few select values if ( Validator.getType(refOptionType) === "array" && refOptionType.indexOf(options[option]) === -1 ) { log( 'Invalid option detected in "' + option + '".' + " Allowed values are:" + Validator.print(refOptionType) + ' not "' + options[option] + '". ' ); errorFound = true; } else if (optionType === "object" && referenceOption !== "__any__") { path = copyAndExtendArray(path, option); Validator.parse( options[option], referenceOptions[referenceOption], path ); } } else if (refOptionObj["any"] === undefined) { // type of the field is incorrect and the field cannot be any log( 'Invalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + ". Received [" + optionType + '] "' + options[option] + '"' ); errorFound = true; } } /** * * @param {object | boolean | number | string | Array.<number> | Date | Node | Moment | undefined | null} object * @returns {string} * @static */ static getType(object) { const type = typeof object; if (type === "object") { if (object === null) { return "null"; } if (object instanceof Boolean) { return "boolean"; } if (object instanceof Number) { return "number"; } if (object instanceof String) { return "string"; } if (Array.isArray(object)) { return "array"; } if (object instanceof Date) { return "date"; } if (object.nodeType !== undefined) { return "dom"; } if (object._isAMomentObject === true) { return "moment"; } return "object"; } else if (type === "number") { return "number"; } else if (type === "boolean") { return "boolean"; } else if (type === "string") { return "string"; } else if (type === undefined) { return "undefined"; } return type; } /** * @param {string} option * @param {object} options * @param {Array.<string>} path * @static */ static getSuggestion(option, options, path) { const localSearch = Validator.findInOptions(option, options, path, false); const globalSearch = Validator.findInOptions(option, allOptions, [], true); const localSearchThreshold = 8; const globalSearchThreshold = 4; let msg; if (localSearch.indexMatch !== undefined) { msg = " in " + Validator.printLocation(localSearch.path, option, "") + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n'; } else if ( globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance ) { msg = " in " + Validator.printLocation(localSearch.path, option, "") + "Perhaps it was misplaced? Matching option found at: " + Validator.printLocation( globalSearch.path, globalSearch.closestMatch, "" ); } else if (localSearch.distance <= localSearchThreshold) { msg = '. Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option); } else { msg = ". Did you mean one of these: " + Validator.print(Object.keys(options)) + Validator.printLocation(path, option); } console.error( '%cUnknown option detected: "' + option + '"' + msg, printStyle ); errorFound = true; } /** * traverse the options in search for a match. * * @param {string} option * @param {object} options * @param {Array} path | where to look for the actual option * @param {boolean} [recursive=false] * @returns {{closestMatch: string, path: Array, distance: number}} * @static */ static findInOptions(option, options, path, recursive = false) { let min = 1e9; let closestMatch = ""; let closestMatchPath = []; const lowerCaseOption = option.toLowerCase(); let indexMatch = undefined; for (const op in options) { let distance; if (options[op].__type__ !== undefined && recursive === true) { const result = Validator.findInOptions( option, options[op], copyAndExtendArray(path, op) ); if (min > result.distance) { closestMatch = result.closestMatch; closestMatchPath = result.path; min = result.distance; indexMatch = result.indexMatch; } } else { if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) { indexMatch = op; } distance = Validator.levenshteinDistance(option, op); if (min > distance) { closestMatch = op; closestMatchPath = copyArray(path); min = distance; } } } return { closestMatch: closestMatch, path: closestMatchPath, distance: min, indexMatch: indexMatch, }; } /** * @param {Array.<string>} path * @param {object} option * @param {string} prefix * @returns {string} * @static */ static printLocation(path, option, prefix = "Problem value found at: \n") { let str = "\n\n" + prefix + "options = {\n"; for (let i = 0; i < path.length; i++) { for (let j = 0; j < i + 1; j++) { str += " "; } str += path[i] + ": {\n"; } for (let j = 0; j < path.length + 1; j++) { str += " "; } str += option + "\n"; for (let i = 0; i < path.length + 1; i++) { for (let j = 0; j < path.length - i; j++) { str += " "; } str += "}\n"; } return str + "\n\n"; } /** * @param {object} options * @returns {string} * @static */ static print(options) { return JSON.stringify(options) .replace(/(")|(\[)|(\])|(,"__type__")/g, "") .replace(/(,)/g, ", "); } /** * Compute the edit distance between the two given strings * http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript * * Copyright (c) 2011 Andrei Mackenzie * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @param {string} a * @param {string} b * @returns {Array.<Array.<number>>}} * @static */ static levenshteinDistance(a, b) { if (a.length === 0) return b.length; if (b.length === 0) return a.length; const matrix = []; // increment along the first column of each row let i; for (i = 0; i <= b.length; i++) { matrix[i] = [i]; } // increment each column in the first row let j; for (j = 0; j <= a.length; j++) { matrix[0][j] = j; } // Fill in the rest of the matrix for (i = 1; i <= b.length; i++) { for (j = 1; j <= a.length; j++) { if (b.charAt(i - 1) == a.charAt(j - 1)) { matrix[i][j] = matrix[i - 1][j - 1]; } else { matrix[i][j] = Math.min( matrix[i - 1][j - 1] + 1, // substitution Math.min( matrix[i][j - 1] + 1, // insertion matrix[i - 1][j] + 1 ) ); // deletion } } } return matrix[b.length][a.length]; } }
JavaScript
class Manager extends Employee { constructor(name, id, email, office, role) { //using super to import parent data from employee super(name, id, email); this.office = office; this.role = role; } getStoreId() { if (!this.office) { return "No store id Available"; } else { return this.office; } } getRole() { if (this.role === "Manager") { return "Manager"; } else { return "Role Not determined"; } } }
JavaScript
class BaseContainer { /** * Array utility: sort and uniq. * @param {Array} list - Items. * @returns {Array} Sorted unique items. */ sortUniq(list) { return Array.from(new Set(list)).sort() } /** * Array utility: flatten * @param {Array<Array>} list - Items. * @returns {Array} Flatten items. */ flatten(list) { // common class method // (to avoid monkey patch to Array.prototype) // https://qiita.com/shuhei/items/5a3d3a779b64a81b8c8d return Array.prototype.concat.apply([], list) } }
JavaScript
class ThumbnailSource extends events.EventEmitter { constructor(geojson, template, imageOptions, mapOptions) { super(); this._size = imageOptions.tileSize || 256; // see image encoding options: https://github.com/mapnik/mapnik/wiki/Image-IO this._imageEncoding = imageOptions.encoding || 'png8:m=h:z=1'; this._bufferSize = 64; this._mapOptions = mapOptions || {}; this._xml = template.replace('{{geojson}}', JSON.stringify(geojson)); this.stats = { requested: 0, rendered: 0 }; } /** * Gets a tile from this source. * * @param {number} z * @param {number} x * @param {number} y * @param {function} callback */ getTile(z, x, y, callback) { const encoding = this._imageEncoding; const size = this._size; const map = new mapnik.Map(size, size); map.bufferSize = this._bufferSize; try { // TODO: It is not smart or performant to create a new mapnik instance for each tile rendering this.stats.rendered += 1; map.fromString(this._xml, this._mapOptions, function onMapLoaded(err) { if (err) return callback(err); map.extent = sm.bbox(x, y, z, false, '900913'); map.render(new mapnik.Image(size, size), {}, function onImageRendered(err, image) { if (err) return callback(err); image.encode(encoding, function onImageEncoded(err, encodedImage) { callback(err, encodedImage); }); }); }); } catch (e) { callback(e); } } }
JavaScript
class RadioOptions extends Component { constructor(props) { super(props); const value = this.retrieveValue(); this.state = { value }; } handleChange = e => { const value = e.target.value; this.notify(value); this.setState({value}); }; handleBlur = e => { const { formProps } = this.props; const handleBlur = this.props.onBlur ? this.props.onBlur : formProps && formProps.handleBlur ? e => formProps.handleBlur(e) : () => {}; handleBlur(e); }; notify = value => { const { name, formProps } = this.props; const handleChange = this.props.onChange ? this.props.onChange : formProps && formProps.setFieldValue ? value => formProps.setFieldValue(name, value) : () => {}; handleChange(value); }; retrieveValue = () => { const { name, formProps } = this.props; const noFormProps = !formProps || !formProps.values; if (noFormProps && this.props.hasOwnProperty('value')) return this.props.value; if (formProps && formProps.values && formProps.values.hasOwnProperty(name)) { return formProps.values[name]; } return null; }; render() { const { label, name, options, layout, required } = this.props; const requiredTag = required ? <span className="required">*</span> : ''; const touched = retrieveValue('touched', this.props); const error = retrieveValue('error', this.props); const isInvalid = touched && error; const validationState = isInvalid ? 'error' : null; const labelRender = label ? layout !== 'vertical' ? (<label className="control-label col-md-3 col-sm-3 col-xs-12" htmlFor={ name + '0' }>{ label } { requiredTag }</label>) : (<label htmlFor={ name + '0' }>{ label } { requiredTag }</label>) : ''; const layoutClass = layout === 'centered' ? 'col-md-6 col-sm-6 col-xs-12' : layout === 'vertical' ? '' : 'col-md-9 col-sm-9 col-xs-12'; return ( <FormGroup validationState={ validationState }> { labelRender } <div className={ label ? layoutClass : ''}> { options.map((element, i) => { const checked = element.value === this.state.value; return ( <div key={i} className="radio"> <label htmlFor={ name + i}> <input onBlur={ this.handleBlur } checked={checked} onChange={ this.handleChange } type="radio" value={ element.value } name={ name } id={ name + i}/> { element.label } </label> </div> ) }) } { isInvalid ? <HelpBlock>{ error }</HelpBlock> : '' } </div> </FormGroup> ); } }
JavaScript
class ContentTest extends DistributedChildrenContentMixin( DistributedChildrenMixin( ShadowTemplateMixin(HTMLElement) ) ) { contentChanged() { this._saveTextContent = this.textContent; if (this.contentChangedHook) { this.contentChangedHook(); } } get [symbols.template]() { return ` <div id="static">This is static content</div> <slot></slot> `; } }
JavaScript
class WrappedContentTest extends ShadowTemplateMixin(HTMLElement) { get [symbols.template]() { return `<content-test><slot></slot></content-test>`; } }
JavaScript
class WebpackConfig extends Singleton { /** * Constructs an instance. */ constructor() { super(); /** {Logger} Logger for this module. */ this.log = new Logger('client-bundle'); /** * {ProgressMessage} Handler that logs progress messages during compilation. */ this.progress = new ProgressMessage(this.log); /** {string} The base directory for all of the client files. */ this._clientDir = Dirs.theOne.CLIENT_DIR; /** {string} Path to the client `node_modules` directory. */ this._nodeModulesDir = path.resolve(this._clientDir, 'node_modules'); Object.freeze(this); } /** * {object} Options passed to the `webpack` compiler constructor. Of * particular note, we _do not_ try to restrict the loaders to any particular * directories (e.g. via `include` configs), instead _just_ applying them * based on filename extension. As such, any `.js` file will get loaded via * our "modern ES" pipeline, and any `.ts` file will get loaded via the * TypeScript loader. * * **Note** about `require.resolve()` as used below: Babel doesn't respect the * Webpack `context` option. Because we treat the `client` and `server` as * peers (that is, because the server modules aren't in a super-directory of * `client`), we have to "manually" resolve the presets. See * <https://github.com/babel/babel-loader/issues/149>, * <https://github.com/babel/babel-loader/issues/166>, and * <http://stackoverflow.com/questions/34574403/how-to-set-resolve-for-babel-loader-presets/> * for details and discussion. */ get webpackConfig() { const nodeModulesDir = this._nodeModulesDir; const mainModuleDir = this._findMainModule(); // The parsed `package.json` for the client's "main" module. const mainPackage = JsonUtil.parseFrozen( fs.readFileSync(path.resolve(mainModuleDir, 'package.json'))); return { // Used for resolving loaders and the like. context: Dirs.theOne.SERVER_DIR, // `inline-source-map` _should_ work, but for some reason doesn't seem to. // Using `cheap-module-eval-source-map` _does_ work on Chrome (v60) but // causes inscrutable problems on Safari (v10.1.2). **TODO:** Investigate // this. devtool: 'inline-source-map', // We use `development` mode here, in that this module is the thing that // does live (re-)building of the client code. For production, the // expectation is that the client code will get built as part of the // offline build process. mode: 'development', entry: { main: [ 'babel-polyfill', path.resolve(mainModuleDir, mainPackage.main) ], test: [ 'babel-polyfill', path.resolve(mainModuleDir, mainPackage.testMain) ] }, output: { // Absolute output path of `/` because we write to a memory filesystem. // And no `.js` suffix, because the memory filesystem contents aren't // served out directly but just serve as an intermediate waystation. See // {@link ClientBundle#_handleCompilation} for more details. path: '/', filename: '[name]', publicPath: '/static/js/' }, plugins: [ new webpack.ProgressPlugin(this.progress.handler) ], resolve: { alias: { // The `quill` module as published exports an entry point which // references a prebuilt bundle. We rewrite it here to refer instead // to the unbundled source. 'quill': path.resolve(nodeModulesDir, 'quill/quill.js'), // Likewise, `parchment`. 'parchment': path.resolve(nodeModulesDir, 'parchment/src/parchment.ts'), // On the client side, we use the local module // {@link @bayou/mocha-client-shim} as a substitute for `mocha`, and // that module refers to `mocha-client-bundle`. These two aliases // makes it so that unit test code can still write `import ... from // 'mocha';`. 'mocha': path.resolve(nodeModulesDir, '@bayou/mocha-client-shim'), 'mocha-client-bundle': path.resolve(nodeModulesDir, 'mocha/mocha.js') }, // All the extensions listed here except `.ts` are in the default list. // Webpack doesn't offer a way to simply add to the defaults (alas). extensions: ['.webpack.js', '.web.js', '.js', '.ts'] }, module: { rules: [ // Convert JavaScript from the modern syntax that we use to what is // supported by the browsers / environments we target. { test: /\.js$/, use: [{ loader: 'babel-loader', options: { presets: [ [ require.resolve('babel-preset-env'), { sourceMaps: 'inline', targets: { browsers: [ // See <https://github.com/ai/browserslist> for the // syntax used here. 'Chrome >= 61', 'ChromeAndroid >= 61', 'Electron >= 1.8', 'Firefox >= 54', 'iOS >= 11', 'Safari >= 11' ] } } ] ] } }] }, // Enable pass-through of the Babel-provided source maps. { test: /\.js$/, enforce: 'pre', use: [{ loader: 'source-map-loader' }] }, // This handles dynamic construction of the main test-collector file, // for client-side unit testing. { test: /@bayou[/]testing-client[/]client-tests$/, use: [{ loader: '@bayou/testing-server/loadClientTests' }] }, // Convert TypeScript files. As of this writing, this is only required // for Parchment (a dependency of Quill). The TypeScript configuration // here has to be compatible with how Parchment wants to be built. // That is, be wary of changes to the `parchment` module which require // reconfiguration of the build process. { test: /\.ts$/, use: [{ loader: 'ts-loader', options: { compilerOptions: { // A reasonably conservative choice, and also recapitulates // what Parchment's `tsconfig.json` specifies. target: 'es5', // Parchment specifies this as `true`, but we need it to be // `false` because we _aren't_ building it as a standalone // library. declaration: false }, silent: true, // Avoids the banner spew. transpileOnly: true } }] }, // Support `import` / `require()` of SVG files. As of this writing, // this is only needed by Quill. The configuration here recapitulates // how Quill is set up to process those assets. See // <https://github.com/quilljs/quill/blob/develop/_develop/webpack.config.js>. { test: /\.svg$/, use: [{ loader: 'html-loader', options: { minimize: true } }] } ] } }; } /** {object} Options passed to `compiler.watch()`. */ get watchConfig() { return { // Wait up to this many msec after detecting a changed file. This helps // prevent a rebuild from starting while in the middle of a file save. aggregateTimeout: 1000 }; } /** * Gets the filesystem path for the directory containing the "main" module of * the client. * * @returns {string} Path to the "main" module. */ _findMainModule() { // The parsed `package.json` for the top-level client directory... const clientPackage = JsonUtil.parseFrozen( fs.readFileSync(path.resolve(this._clientDir, 'package.json'))); // ...which tells us the name of the "main" module. const name = clientPackage.mainModule; return path.resolve(this._nodeModulesDir, name); } }
JavaScript
class ScaledVars { constructor(variableOptions) { this.vars = variableOptions; } /* * Variables getter. */ get vars() { return this._vars; } /* * Variables setter. */ set vars(variableOptions) { this._vars = variableOptions.map(options => new Variable(options)); } /* * Iterate over variables and apply scaled transformation on each. */ update(value, vars = this.vars) { vars.forEach(variable => variable.update(value)); return vars; } /* * Expose D3's scale engine module. */ static get Scales() { return Scales; } /* * Expose underlying Variable class. */ static get Variable() { return Variable; } }
JavaScript
class CalculateCLS { constructor(age, propertyFMV, term, afr) { ///SET UP ALLOCATION PERCENTAGES this.age = age; this.propertyFMV = propertyFMV; this.term = term; this.afr = afr; //var annExp = $('#annual_expense_ratio').dropdown('get value'); if(window.myBarChart!=null){ window.myBarChart.destroy(); } }//end constructor in javascript class clearResults() { } CalculateQPRT() { ///FIRST VALUE THE INCOME INTEREST var rate = 1 + (parseFloat(this.afr)/100); console.log ("Rate is: " + rate); var term = parseInt(this.term); var entry = 1/rate; console.log ("Term is: " + this.term + " this rate is: " + entry); var incomeInterest = Math.pow(entry, term); console.log("Income interest is: " + incomeInterest); console.log("Fair Market Value of Property is: " + this.propertyFMV); //Adjust for mortality //Mx factor for current age var currentMX = mortality_factors[this.age]; console.log("Current mx = " + currentMX); //minus mx factor for age at end of term var mfa = parseInt(this.age) + term; var futureMX = mortality_factors[mfa]; console.log("MFA is " + mfa + " Future mx = " + futureMX); //mortality adjustment var mortAdj = futureMX/currentMX; //remainder value var remainderValue = ((mortAdj * incomeInterest) * this.propertyFMV).toFixed(2); console.log("Remainder Value is: " + remainderValue); var retainedValue = (this.propertyFMV -remainderValue).toFixed(2); ///determine life expectancy var gender_main = $('#gender_main').dropdown('get value'); //1 for male; 0 for female console.log("Gender is: " + gender_main);//for debugging only var LE; if (gender_main == 1) { LE = male_life_exectancies[this.age]; } else { LE = female_life_expectancies[this.age]; } ///DETERMINE AMOUNT GIFTED TAX-FREE TO BENEFICIARIES IF SUCCESSFUL // FIRST DETERMINE VALUE AT END OF TERM var finalFMV = this.propertyFMV; var annualAppreciation = (parseFloat($('#estimatedAnnualAppreciation').val())/100); for (var x = 0; x< this.term; x++) { finalFMV += finalFMV * annualAppreciation; //multiplied by annual appreciation } finalFMV = finalFMV.toFixed(2); var finalValueTransfer = (finalFMV - remainderValue).toFixed(2); var firstName = $('#First_Name').val(); //document.getElementsByName("First_Name").value; var lastName = $('#Last_Name').val(); //document.getElementsByName("Last_Name").value; var secondMsg = "Life expectancy at start of QPRT using SSA data: " + LE + " years."; var thirdMsg = "Probability of surviving QPRT term using IRS tables is: " + (100* mortAdj).toFixed(4) + "%"; var giftTaxAmount = (new Intl.NumberFormat().format(remainderValue *0.40)); var finalTable; finalTable = `<table class="ui compact table"> <thead> <tr> <th>Results of Calculation</th> </tr> </thead> <tbody> <tr> <td>` + "Prepared for: " + firstName + " " + lastName + " " + "on " + new Date() + `</td> </tr> <tr> <td>` + "Value of residence is: $" + (new Intl.NumberFormat().format(this.propertyFMV)) + `</td> </tr>` + `<tr> <td>` + "Term of QPRT is: " + this.term + " years." + `</td> </tr> ` + `<tr> <td>` + "Value of Gift of Remainder is: $" + (new Intl.NumberFormat().format(remainderValue)) + `</td> </tr> <tr> <td>` + secondMsg + `</td> </tr>`+ `<tr> <td>` + thirdMsg + `</td> </tr> ` + `<tr> <td>` + "Value of Retained Term of Use is: $" + (new Intl.NumberFormat().format(retainedValue)) + `</td> </tr> ` + `<tr> <td>` + "Section 7520 Rate used was: " + this.afr + "%" + `</td> </tr> ` + `<tr> <td>` + "Final Property Value = $"+ (new Intl.NumberFormat().format(finalFMV)) + " less initial gift amount of $" + (new Intl.NumberFormat().format(remainderValue))+" equals $" + (new Intl.NumberFormat().format(finalValueTransfer)) + " amount transferred without gift tax or use of gift/estate exemption." + `</td> </tr> ` + `<tr> <td>` + "Gift tax payable if no gift/estate tax exemption available is: $" + giftTaxAmount + `</td> </tr> ` + `</tbody> </table>`; window.data = [remainderValue, retainedValue]; window.dataForEmail = "Prepared for: " + firstName + " " + lastName + " " + "on " + new Date() +"\n"+"Value of residence is: $" + (new Intl.NumberFormat().format(this.propertyFMV)) + "\n"+ "Term of QPRT is: " + this.term + " years." + "\n"+ "Value of Gift of Remainder is: $" + (new Intl.NumberFormat().format(remainderValue))+ "\n"+secondMsg+ "\n"+thirdMsg + "Value of Retained Term of Use is: $" + (new Intl.NumberFormat().format(retainedValue)) +"\n"+ "Section 7520 Rate used was: " + this.afr + "%" + "Final Property Value = $"+ (new Intl.NumberFormat().format(finalFMV)) + " less initial gift amount of $" + (new Intl.NumberFormat().format(remainderValue))+" equals $" + (new Intl.NumberFormat().format(finalValueTransfer)) + " amount transferred without gift tax or use of gift/estate exemption." + "\n"+ "Gift tax payable if no gift/estate tax exemption available is: $" + giftTaxAmount; ////DISPLAY RESULTS OF QUERY////////////////// //var firstMsg = finalTable + "<br>Prepared for: " + firstName + " " + lastName + " " + "on " + new Date(); // firstMsg += "<br>Value of residence is: $" + (new Intl.NumberFormat().format(this.propertyFMV)) + "<br> Term of QPRT is: " + this.term + " years."; document.getElementById("text_output1").innerHTML = finalTable;// + "<br>Value of Gift of Remainder is: $" + (new Intl.NumberFormat().format(remainderValue)); //var secondMsg = "Life expectancy at start of QPRT using SSA data: " + LE + " years."+"<br>Probability of surviving QPRT term using IRS tables is: " + (100* mortAdj).toFixed(4) + "%"; //document.getElementById("text_output2").innerHTML = secondMsg + "<br>Value of Retained Term of Use is: $" + (new Intl.NumberFormat().format(retainedValue)); // document.getElementById("text_output3").innerHTML = "Section 7520 Rate used was: " + this.afr + "%"; //document.getElementById("text_output4").innerHTML = "Final Property Value = $"+ (new Intl.NumberFormat().format(finalFMV)) + " less initial gift amount of $" + (new Intl.NumberFormat().format(remainderValue))+" equals $" + (new Intl.NumberFormat().format(finalValueTransfer)) + " amount transferred without gift tax or use of gift/estate exemption." + "<br>"; document.getElementById("success_button").style.visibility ="visible"; document.getElementById("success_label").innerHTML = (100* mortAdj).toFixed(4) + "%"; document.getElementById("pieChart").style.visibility="visible"; this.CreateChart(); } CreateChart() { new Chart(document.getElementById("pieChart"), { type: 'pie', data: { labels: ["Gift Amount", "Value of Retained Interest"], datasets: [{ label: "Critical Data", backgroundColor: ["#3e95cd", "#8e5ea2"], data: window.data }] }, options: { title: { display: true, text: 'QPRT Data Points' }, tooltips:{ } } }); //var canvas = document.getElementById("lineChart"); //var ctx = canvas.getContext('2d'); //var chartType = 'line'; //NOT USED WHEN SET UP CHARTYPE AS LINE IN CONFIG //window.myBarChart=""; // Global Options: //Chart.defaults.global.defaultFontColor = 'grey'; //Chart.defaults.global.defaultFontSize = 16; //Chart.defaults.global.legend.display = false; //window.myBarChart = new Chart(ctx, config); } //END CREATE CHART FUNCTION float2dollar(value){ return "U$ "+(value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); } }
JavaScript
class Loader { constructor({ onLoad }) { this._onLoad = onLoad; this.load = this.load.bind(this); this._contents = []; } load(contents) { this._contents = contents; this._onLoad(); } get contents() { return this._contents; } }
JavaScript
class Kernel { constructor(io, source) { this.inputs = io.in || io.input || io.inputs || {} this.outputs = io.out || io.output || io.outputs if (!this.outputs || !Object.values(this.outputs).length) { throw new Error(`At least 1 output is required.`) } // // Check for conflicts. for (const output of Object.keys(this.outputs)) { for (const input of Object.keys(this.inputs)) { if (input === output) { throw new Error(`Conflicting input/output variable name: ${input}.`) } } } // // Compare maximum input variabes allowed by the device. let inputCount = Object.values(this.inputs).length if (inputCount > device.maxTextureUnits) { throw new Error(`Maximum number of inputs exceeded. Allowed: ${device.maxTextureUnits}, given: ${inputCount}.`) } // // Split the task in multiple programs based on the maximum number of outputs. const maxOutputs = device.maxColorAttachments const outputNames = Object.keys(this.outputs) const outputGroupCount = Math.ceil(outputNames.length / maxOutputs) let outputDescriptors = [] let groupStartIndex = 0 for (let a = 0; a < outputGroupCount; a++) { let descriptors = {} for (const [i, name] of outputNames.entries()) { const { outputType, precision } = this.outputs[name].formatInfo descriptors[name] = { outputType, precision } if (i >= groupStartIndex && i < groupStartIndex + maxOutputs) { descriptors[name].location = i - groupStartIndex } } outputDescriptors.push(descriptors) groupStartIndex += maxOutputs } // Create the set of programs. this.steps = new Set(outputDescriptors.map((descriptors) => { const shaderSource = prepareFragmentShader(this.inputs, descriptors, source) let program = new Program(shaderSource) let out = [] for (const [name, descriptor] of Object.entries(descriptors)) { if (descriptor.location !== undefined) { out.push(name) } } return { out, program } })) } delete() { this.steps.forEach(step => step.program.delete()) this.steps.clear() delete this.inputs delete this.outputs delete this.steps } exec(uniforms = {}) { // Check dimensions. let size = [] for (const output of Object.values(this.outputs)) { const dimensions = [...output.dimensions] if (!size.length) { size = dimensions } else if (size[0] != dimensions[0] || size[1] != dimensions[1]) { throw new Error('Outputs require consistent sizes.') } } // // Prepare Framebuffer. let fbo = gl.createFramebuffer() gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) // // Run every step. for (const step of this.steps) { // Output textures. for (const [index, name] of step.out.entries()) { const texture = this.outputs[name]._getWritable(true) gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + index, gl.TEXTURE_2D, texture.id, 0) } const { program } = step gl.useProgram(program.id) gl.viewport(0, 0, size[0], size[1]) // Built-in uniforms. program.setUniform('bl_Size', ...size) // User uniforms. for (const [uniform, value] of Object.entries(uniforms)) { program.setUniform(uniform, value) } // Input textures. for (const [index, name] of Object.keys(this.inputs).entries()) { gl.activeTexture(gl.TEXTURE0 + index) const texture = this.inputs[name]._getReadable(true) gl.bindTexture(gl.TEXTURE_2D, texture.id) program.setUniform(name, index) } gl.drawBuffers(step.out.map((_, i) => gl.COLOR_ATTACHMENT0 + i)) gl.drawArrays(gl.TRIANGLES, 0, 3) // Unpacking time. But only for `Buffer`s. for (const [index, name] of step.out.entries()) { const buffer = this.outputs[name] if (buffer instanceof Buffer) { const { bytes, format, type } = buffer.formatInfo gl.readBuffer(gl.COLOR_ATTACHMENT0 + index) gl.readPixels(0, 0, size[0], size[1], gl[format], gl[type], buffer.data, 0) } } gl.bindTexture(gl.TEXTURE_2D, null) } // Clean-up all resources. const allBuffers = new Set([...Object.values(this.inputs), ...Object.values(this.outputs)]) for (const buffer of allBuffers) { buffer._finish() } gl.bindFramebuffer(gl.FRAMEBUFFER, null) gl.deleteFramebuffer(fbo) } }
JavaScript
class ConferencePeerConnectionChannel extends EventDispatcher { // eslint-disable-next-line require-jsdoc constructor(config, signaling) { super(); this.pc = null; this._config = config; this._videoCodecs = undefined; this._options = null; this._videoCodecs = undefined; this._signaling = signaling; this._internalId = null; // It's publication ID or subscription ID. this._pendingCandidates = []; this._subscribePromises = new Map(); // internalId => { resolve, reject } this._publishPromises = new Map(); // internalId => { resolve, reject } this._publications = new Map(); // PublicationId => Publication this._subscriptions = new Map(); // SubscriptionId => Subscription this._publishTransceivers = new Map(); // internalId => { id, transceivers: [Transceiver] } this._subscribeTransceivers = new Map(); // internalId => { id, transceivers: [Transceiver] } this._reverseIdMap = new Map(); // PublicationId || SubscriptionId => internalId // Timer for PeerConnection disconnected. Will stop connection after timer. this._disconnectTimer = null; this._ended = false; // Channel ID assigned by conference this._id = undefined; // Used to create internal ID for publication/subscription this._internalCount = 0; this._sdpPromise = Promise.resolve(); this._sdpResolverMap = new Map(); // internalId => {finish, resolve, reject} this._sdpResolvers = []; // [{finish, resolve, reject}] this._sdpResolveNum = 0; this._remoteMediaStreams = new Map(); // Key is subscription ID, value is MediaStream. } /** * @function onMessage * @desc Received a message from conference portal. Defined in client-server * protocol. * @param {string} notification Notification type. * @param {object} message Message received. * @private */ onMessage(notification, message) { switch (notification) { case 'progress': if (message.status === 'soac') { this._sdpHandler(message.data); } else if (message.status === 'ready') { this._readyHandler(message.sessionId); } else if (message.status === 'error') { this._errorHandler(message.sessionId, message.data); } break; case 'stream': this._onStreamEvent(message); break; default: Logger.warning('Unknown notification from MCU.'); } } async publishWithTransceivers(stream, transceivers) { for (const t of transceivers) { if (t.direction !== 'sendonly') { return Promise.reject( 'RTCRtpTransceiver\'s direction must be sendonly.'); } if (!stream.stream.getTracks().includes(t.sender.track)) { return Promise.reject( 'The track associated with RTCRtpSender is not included in ' + 'stream.'); } if (transceivers.length > 2) { // Not supported by server. return Promise.reject( 'At most one transceiver for audio and one transceiver for video ' + 'are accepted.'); } const transceiverDescription = transceivers.map((t) => { const kind = t.sender.track.kind; return { type: kind, transceiver: t, source: stream.source[kind], option: {}, }; }); const internalId = this._createInternalId(); await this._chainSdpPromise(internalId); // Copied from publish method. this._publishTransceivers.set(internalId, transceiverDescription); const offer=await this.pc.createOffer(); await this.pc.setLocalDescription(offer); const trackOptions = transceivers.map((t) => { const kind = t.sender.track.kind; return { type: kind, source: stream.source[kind], mid: t.mid, }; }); const publicationId = await this._signaling.sendSignalingMessage('publish', { media: {tracks: trackOptions}, attributes: stream.attributes, transport: {id: this._id, type: 'webrtc'}, }).id; this._publishTransceivers.get(internalId).id = publicationId; this._reverseIdMap.set(publicationId, internalId); await this._signaling.sendSignalingMessage( 'soac', {id: this._id, signaling: offer}); return new Promise((resolve, reject) => { this._publishPromises.set(internalId, { resolve: resolve, reject: reject, }); }); } } async publish(stream, options, videoCodecs) { if (this._ended) { return Promise.reject('Connection closed'); } if (Array.isArray(options)) { // The second argument is an array of RTCRtpTransceivers. return this.publishWithTransceivers(stream, options); } if (options === undefined) { options = { audio: !!stream.mediaStream.getAudioTracks().length, video: !!stream.mediaStream.getVideoTracks().length, }; } if (typeof options !== 'object') { return Promise.reject(new TypeError('Options should be an object.')); } if ((this._isRtpEncodingParameters(options.audio) && this._isOwtEncodingParameters(options.video)) || (this._isOwtEncodingParameters(options.audio) && this._isRtpEncodingParameters(options.video))) { return Promise.reject(new ConferenceError( 'Mixing RTCRtpEncodingParameters and ' + 'AudioEncodingParameters/VideoEncodingParameters is not allowed.')); } if (options.audio === undefined) { options.audio = !!stream.mediaStream.getAudioTracks().length; } if (options.video === undefined) { options.video = !!stream.mediaStream.getVideoTracks().length; } if ((!!options.audio && !stream.mediaStream.getAudioTracks().length) || (!!options.video && !stream.mediaStream.getVideoTracks().length)) { return Promise.reject(new ConferenceError( 'options.audio/video is inconsistent with tracks presented in the ' + 'MediaStream.', )); } if ((options.audio === false || options.audio === null) && (options.video === false || options.video === null)) { return Promise.reject(new ConferenceError( 'Cannot publish a stream without audio and video.')); } if (typeof options.audio === 'object') { if (!Array.isArray(options.audio)) { return Promise.reject(new TypeError( 'options.audio should be a boolean or an array.')); } for (const parameters of options.audio) { if (!parameters.codec || typeof parameters.codec.name !== 'string' || ( parameters.maxBitrate !== undefined && typeof parameters.maxBitrate !== 'number')) { return Promise.reject(new TypeError( 'options.audio has incorrect parameters.')); } } } if (typeof options.video === 'object' && !Array.isArray(options.video)) { return Promise.reject(new TypeError( 'options.video should be a boolean or an array.')); } if (this._isOwtEncodingParameters(options.video)) { for (const parameters of options.video) { if (!parameters.codec || typeof parameters.codec.name !== 'string' || ( parameters.maxBitrate !== undefined && typeof parameters .maxBitrate !== 'number') || (parameters.codec.profile !== undefined && typeof parameters.codec.profile !== 'string')) { return Promise.reject(new TypeError( 'options.video has incorrect parameters.')); } } } const mediaOptions = {}; this._createPeerConnection(); if (stream.mediaStream.getAudioTracks().length > 0 && options.audio !== false && options.audio !== null) { if (stream.mediaStream.getAudioTracks().length > 1) { Logger.warning( 'Publishing a stream with multiple audio tracks is not fully' + ' supported.', ); } if (typeof options.audio !== 'boolean' && typeof options.audio !== 'object') { return Promise.reject(new ConferenceError( 'Type of audio options should be boolean or an object.', )); } mediaOptions.audio = {}; mediaOptions.audio.source = stream.source.audio; } else { mediaOptions.audio = false; } if (stream.mediaStream.getVideoTracks().length > 0 && options.video !== false && options.video !== null) { if (stream.mediaStream.getVideoTracks().length > 1) { Logger.warning( 'Publishing a stream with multiple video tracks is not fully ' + 'supported.', ); } mediaOptions.video = {}; mediaOptions.video.source = stream.source.video; const trackSettings = stream.mediaStream.getVideoTracks()[0] .getSettings(); mediaOptions.video.parameters = { resolution: { width: trackSettings.width, height: trackSettings.height, }, framerate: trackSettings.frameRate, }; } else { mediaOptions.video = false; } const internalId = this._createInternalId(); // Waiting for previous SDP negotiation if needed await this._chainSdpPromise(internalId); const offerOptions = {}; const transceivers = []; if (typeof this.pc.addTransceiver === 'function') { // |direction| seems not working on Safari. if (mediaOptions.audio && stream.mediaStream.getAudioTracks().length > 0) { const transceiverInit = { direction: 'sendonly', streams: [stream.mediaStream], }; if (this._isRtpEncodingParameters(options.audio)) { transceiverInit.sendEncodings = options.audio; } const transceiver = this.pc.addTransceiver( stream.mediaStream.getAudioTracks()[0], transceiverInit); transceivers.push({ type: 'audio', transceiver, source: mediaOptions.audio.source, option: {audio: options.audio}, }); if (Utils.isFirefox()) { // Firefox does not support encodings setting in addTransceiver. const parameters = transceiver.sender.getParameters(); parameters.encodings = transceiverInit.sendEncodings; await transceiver.sender.setParameters(parameters); } } if (mediaOptions.video && stream.mediaStream.getVideoTracks().length > 0) { const transceiverInit = { direction: 'sendonly', streams: [stream.mediaStream], }; if (this._isRtpEncodingParameters(options.video)) { transceiverInit.sendEncodings = options.video; this._videoCodecs = videoCodecs; } const transceiver = this.pc.addTransceiver( stream.mediaStream.getVideoTracks()[0], transceiverInit); transceivers.push({ type: 'video', transceiver, source: mediaOptions.video.source, option: {video: options.video}, }); if (Utils.isFirefox()) { // Firefox does not support encodings setting in addTransceiver. const parameters = transceiver.sender.getParameters(); parameters.encodings = transceiverInit.sendEncodings; await transceiver.sender.setParameters(parameters); } } } else { // Should not reach here if (mediaOptions.audio && stream.mediaStream.getAudioTracks().length > 0) { for (const track of stream.mediaStream.getAudioTracks()) { this.pc.addTrack(track, stream.mediaStream); } } if (mediaOptions.video && stream.mediaStream.getVideoTracks().length > 0) { for (const track of stream.mediaStream.getVideoTracks()) { this.pc.addTrack(track, stream.mediaStream); } } offerOptions.offerToReceiveAudio = false; offerOptions.offerToReceiveVideo = false; } this._publishTransceivers.set(internalId, {transceivers}); let localDesc; this.pc.createOffer(offerOptions).then((desc) => { localDesc = desc; return this.pc.setLocalDescription(desc); }).then(() => { const trackOptions = []; transceivers.forEach(({type, transceiver, source}) => { trackOptions.push({ type, mid: transceiver.mid, source, }); }); return this._signaling.sendSignalingMessage('publish', { media: {tracks: trackOptions}, attributes: stream.attributes, transport: {id: this._id, type: 'webrtc'}, }).catch((e) => { // Send SDP even when failed to get Answer. this._signaling.sendSignalingMessage('soac', { id: this._id, signaling: localDesc, }); throw e; }); }).then((data) => { const publicationId = data.id; const messageEvent = new MessageEvent('id', { message: publicationId, origin: this._remoteId, }); this.dispatchEvent(messageEvent); this._publishTransceivers.get(internalId).id = publicationId; this._reverseIdMap.set(publicationId, internalId); if (this._id && this._id !== data.transportId) { Logger.warning('Server returns conflict ID: ' + data.transportId); } this._id = data.transportId; // Modify local SDP before sending if (options) { transceivers.forEach(({type, transceiver, option}) => { localDesc.sdp = this._setRtpReceiverOptions( localDesc.sdp, option, transceiver.mid); localDesc.sdp = this._setRtpSenderOptions( localDesc.sdp, option, transceiver.mid); }); } this._signaling.sendSignalingMessage('soac', { id: this._id, signaling: localDesc, }); }).catch((e) => { Logger.error('Failed to create offer or set SDP. Message: ' + e.message); if (this._publishTransceivers.get(internalId).id) { this._unpublish(internalId); this._rejectPromise(e); this._fireEndedEventOnPublicationOrSubscription(); } else { this._unpublish(internalId); } }); return new Promise((resolve, reject) => { this._publishPromises.set(internalId, { resolve: resolve, reject: reject, }); }); } async subscribe(stream, options) { if (this._ended) { return Promise.reject('Connection closed'); } if (options === undefined) { options = { audio: !!stream.settings.audio, video: !!stream.settings.video, }; } if (typeof options !== 'object') { return Promise.reject(new TypeError('Options should be an object.')); } if (options.audio === undefined) { options.audio = !!stream.settings.audio; } if (options.video === undefined) { options.video = !!stream.settings.video; } if ((options.audio !== undefined && typeof options.audio !== 'object' && typeof options.audio !== 'boolean' && options.audio !== null) || ( options.video !== undefined && typeof options.video !== 'object' && typeof options.video !== 'boolean' && options.video !== null)) { return Promise.reject(new TypeError('Invalid options type.')); } if (options.audio && !stream.settings.audio || (options.video && !stream.settings.video)) { return Promise.reject(new ConferenceError( 'options.audio/video cannot be true or an object if there is no ' + 'audio/video track in remote stream.', )); } if (options.audio === false && options.video === false) { return Promise.reject(new ConferenceError( 'Cannot subscribe a stream without audio and video.')); } const mediaOptions = {}; if (options.audio) { if (typeof options.audio === 'object' && Array.isArray(options.audio.codecs)) { if (options.audio.codecs.length === 0) { return Promise.reject(new TypeError( 'Audio codec cannot be an empty array.')); } } mediaOptions.audio = {}; mediaOptions.audio.from = stream.id; } else { mediaOptions.audio = false; } if (options.video) { if (typeof options.video === 'object' && Array.isArray(options.video.codecs)) { if (options.video.codecs.length === 0) { return Promise.reject(new TypeError( 'Video codec cannot be an empty array.')); } } mediaOptions.video = {}; mediaOptions.video.from = stream.id; if (options.video.resolution || options.video.frameRate || (options.video .bitrateMultiplier && options.video.bitrateMultiplier !== 1) || options.video.keyFrameInterval) { mediaOptions.video.parameters = { resolution: options.video.resolution, framerate: options.video.frameRate, bitrate: options.video.bitrateMultiplier ? 'x' + options.video.bitrateMultiplier.toString() : undefined, keyFrameInterval: options.video.keyFrameInterval, }; } if (options.video.rid) { // Use rid matched track ID as from if possible const matchedSetting = stream.settings.video .find((video) => video.rid === options.video.rid); if (matchedSetting && matchedSetting._trackId) { mediaOptions.video.from = matchedSetting._trackId; // Ignore other settings when RID set. delete mediaOptions.video.parameters; } options.video = true; } } else { mediaOptions.video = false; } const internalId = this._createInternalId(); // Waiting for previous SDP negotiation if needed await this._chainSdpPromise(internalId); const offerOptions = {}; const transceivers = []; this._createPeerConnection(); if (typeof this.pc.addTransceiver === 'function') { // |direction| seems not working on Safari. if (mediaOptions.audio) { const transceiver = this.pc.addTransceiver( 'audio', {direction: 'recvonly'}); transceivers.push({ type: 'audio', transceiver, from: mediaOptions.audio.from, option: {audio: options.audio}, }); } if (mediaOptions.video) { const transceiver = this.pc.addTransceiver( 'video', {direction: 'recvonly'}); transceivers.push({ type: 'video', transceiver, from: mediaOptions.video.from, parameters: mediaOptions.video.parameters, option: {video: options.video}, }); } } else { offerOptions.offerToReceiveAudio = !!options.audio; offerOptions.offerToReceiveVideo = !!options.video; } this._subscribeTransceivers.set(internalId, {transceivers}); let localDesc; this.pc.createOffer(offerOptions).then((desc) => { localDesc = desc; return this.pc.setLocalDescription(desc) .catch((errorMessage) => { Logger.error('Set local description failed. Message: ' + JSON.stringify(errorMessage)); throw errorMessage; }); }, function(error) { Logger.error('Create offer failed. Error info: ' + JSON.stringify( error)); throw error; }).then(() => { const trackOptions = []; transceivers.forEach(({type, transceiver, from, parameters, option}) => { trackOptions.push({ type, mid: transceiver.mid, from: from, parameters: parameters, }); }); return this._signaling.sendSignalingMessage('subscribe', { media: {tracks: trackOptions}, transport: {id: this._id, type: 'webrtc'}, }).catch((e) => { // Send SDP even when failed to get Answer. this._signaling.sendSignalingMessage('soac', { id: this._id, signaling: localDesc, }); throw e; }); }).then((data) => { const subscriptionId = data.id; const messageEvent = new MessageEvent('id', { message: subscriptionId, origin: this._remoteId, }); this.dispatchEvent(messageEvent); this._subscribeTransceivers.get(internalId).id = subscriptionId; this._reverseIdMap.set(subscriptionId, internalId); if (this._id && this._id !== data.transportId) { Logger.warning('Server returns conflict ID: ' + data.transportId); } this._id = data.transportId; // Modify local SDP before sending if (options) { transceivers.forEach(({type, transceiver, option}) => { localDesc.sdp = this._setRtpReceiverOptions( localDesc.sdp, option, transceiver.mid); }); } this._signaling.sendSignalingMessage('soac', { id: this._id, signaling: localDesc, }); }).catch((e) => { Logger.error('Failed to create offer or set SDP. Message: ' + e.message); if (this._subscribeTransceivers.get(internalId).id) { this._unsubscribe(internalId); this._rejectPromise(e); this._fireEndedEventOnPublicationOrSubscription(); } else { this._unsubscribe(internalId); } }); return new Promise((resolve, reject) => { this._subscribePromises.set(internalId, { resolve: resolve, reject: reject, }); }); } close() { if (this.pc && this.pc.signalingState !== 'closed') { this.pc.close(); } } _chainSdpPromise(internalId) { const prior = this._sdpPromise; const negotiationTimeout = 10000; this._sdpPromise = prior.then( () => new Promise((resolve, reject) => { const resolver = {finish: false, resolve, reject}; this._sdpResolvers.push(resolver); this._sdpResolverMap.set(internalId, resolver); setTimeout(() => reject('Timeout to get SDP answer'), negotiationTimeout); })); return prior.catch((e)=>{ // }); } _nextSdpPromise() { let ret = false; // Skip the finished sdp promise while (this._sdpResolveNum < this._sdpResolvers.length) { const resolver = this._sdpResolvers[this._sdpResolveNum]; this._sdpResolveNum++; if (!resolver.finish) { resolver.resolve(); resolver.finish = true; ret = true; } } return ret; } _createInternalId() { return this._internalCount++; } _unpublish(internalId) { if (this._publishTransceivers.has(internalId)) { const {id, transceivers} = this._publishTransceivers.get(internalId); if (id) { this._signaling.sendSignalingMessage('unpublish', {id}) .catch((e) => { Logger.warning('MCU returns negative ack for unpublishing, ' + e); }); this._reverseIdMap.delete(id); } // Clean transceiver transceivers.forEach(({transceiver}) => { if (this.pc.signalingState === 'stable') { transceiver.sender.replaceTrack(null); this.pc.removeTrack(transceiver.sender); } }); this._publishTransceivers.delete(internalId); // Fire ended event if (this._publications.has(id)) { const event = new OwtEvent('ended'); this._publications.get(id).dispatchEvent(event); this._publications.delete(id); } else { Logger.warning('Invalid publication to unpublish: ' + id); if (this._publishPromises.has(internalId)) { this._publishPromises.get(internalId).reject( new ConferenceError('Failed to publish')); } } if (this._sdpResolverMap.has(internalId)) { const resolver = this._sdpResolverMap.get(internalId); if (!resolver.finish) { resolver.resolve(); resolver.finish = true; } this._sdpResolverMap.delete(internalId); } // Create offer, set local and remote description } } _unsubscribe(internalId) { if (this._subscribeTransceivers.has(internalId)) { const {id, transceivers} = this._subscribeTransceivers.get(internalId); if (id) { this._signaling.sendSignalingMessage('unsubscribe', {id}) .catch((e) => { Logger.warning( 'MCU returns negative ack for unsubscribing, ' + e); }); } // Clean transceiver transceivers.forEach(({transceiver}) => { transceiver.receiver.track.stop(); }); this._subscribeTransceivers.delete(internalId); // Fire ended event if (this._subscriptions.has(id)) { const event = new OwtEvent('ended'); this._subscriptions.get(id).dispatchEvent(event); this._subscriptions.delete(id); } else { Logger.warning('Invalid subscription to unsubscribe: ' + id); if (this._subscribePromises.has(internalId)) { this._subscribePromises.get(internalId).reject( new ConferenceError('Failed to subscribe')); } } if (this._sdpResolverMap.has(internalId)) { const resolver = this._sdpResolverMap.get(internalId); if (!resolver.finish) { resolver.resolve(); resolver.finish = true; } this._sdpResolverMap.delete(internalId); } // Disable media in remote SDP // Set remoteDescription and set localDescription } } _muteOrUnmute(sessionId, isMute, isPub, trackKind) { const eventName = isPub ? 'stream-control' : 'subscription-control'; const operation = isMute ? 'pause' : 'play'; return this._signaling.sendSignalingMessage(eventName, { id: sessionId, operation: operation, data: trackKind, }).then(() => { if (!isPub) { const muteEventName = isMute ? 'mute' : 'unmute'; this._subscriptions.get(sessionId).dispatchEvent( new MuteEvent(muteEventName, {kind: trackKind})); } }); } _applyOptions(sessionId, options) { if (typeof options !== 'object' || typeof options.video !== 'object') { return Promise.reject(new ConferenceError( 'Options should be an object.')); } const videoOptions = {}; videoOptions.resolution = options.video.resolution; videoOptions.framerate = options.video.frameRate; videoOptions.bitrate = options.video.bitrateMultiplier ? 'x' + options.video .bitrateMultiplier .toString() : undefined; videoOptions.keyFrameInterval = options.video.keyFrameInterval; return this._signaling.sendSignalingMessage('subscription-control', { id: sessionId, operation: 'update', data: { video: {parameters: videoOptions}, }, }).then(); } _onRemoteStreamAdded(event) { Logger.debug('Remote stream added.'); for (const [internalId, sub] of this._subscribeTransceivers) { if (sub.transceivers.find((t) => t.transceiver === event.transceiver)) { if (this._subscriptions.has(sub.id)) { const subscription = this._subscriptions.get(sub.id); subscription.stream = event.streams[0]; if (this._subscribePromises.has(internalId)) { this._subscribePromises.get(internalId).resolve(subscription); this._subscribePromises.delete(internalId); } } else { this._remoteMediaStreams.set(sub.id, event.streams[0]); } return; } } // This is not expected path. However, this is going to happen on Safari // because it does not support setting direction of transceiver. Logger.warning('Received remote stream without subscription.'); } _onLocalIceCandidate(event) { if (event.candidate) { if (this.pc.signalingState !== 'stable') { this._pendingCandidates.push(event.candidate); } else { this._sendCandidate(event.candidate); } } else { Logger.debug('Empty candidate.'); } } _fireEndedEventOnPublicationOrSubscription() { if (this._ended) { return; } this._ended = true; const event = new OwtEvent('ended'); for (const [/* id */, publication] of this._publications) { publication.dispatchEvent(event); publication.stop(); } for (const [/* id */, subscription] of this._subscriptions) { subscription.dispatchEvent(event); subscription.stop(); } this.dispatchEvent(event); this.close(); } _rejectPromise(error) { if (!error) { error = new ConferenceError('Connection failed or closed.'); } if (this.pc && this.pc.iceConnectionState !== 'closed') { this.pc.close(); } // Rejecting all corresponding promises if publishing and subscribing is ongoing. for (const [/* id */, promise] of this._publishPromises) { promise.reject(error); } this._publishPromises.clear(); for (const [/* id */, promise] of this._subscribePromises) { promise.reject(error); } this._subscribePromises.clear(); } _onIceConnectionStateChange(event) { if (!event || !event.currentTarget) { return; } Logger.debug('ICE connection state changed to ' + event.currentTarget.iceConnectionState); if (event.currentTarget.iceConnectionState === 'closed' || event.currentTarget.iceConnectionState === 'failed') { if (event.currentTarget.iceConnectionState === 'failed') { this._handleError('connection failed.'); } else { // Fire ended event if publication or subscription exists. this._fireEndedEventOnPublicationOrSubscription(); } } } _onConnectionStateChange(event) { if (this.pc.connectionState === 'closed' || this.pc.connectionState === 'failed') { if (this.pc.connectionState === 'failed') { this._handleError('connection failed.'); } else { // Fire ended event if publication or subscription exists. this._fireEndedEventOnPublicationOrSubscription(); } } } _sendCandidate(candidate) { this._signaling.sendSignalingMessage('soac', { id: this._id, signaling: { type: 'candidate', candidate: { candidate: 'a=' + candidate.candidate, sdpMid: candidate.sdpMid, sdpMLineIndex: candidate.sdpMLineIndex, }, }, }); } _createPeerConnection() { if (this.pc) { return; } const pcConfiguration = this._config.rtcConfiguration || {}; if (Utils.isChrome()) { pcConfiguration.bundlePolicy = 'max-bundle'; } this.pc = new RTCPeerConnection(pcConfiguration); this.pc.onicecandidate = (event) => { this._onLocalIceCandidate.apply(this, [event]); }; this.pc.ontrack = (event) => { this._onRemoteStreamAdded.apply(this, [event]); }; this.pc.oniceconnectionstatechange = (event) => { this._onIceConnectionStateChange.apply(this, [event]); }; this.pc.onconnectionstatechange = (event) => { this._onConnectionStateChange.apply(this, [event]); }; } _getStats() { if (this.pc) { return this.pc.getStats(); } else { return Promise.reject(new ConferenceError( 'PeerConnection is not available.')); } } _readyHandler(sessionId) { const internalId = this._reverseIdMap.get(sessionId); if (this._subscribePromises.has(internalId)) { const mediaStream = this._remoteMediaStreams.get(sessionId); const transportSettings = new TransportSettings(TransportType.WEBRTC, this._id); transportSettings.rtpTransceivers = this._subscribeTransceivers.get(internalId).transceivers; const subscription = new Subscription( sessionId, mediaStream, transportSettings, () => { this._unsubscribe(internalId); }, () => this._getStats(), (trackKind) => this._muteOrUnmute(sessionId, true, false, trackKind), (trackKind) => this._muteOrUnmute(sessionId, false, false, trackKind), (options) => this._applyOptions(sessionId, options)); this._subscriptions.set(sessionId, subscription); // Resolve subscription if mediaStream is ready. if (this._subscriptions.get(sessionId).stream) { this._subscribePromises.get(internalId).resolve(subscription); this._subscribePromises.delete(internalId); } } else if (this._publishPromises.has(internalId)) { const transportSettings = new TransportSettings(TransportType.WEBRTC, this._id); transportSettings.transceivers = this._publishTransceivers.get(internalId).transceivers; const publication = new Publication( sessionId, transportSettings, () => { this._unpublish(internalId); return Promise.resolve(); }, () => this._getStats(), (trackKind) => this._muteOrUnmute(sessionId, true, true, trackKind), (trackKind) => this._muteOrUnmute(sessionId, false, true, trackKind)); this._publications.set(sessionId, publication); this._publishPromises.get(internalId).resolve(publication); // Do not fire publication's ended event when associated stream is ended. // It may still sending silence or black frames. // Refer to https://w3c.github.io/webrtc-pc/#rtcrtpsender-interface. } else if (!sessionId) { // Channel ready } } _sdpHandler(sdp) { if (sdp.type === 'answer') { this.pc.setRemoteDescription(sdp).then(() => { if (this._pendingCandidates.length > 0) { for (const candidate of this._pendingCandidates) { this._sendCandidate(candidate); } } }, (error) => { Logger.error('Set remote description failed: ' + error); this._rejectPromise(error); this._fireEndedEventOnPublicationOrSubscription(); }).then(() => { if (!this._nextSdpPromise()) { Logger.warning('Unexpected SDP promise state'); } }); } } _errorHandler(sessionId, errorMessage) { if (!sessionId) { // Transport error return this._handleError(errorMessage); } // Fire error event on publication or subscription const errorEvent = new ErrorEvent('error', { error: new ConferenceError(errorMessage), }); if (this._publications.has(sessionId)) { this._publications.get(sessionId).dispatchEvent(errorEvent); } if (this._subscriptions.has(sessionId)) { this._subscriptions.get(sessionId).dispatchEvent(errorEvent); } // Stop publication or subscription const internalId = this._reverseIdMap.get(sessionId); if (this._publishTransceivers.has(internalId)) { this._unpublish(internalId); } if (this._subscribeTransceivers.has(internalId)) { this._unsubscribe(internalId); } } _handleError(errorMessage) { const error = new ConferenceError(errorMessage); if (this._ended) { return; } const errorEvent = new ErrorEvent('error', { error: error, }); for (const [/* id */, publication] of this._publications) { publication.dispatchEvent(errorEvent); } for (const [/* id */, subscription] of this._subscriptions) { subscription.dispatchEvent(errorEvent); } // Fire ended event when error occured this._fireEndedEventOnPublicationOrSubscription(); } _setCodecOrder(sdp, options, mid) { if (options.audio) { if (options.audio.codecs) { const audioCodecNames = Array.from(options.audio.codecs, (codec) => codec.name); sdp = SdpUtils.reorderCodecs(sdp, 'audio', audioCodecNames, mid); } else { const audioCodecNames = Array.from(options.audio, (encodingParameters) => encodingParameters.codec.name); sdp = SdpUtils.reorderCodecs(sdp, 'audio', audioCodecNames, mid); } } if (options.video) { if (options.video.codecs) { const videoCodecNames = Array.from(options.video.codecs, (codec) => codec.name); sdp = SdpUtils.reorderCodecs(sdp, 'video', videoCodecNames, mid); } else { const videoCodecNames = Array.from(options.video, (encodingParameters) => encodingParameters.codec.name); sdp = SdpUtils.reorderCodecs(sdp, 'video', videoCodecNames, mid); } } return sdp; } _setMaxBitrate(sdp, options, mid) { if (typeof options.audio === 'object') { sdp = SdpUtils.setMaxBitrate(sdp, options.audio, mid); } if (typeof options.video === 'object') { sdp = SdpUtils.setMaxBitrate(sdp, options.video, mid); } return sdp; } _setRtpSenderOptions(sdp, options, mid) { // SDP mugling is deprecated, moving to `setParameters`. if (this._isRtpEncodingParameters(options.audio) || this._isRtpEncodingParameters(options.video)) { return sdp; } sdp = this._setMaxBitrate(sdp, options, mid); return sdp; } _setRtpReceiverOptions(sdp, options, mid) { // Add legacy simulcast in SDP for safari. if (this._isRtpEncodingParameters(options.video) && Utils.isSafari()) { if (options.video.length > 1) { sdp = SdpUtils.addLegacySimulcast( sdp, 'video', options.video.length, mid); } } // _videoCodecs is a workaround for setting video codecs. It will be moved to RTCRtpSendParameters. if (this._isRtpEncodingParameters(options.video) && this._videoCodecs) { sdp = SdpUtils.reorderCodecs(sdp, 'video', this._videoCodecs, mid); return sdp; } if (this._isRtpEncodingParameters(options.audio) || this._isRtpEncodingParameters(options.video)) { return sdp; } sdp = this._setCodecOrder(sdp, options, mid); return sdp; } // Handle stream event sent from MCU. Some stream update events sent from // server, more specifically audio.status and video.status events should be // publication event or subscription events. They don't change MediaStream's // status. See // https://github.com/open-webrtc-toolkit/owt-server/blob/master/doc/Client-Portal%20Protocol.md#339-participant-is-notified-on-streams-update-in-room // for more information. _onStreamEvent(message) { const eventTargets = []; if (this._publications.has(message.id)) { eventTargets.push(this._publications.get(message.id)); } for (const subscription of this._subscriptions) { if (message.id === subscription._audioTrackId || message.id === subscription._videoTrackId) { eventTargets.push(subscription); } } if (!eventTargets.length) { return; } let trackKind; if (message.data.field === 'audio.status') { trackKind = TrackKind.AUDIO; } else if (message.data.field === 'video.status') { trackKind = TrackKind.VIDEO; } else { Logger.warning('Invalid data field for stream update info.'); } if (message.data.value === 'active') { eventTargets.forEach((target) => target.dispatchEvent(new MuteEvent('unmute', {kind: trackKind}))); } else if (message.data.value === 'inactive') { eventTargets.forEach((target) => target.dispatchEvent(new MuteEvent('mute', {kind: trackKind}))); } else { Logger.warning('Invalid data value for stream update info.'); } } _isRtpEncodingParameters(obj) { if (!Array.isArray(obj)) { return false; } // Only check the first one. const param = obj[0]; return !!( param.codecPayloadType || param.dtx || param.active || param.ptime || param.maxFramerate || param.scaleResolutionDownBy || param.rid || param.scalabilityMode); } _isOwtEncodingParameters(obj) { if (!Array.isArray(obj)) { return false; } // Only check the first one. const param = obj[0]; return !!param.codec; } }
JavaScript
class Desktop extends React.Component { /** * */ constructor (props) { super(props); this.state={ apps: [], drivers: [], appState: 2, appTimeout: 0, serviceState : { prosceniumEnabled: false, chaperoneEnabled: false, dbEnabled: false, mainEnabled: false, sparkEnabled: false } }; this.setDriverData=this.setDriverData.bind(this); this.getDriverData=this.getDriverData.bind(this); this.getDriverReference=this.getDriverReference.bind(this); this.setAppData=this.setAppData.bind(this); this.getAppData=this.getAppData.bind(this); this.getAppReference=this.getAppReference.bind(this); this.dataTools = new DataTools (); window.appManager = new ApplicationManager (this.setDriverData,this.getDriverData,this.getDriverReference,this.setAppData,this.getAppData,this.getAppReference); /* if (this.state.appManager) { console.log ("Initializing application manager ..."); this.state.appManager.build(); } */ } /** * */ componentDidMount () { console.log ("componentDidMount"); window.appManager.build(); //this.start (); } /** * */ start () { console.log ("start ()"); tId=setInterval (() => { let t=this.state.appTimeout; let s=this.state.appState; t++; let prosceniumEnabled = false; let chaperoneEnabled = false; let dbEnabled = false; let mainEnabled = false; let sparkEnabled = false; if (t>1) { prosceniumEnabled = true; } if (t>2) { chaperoneEnabled = true; } if (t>3) { dbEnabled = true; } if (t>4) { mainEnabled = true; } if (t>5) { sparkEnabled = true; } if (t>7) { s=1; clearInterval (tId); } this.setState ({ appState: s, appTimeout: t, serviceState : { prosceniumEnabled: prosceniumEnabled, chaperoneEnabled: chaperoneEnabled, dbEnabled: dbEnabled, mainEnabled: mainEnabled, sparkEnabled: sparkEnabled } }); },1000); } /** * */ setDriverData (newData, aCallback) { this.setState ({drivers: newData},() => { if(aCallback) { aCallback(); } }); } /** * */ getDriverData () { return (this.dataTools.deepCopy (this.state.drivers)); } /** * */ getDriverReference () { return (this.state.drivers); } /** * */ setAppData (newData, aCallback) { console.log ("setAppData ()"); this.setState ({apps: newData}, () => { if (aCallback) { aCallback (); } }); } /** * */ getAppData () { return (this.dataTools.deepCopy (this.state.apps)); } /** * */ getAppReference () { return (this.state.apps); } /** * */ onLogin () { console.log ("onLogin ()"); this.setState ({appState: 2}); } /** * */ onLogout () { console.log ("onLogin ()"); this.setState ({appState: 1}); } /** * */ render() { if (this.state.appState==0) { return (<ConnectionDialog timeout={7-this.state.appTimeout} state={this.state.serviceState} />); } if (this.state.appState==1) { return (<LoginDialog onLogin={this.onLogin.bind(this)} />); } return (<MainWindow appmanager={window.appManager} apps={this.state.apps} onLogout={this.onLogout.bind(this)} />); } }
JavaScript
class ActorHttpMemento extends bus_http_1.ActorHttp { constructor(args) { super(args); } async test(action) { if (!(action.context && action.context.has(exports.KEY_CONTEXT_DATETIME) && action.context.get(exports.KEY_CONTEXT_DATETIME) instanceof Date)) { throw new Error('This actor only handles request with a set valid datetime.'); } if (action.init && new Headers(action.init.headers || {}).has('accept-datetime')) { throw new Error('The request already has a set datetime.'); } return true; } async run(action) { // Duplicate the ActionHttp to append a datetime header to the request. const init = action.init ? Object.assign({}, action.init) : {}; const headers = init.headers = new Headers(init.headers || {}); if (action.context && action.context.has(exports.KEY_CONTEXT_DATETIME)) { headers.append('accept-datetime', action.context.get(exports.KEY_CONTEXT_DATETIME).toUTCString()); } const httpAction = { context: action.context, input: action.input, init }; // Execute the request and follow the timegate in the response (if any). const result = await this.mediatorHttp.mediate(httpAction); // Did we ask for a time-negotiated response, but haven't received one? if (headers.has('accept-datetime') && result.headers && !result.headers.has('memento-datetime')) { // The links might have a timegate that can help us const links = result.headers.has('link') && parseLink(result.headers.get('link')); if (links && links.timegate) { result.body.cancel(); // Respond with a time-negotiated response from the timegate instead const followLink = { context: action.context, input: links.timegate.url, init }; return this.mediatorHttp.mediate(followLink); } } return result; } }
JavaScript
class WeaponEmbed extends BaseEmbed { /** * @param {Genesis} bot - An instance of Genesisad * @param {Enhancement} weapon - The enhancement to send info on */ constructor(bot, weapon) { super(); if (weapon && typeof weapon !== 'undefined') { this.title = weapon.name; this.url = weapon.wikiaUrl || ''; this.thumbnail = { url: weapon.wikiaThumbnail || '' }; this.description = `${weapon.type} ${`• MR ${weapon.masteryReq}`}`; this.color = weapon.color || 0x7C0A02; this.fields = []; if (weapon.color) { this.color = weapon.color; } if (weapon.primary) { this.fields.push({ name: 'Primary Fire', value: `**Trigger:** ${weapon.primary.trigger}\n` + `**Projectile:** ${weapon.primary.projectile}\n` + `**Rate:** ${weapon.primary.rate} ammo\\s\n` + `**Flight:**: ${weapon.primary.flight || '-'} m\\s\n` + `**Noise:** ${weapon.primary.noise || '-'}\n` + `**Accuracy:** ${weapon.primary.accuracy || '-'}\n` + `**Reload:** ${weapon.primary.reload || '-'}s\n` + `**Damage:** ${emojify(weapon.primary.damage) || '-'}\n` + `**Impact:** ${emojify(weapon.primary.impact) || '-'}\n` + `**Puncture:** ${emojify(weapon.primary.puncture) || '-'}\n` + `**Slash:** ${emojify(weapon.primary.slash) || '-'}\n` + `**Critical Chance:** ${weapon.primary.crit_chance || '-'}%\n` + `**Critical Multiplier:** ${weapon.primary.crit_mult || '-'}x\n` + `**Status Chance:** ${weapon.primary.status_chance || '-'}%`, inline: true, }); } else { const things = [{ name: 'Rate', value: `${String((weapon.fireRate).toFixed(0) || '-')} unit\\s`, inline: true, }, { name: 'Damage', value: emojify(weapon.damage || '-'), inline: true, }, { name: 'Critical Chance', value: `${((weapon.criticalChance) * 100).toFixed(2) || '-'}%`, inline: true, }, { name: 'Critical Multiplier', value: `${(weapon.criticalMultiplier || 0).toFixed(2) || '-'}x`, inline: true, }, { name: 'Status Chance', value: `${((weapon.procChance || 0) * 100).toFixed(2) || '-'}%`, inline: true, }, { name: 'Polarities', value: emojify(weapon.polarities && weapon.polarities.length ? weapon.polarities.join(' ') : '-'), inline: true, }]; this.fields.push(...things); if (weapon.stancePolarity) { this.fields.push({ name: 'Stance Polarity', value: emojify(weapon.stancePolarity || '-'), inline: true, }); } } if (weapon.secondary) { const values = []; values.push(`**Trigger:** ${weapon.secondary.trigger || '-'}`); values.push(`**Projectile:** ${weapon.secondary.pellet.name}`); values.push(`**Rate:** ${weapon.secondary.rate}`); values.push(`**Flight:**: ${weapon.secondary.flight}m\\s`); values.push(`**Noise:** ${weapon.secondary.noise}`); values.push(`**Accuracy:** ${weapon.secondary.accuracy}`); values.push(`**Reload:** ${weapon.secondary.reload}`); values.push(`**Damage:** ${emojify(weapon.secondary.damage || '-')}`); values.push(`**Impact:** ${weapon.secondary.impact}`); values.push(`**Puncture:** ${weapon.secondary.puncture}`); values.push(`**Slash:** ${weapon.secondary.slash}`); values.push(`**Critical Chance:** ${weapon.secondary.crit_chance}%`); values.push(`**Critical Multiplier:** ${weapon.secondary.crit_mult}x`); values.push(`**Status Chance:** ${weapon.secondary.status_chance}%`); this.fields.push({ name: 'Secondary Fire', value: values.join('\n') || '--', inline: true, }); } if (weapon.noise) { this.fields.push({ name: 'Noise Level', value: String(weapon.noise), inline: true, }); } if (weapon.projectile) { this.fields.push({ name: 'Projectile', value: String(weapon.projectile), inline: true, }); } if (weapon.trigger) { this.fields.push({ name: 'Trigger Type', value: weapon.trigger, inline: true, }); } if (weapon.damageTypes) { this.fields.push({ name: 'IPS Damage Distribution', value: emojify(`impact ${String(weapon.damageTypes.impact || '-')}\npuncture ${String(weapon.damageTypes.puncture || '-')}\nslash ${String(weapon.damageTypes.slash || '-')}`), inline: true, }); } if (weapon.flight) { this.fields.push({ name: 'Flight Speed', value: `${weapon.flight || '0'}m\\s`, inline: true, }); } if (weapon.magazineSize) { this.fields.push({ name: 'Magazine Size', value: String(weapon.magazineSize), inline: true, }); } if (weapon.ammo) { this.fields.push({ name: 'Ammo Max', value: String(weapon.ammo), inline: true, }); } if (weapon.accuracy) { this.fields.push({ name: 'Accuracy', value: String(weapon.accuracy), inline: true, }); } if (weapon.reload) { this.fields.push({ name: 'Reload Speed', value: `${(weapon.reloadTime || 0).toFixed(1) || '-'}s`, inline: true, }); } if (weapon.disposition) { this.fields.push({ name: 'Riven Disposition', value: dispositions[weapon.disposition], inline: true, }); } } else { this.title = 'Invalid Query'; this.color = 0xff6961; this.footer = undefined; } } }
JavaScript
class Model { constructor(data, params) { this.data = data.slice() this.params = params || {} } fit() { throw new Error("Use one of the implementations, not base class.") } append() { throw new Error("Use one of the implementations, not base class.") } forecast() { throw new Error("Use one of the implementations, not base class.") } }
JavaScript
class RegisterServerManager extends events_1.EventEmitter { constructor(options) { super(); this.state = RegisterServerManagerStatus.INACTIVE; this._registration_client = null; this._serverEndpoints = []; this.server = options.server; this._setState(RegisterServerManagerStatus.INACTIVE); this.timeout = g_DefaultRegistrationServerTimeout; this.discoveryServerEndpointUrl = options.discoveryServerEndpointUrl || "opc.tcp://localhost:4840"; (0, node_opcua_assert_1.assert)(typeof this.discoveryServerEndpointUrl === "string"); this._registrationTimerId = null; } dispose() { this.server = null; debugLog("RegisterServerManager#dispose", this.state.toString()); (0, node_opcua_assert_1.assert)(this.state === RegisterServerManagerStatus.INACTIVE); (0, node_opcua_assert_1.assert)(this._registrationTimerId === null, "stop has not been called"); this.removeAllListeners(); } _emitEvent(eventName) { setImmediate(() => { this.emit(eventName); }); } _setState(status) { const previousState = this.state || RegisterServerManagerStatus.INACTIVE; debugLog("RegisterServerManager#setState : ", RegisterServerManagerStatus[previousState], " => ", RegisterServerManagerStatus[status]); this.state = status; } start(callback) { debugLog("RegisterServerManager#start"); if (this.state !== RegisterServerManagerStatus.INACTIVE) { return callback(new Error("RegisterServer process already started")); // already started } this.discoveryServerEndpointUrl = (0, node_opcua_hostname_1.resolveFullyQualifiedDomainName)(this.discoveryServerEndpointUrl); // perform initial registration + automatic renewal this._establish_initial_connection((err) => { if (err) { debugLog("RegisterServerManager#start => _establish_initial_connection has failed"); return callback(err); } if (this.state !== RegisterServerManagerStatus.INITIALIZING) { debugLog("RegisterServerManager#start => _establish_initial_connection has failed"); return callback(); } this._registerServer(true, (err1) => { if (this.state !== RegisterServerManagerStatus.REGISTERING) { debugLog("RegisterServerManager#start )=> Registration has been cancelled"); return callback(new Error("Registration has been cancelled")); } if (err1) { warningLog("RegisterServerManager#start - registering server has failed ! \n" + "please check that your server certificate is accepted by the LDS"); this._setState(RegisterServerManagerStatus.INACTIVE); this._emitEvent("serverRegistrationFailure"); } else { this._emitEvent("serverRegistered"); this._setState(RegisterServerManagerStatus.WAITING); this._trigger_next(); } callback(); }); }); } _establish_initial_connection(outer_callback) { var _a; /* istanbul ignore next */ if (!this.server) { throw new Error("Internal Error"); } debugLog("RegisterServerManager#_establish_initial_connection"); (0, node_opcua_assert_1.assert)(!this._registration_client); (0, node_opcua_assert_1.assert)(typeof this.discoveryServerEndpointUrl === "string"); (0, node_opcua_assert_1.assert)(this.state === RegisterServerManagerStatus.INACTIVE); this._setState(RegisterServerManagerStatus.INITIALIZING); this.selectedEndpoint = undefined; const applicationName = ((_a = (0, node_opcua_client_1.coerceLocalizedText)(this.server.serverInfo.applicationName)) === null || _a === void 0 ? void 0 : _a.text) || undefined; // Retry Strategy must be set this.server.serverCertificateManager.referenceCounter++; const registrationClient = node_opcua_client_1.OPCUAClientBase.create({ clientName: this.server.serverInfo.applicationUri, applicationName, applicationUri: this.server.serverInfo.applicationUri, connectionStrategy: infinite_connectivity_strategy, clientCertificateManager: this.server.serverCertificateManager, certificateFile: this.server.certificateFile, privateKeyFile: this.server.privateKeyFile }); this._registration_client = registrationClient; registrationClient.on("backoff", (nbRetry, delay) => { debugLog("RegisterServerManager - received backoff"); warningLog(chalk.bgWhite.cyan("contacting discovery server backoff "), this.discoveryServerEndpointUrl, " attempt #", nbRetry, " retrying in ", delay / 1000.0, " seconds"); this._emitEvent("serverRegistrationPending"); }); async.series([ // do_initial_connection_with_discovery_server (callback) => { registrationClient.connect(this.discoveryServerEndpointUrl, (err) => { if (err) { debugLog("RegisterServerManager#_establish_initial_connection " + ": initial connection to server has failed"); // xx debugLog(err); } return callback(err); }); }, // getEndpoints_on_discovery_server (callback) => { registrationClient.getEndpoints((err, endpoints) => { if (!err) { const endpoint = findSecureEndpoint(endpoints); if (!endpoint) { throw new Error("Cannot find Secure endpoint"); } if (endpoint.serverCertificate) { (0, node_opcua_assert_1.assert)(endpoint.serverCertificate); this.selectedEndpoint = endpoint; } else { this.selectedEndpoint = undefined; } } else { debugLog("RegisterServerManager#_establish_initial_connection " + ": getEndpointsRequest has failed"); debugLog(err); } callback(err); }); }, // function closing_discovery_server_connection (callback) => { this._serverEndpoints = registrationClient._serverEndpoints; registrationClient.disconnect((err) => { this._registration_client = null; callback(err); }); }, // function wait_a_little_bit (callback) => { setTimeout(callback, 10); } ], (err) => { debugLog("-------------------------------", !!err); if (this.state !== RegisterServerManagerStatus.INITIALIZING) { debugLog("RegisterServerManager#_establish_initial_connection has been interrupted ", RegisterServerManagerStatus[this.state]); this._setState(RegisterServerManagerStatus.INACTIVE); if (this._registration_client) { this._registration_client.disconnect((err2) => { this._registration_client = null; outer_callback(new Error("Initialization has been canceled")); }); } else { outer_callback(new Error("Initialization has been canceled")); } return; } if (err) { this._setState(RegisterServerManagerStatus.INACTIVE); if (this._registration_client) { this._registration_client.disconnect((err1) => { this._registration_client = null; debugLog("#######", !!err1); outer_callback(err); }); return; } } outer_callback(); }); } _trigger_next() { (0, node_opcua_assert_1.assert)(!this._registrationTimerId); (0, node_opcua_assert_1.assert)(this.state === RegisterServerManagerStatus.WAITING); // from spec 1.04 part 4: // The registration process is designed to be platform independent, robust and able to minimize // problems created by configuration errors. For that reason, Servers shall register themselves more // than once. // Under normal conditions, manually launched Servers shall periodically register with the Discovery // Server as long as they are able to receive connections from Clients. If a Server goes offline then it // shall register itself once more and indicate that it is going offline. The registration frequency // should be configurable; however, the maximum is 10 minutes. If an error occurs during registration // (e.g. the Discovery Server is not running) then the Server shall periodically re-attempt registration. // The frequency of these attempts should start at 1 second but gradually increase until the // registration frequency is the same as what it would be if no errors occurred. The recommended // approach would be to double the period of each attempt until reaching the maximum. // When an automatically launched Server (or its install program) registers with the Discovery Server // it shall provide a path to a semaphore file which the Discovery Server can use to determine if the // Server has been uninstalled from the machine. The Discovery Server shall have read access to // the file system that contains the file // install a registration debugLog("RegisterServerManager#_trigger_next " + ": installing timeout to perform registerServer renewal (timeout =", this.timeout, ")"); this._registrationTimerId = setTimeout(() => { if (!this._registrationTimerId) { debugLog("RegisterServerManager => cancelling re registration"); return; } this._registrationTimerId = null; debugLog("RegisterServerManager#_trigger_next : renewing RegisterServer"); this._registerServer(true, (err) => { if (this.state !== RegisterServerManagerStatus.INACTIVE && this.state !== RegisterServerManagerStatus.UNREGISTERING) { debugLog("RegisterServerManager#_trigger_next : renewed !", err); this._setState(RegisterServerManagerStatus.WAITING); this._emitEvent("serverRegistrationRenewed"); this._trigger_next(); } }); }, this.timeout); } stop(callback) { debugLog("RegisterServerManager#stop"); if (this._registrationTimerId) { debugLog("RegisterServerManager#stop :clearing timeout"); clearTimeout(this._registrationTimerId); this._registrationTimerId = null; } this._cancel_pending_client_if_any(() => { debugLog("RegisterServerManager#stop _cancel_pending_client_if_any done ", this.state); if (!this.selectedEndpoint || this.state === RegisterServerManagerStatus.INACTIVE) { this.state = RegisterServerManagerStatus.INACTIVE; (0, node_opcua_assert_1.assert)(this._registrationTimerId === null); return callback(); } this._registerServer(false, () => { this._setState(RegisterServerManagerStatus.INACTIVE); this._emitEvent("serverUnregistered"); callback(); }); }); } /** * @param isOnline * @param outer_callback * @private */ _registerServer(isOnline, outer_callback) { var _a, _b; (0, node_opcua_assert_1.assert)(typeof outer_callback === "function"); debugLog("RegisterServerManager#_registerServer isOnline:", isOnline, "selectedEndpoint: ", (_a = this.selectedEndpoint) === null || _a === void 0 ? void 0 : _a.endpointUrl); (0, node_opcua_assert_1.assert)(this.selectedEndpoint, "must have a selected endpoint => please call _establish_initial_connection"); (0, node_opcua_assert_1.assert)(this.server.serverType !== undefined, " must have a valid server Type"); // construct connection const server = this.server; const selectedEndpoint = this.selectedEndpoint; if (!selectedEndpoint) { warningLog("Warning : cannot register server - no endpoint available"); return outer_callback(new Error("Cannot registerServer")); } server.serverCertificateManager.referenceCounter++; const applicationName = ((_b = (0, node_opcua_client_1.coerceLocalizedText)(server.serverInfo.applicationName)) === null || _b === void 0 ? void 0 : _b.text) || undefined; const theStatus = isOnline ? RegisterServerManagerStatus.REGISTERING : RegisterServerManagerStatus.UNREGISTERING; if (theStatus === this.state) { warningLog(`Warning the server is already in the ${RegisterServerManagerStatus[theStatus]} state`); return outer_callback(); } (0, node_opcua_assert_1.assert)(this.state === RegisterServerManagerStatus.INITIALIZING || this.state === RegisterServerManagerStatus.WAITING); this._setState(theStatus); if (this._registration_client) { warningLog(`Warning there is already a registering/unregistering task taking place: ${RegisterServerManagerStatus[this.state]} state`); } const options = { securityMode: selectedEndpoint.securityMode, securityPolicy: (0, node_opcua_secure_channel_1.coerceSecurityPolicy)(selectedEndpoint.securityPolicyUri), serverCertificate: selectedEndpoint.serverCertificate, clientCertificateManager: server.serverCertificateManager, certificateFile: server.certificateFile, privateKeyFile: server.privateKeyFile, // xx clientName: server.serverInfo.applicationUri!, applicationName, applicationUri: server.serverInfo.applicationUri, connectionStrategy: no_reconnect_connectivity_strategy, clientName: "server client to LDS " + RegisterServerManagerStatus[theStatus] }; const client = node_opcua_client_1.OPCUAClientBase.create(options); const tmp = this._serverEndpoints; client._serverEndpoints = tmp; this._registration_client = client; debugLog(" lds endpoint uri : ", selectedEndpoint.endpointUrl); debugLog(" securityMode : ", node_opcua_secure_channel_1.MessageSecurityMode[selectedEndpoint.securityMode]); debugLog(" securityPolicy : ", selectedEndpoint.securityPolicyUri); async.series([ // establish_connection_with_lds (callback) => { client.connect(selectedEndpoint.endpointUrl, (err) => { debugLog("establish_connection_with_lds => err = ", err); if (err) { debugLog("RegisterServerManager#_registerServer connection to client has failed"); debugLog("RegisterServerManager#_registerServer " + "=> please check that you server certificate is trusted by the LDS"); warningLog("RegisterServer to the LDS has failed during secure connection " + "=> please check that you server certificate is trusted by the LDS.", "\nerr: " + err.message, "\nLDS endpoint :", selectedEndpoint.endpointUrl, "\nsecurity mode :", node_opcua_secure_channel_1.MessageSecurityMode[selectedEndpoint.securityMode], "\nsecurity policy :", (0, node_opcua_secure_channel_1.coerceSecurityPolicy)(selectedEndpoint.securityPolicyUri)); // xx debugLog(options); client.disconnect(() => { this._registration_client = null; debugLog("RegisterServerManager#_registerServer client disconnected"); callback( /* intentionally no error propagation*/); }); } else { callback(); } }); }, (callback) => { if (!this._registration_client) { callback(); return; } sendRegisterServerRequest(this.server, client, isOnline, (err) => { callback( /* intentionally no error propagation*/); }); }, // close_connection_with_lds (callback) => { if (!this._registration_client) { callback(); return; } client.disconnect(callback); } ], (err) => { if (!this._registration_client) { debugLog("RegisterServerManager#_registerServer end (isOnline", isOnline, ") has been interrupted"); outer_callback(); return; } this._registration_client.disconnect(() => { debugLog("RegisterServerManager#_registerServer end (isOnline", isOnline, ")"); this._registration_client = null; outer_callback(err); }); }); } _cancel_pending_client_if_any(callback) { debugLog("RegisterServerManager#_cancel_pending_client_if_any"); if (this._registration_client) { debugLog("RegisterServerManager#_cancel_pending_client_if_any " + "=> wee need to disconnect _registration_client"); this._registration_client.disconnect(() => { this._registration_client = null; this._cancel_pending_client_if_any(callback); }); } else { debugLog("RegisterServerManager#_cancel_pending_client_if_any : done"); callback(); } } }
JavaScript
class CustomListItem extends ListItem { static get metadata() { return metadata; } static get template() { return CustomListItemTemplate; } static get styles() { return [ListItem.styles, customListItemCss]; } _onkeydown(event) { const isTab = isTabNext(event) || isTabPrevious(event); if (!isTab && !this.focused) { return; } super._onkeydown(event); } _onkeyup(event) { const isTab = isTabNext(event) || isTabPrevious(event); if (!isTab && !this.focused) { return; } super._onkeyup(event); } get classes() { const result = super.classes; result.main["ui5-custom-li-root"] = true; return result; } }
JavaScript
class Array2DImpl { constructor(h, v) { this._ = new Array(v).fill(null).map(() => (new Array(h)).fill(null)) } get(x, y) { return this._[y][x] } set(x, y, v) { this._[y][x] = v } asArray() { return this._ } }
JavaScript
class Tile { constructor(charIndex, letter, style = Tile.Style.NORMAL) { this._charIndex = charIndex; this._letter = letter; this._style = style; this._x = TileBoard.indexToX(charIndex); this._y = TileBoard.indexToY(charIndex); } get charIndex() { return this._charIndex; } get letter() { return this._letter; } get x() { return this._x; } get y() { return this._y; } get isShiftedDown() { return this._x % 2 == 0; } get style() { return this._style; } get styleAsNumber() { return Tile.StyleToNumber[this.style]; } toString() { return `[charIndex=${this.charIndex}, letter=${this.letter}, style=${ this.style.toString()}, x=${this.x}, y=${this.y}]`; } static numberToStyle(value) { if (value > Tile.NumberToStyle.length) { throw new Error('Unknown tile style.'); } return Tile.NumberToStyle[value]; } }
JavaScript
class TokenSigner { // Initialise a TokenSigner with an Ably API Key. // // The key has the following format: // // <keyName>:<keySecret> // // The keyName is used as the "kid" value in the header of the Ably JWT // token, and keySecret is used to sign the token using the HS256 algorithm. constructor(ablyKey) { const keyParts = ablyKey.split(':', 2); this.keyName = keyParts[0]; this.keySecret = keyParts[1]; } // Sign a JWT of the given token details using the keySecret and return the // resulting signed Ably JWT token. // // The steps used are specified at https://tools.ietf.org/html/rfc7515#section-3.3 sign(tokenDetails) { const header = { typ: 'JWT', kid: this.keyName, alg: 'HS256', }; const jwt = { 'iat': tokenDetails.issued, 'exp': tokenDetails.expires, 'x-ably-capability': tokenDetails.capapility, 'x-ably-clientId': tokenDetails.clientId, }; const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(jwt))}`; const hmac = crypto.createHmac('sha256', this.keySecret); hmac.update(signingInput); const signature = base64url(hmac.digest()); return `${signingInput}.${signature}`; } }
JavaScript
class Testing { log() { console.log('this is just dummy code as a place holder') } }
JavaScript
class TestHelper { /** * HashBrown.Helpers.BackupHelper test * * @param {String} project * @param {Function} onMessage * * @returns {Promise} */ static testBackupHelper(project, onMessage) { checkParam(project, 'project', String); checkParam(onMessage, 'onMessage', Function); let timestamp; onMessage('Get backups for project "' + project + '"'); return HashBrown.Helpers.BackupHelper.getBackupsForProject(project) .then((backups) => { onMessage('Create backup'); return HashBrown.Helpers.BackupHelper.createBackup(project); }) .then((newTimestamp) => { timestamp = newTimestamp; onMessage('Get path of backup "' + timestamp + '"'); return HashBrown.Helpers.BackupHelper.getBackupPath(project, timestamp); }).then((path) => { onMessage('Restore backup "' + timestamp + '"'); return HashBrown.Helpers.BackupHelper.restoreBackup(project, timestamp); }).then((path) => { onMessage('Delete backup "' + timestamp + '"'); return HashBrown.Helpers.BackupHelper.deleteBackup(project, timestamp); }); } /** * HashBrown.Helpers.ConnectionHelper test * * @param {String} project * @param {String} environment * @param {Function} onMessage * * @returns {Promise} */ static testConnectionHelper(project, environment, onMessage) { checkParam(project, 'project', String); checkParam(environment, 'environment', String); checkParam(onMessage, 'onMessage', Function); onMessage('Create connection') return HashBrown.Helpers.ConnectionHelper.createConnection(project, environment) .then((testConnection) => { onMessage('Get connection by id "' + testConnection.id + '"'); return HashBrown.Helpers.ConnectionHelper.getConnectionById(project, environment, testConnection.id); }) .then((testConnection) => { onMessage('Update connection by id "' + testConnection.id + '"'); return HashBrown.Helpers.ConnectionHelper.setConnectionById(project, environment, testConnection.id, testConnection, false); }) .then((testConnection) => { onMessage('Remove connection by id "' + testConnection.id + '"'); return HashBrown.Helpers.ConnectionHelper.removeConnectionById(project, environment, testConnection.id); }) .then(() => { onMessage('Get all connections'); return HashBrown.Helpers.ConnectionHelper.getAllConnections(project, environment) }); } /** * HashBrown.Helpers.FormHelper test * * @param {String} project * @param {String} environment * @param {Function} onMessage * * @returns {Promise} */ static testFormHelper(project, environment, onMessage) { checkParam(project, 'project', String); checkParam(environment, 'environment', String); checkParam(onMessage, 'onMessage', Function); onMessage('Create form') return HashBrown.Helpers.FormHelper.createForm(project, environment) .then((testForm) => { onMessage('Get form by id "' + testForm.id + '"'); return HashBrown.Helpers.FormHelper.getForm(project, environment, testForm.id); }) .then((testForm) => { onMessage('Update form by id "' + testForm.id + '"'); return HashBrown.Helpers.FormHelper.setForm(project, environment, testForm.id, testForm, false); }) .then((testForm) => { onMessage('Add entry to form "' + testForm.id + '"'); return HashBrown.Helpers.FormHelper.addEntry(project, environment, testForm.id, {}); }) .then((testForm) => { onMessage('Remove form by id "' + testForm.id + '"'); return HashBrown.Helpers.FormHelper.deleteForm(project, environment, testForm.id); }) .then(() => { onMessage('Get all forms'); return HashBrown.Helpers.FormHelper.getAllForms(project, environment) }); } /** * HashBrown.Helpers.ContentHelper test * * @param {String} project * @param {String} environment * @param {User} user * @param {Function} onMessage * * @returns {Promise} */ static testContentHelper(project, environment, user, onMessage) { checkParam(project, 'project', String); checkParam(environment, 'environment', String); checkParam(user, 'user', HashBrown.Models.User); checkParam(onMessage, 'onMessage', Function); onMessage('Create content'); return HashBrown.Helpers.ContentHelper.createContent( project, environment, 'contentBase', null, user ).then((testContent) => { onMessage('Get content by id "' + testContent.id + '"'); return HashBrown.Helpers.ContentHelper.getContentById(project, environment, testContent.id); }) .then((testContent) => { onMessage('Update content by id "' + testContent.id + '"'); return HashBrown.Helpers.ContentHelper.setContentById(project, environment, testContent.id, testContent, user); }) .then((testContent) => { onMessage('Remove content by id "' + testContent.id + '"'); return HashBrown.Helpers.ContentHelper.removeContentById(project, environment, testContent.id); }) .then(() => { onMessage('Get all contents'); return HashBrown.Helpers.ContentHelper.getAllContents(project, environment) }); } /** * HashBrown.Helpers.ProjectHelper test * * @param {Project} testProject * @param {Function} onMessage * * @returns {Promise} */ static testProjectHelper(testProject, onMessage) { checkParam(testProject, 'testProject', HashBrown.Models.Project); checkParam(onMessage, 'onMessage', Function); onMessage('Get project by id "' + testProject.id + '"'); return HashBrown.Helpers.ProjectHelper.getProject(testProject.id) .then(() => { onMessage('Add environment to project "' + testProject.id + '"'); return HashBrown.Helpers.ProjectHelper.addEnvironment(testProject.id, 'testenvironment'); }) .then((testEnvironment) => { onMessage('Remove environment from project "' + testProject.id + '"'); return HashBrown.Helpers.ProjectHelper.deleteEnvironment(testProject.id, testEnvironment); }) .then(() => { onMessage('Get all environments from project "' + testProject.id + '"'); return HashBrown.Helpers.ProjectHelper.getAllEnvironments(testProject.id); }) .then(() => { onMessage('Delete project "' + testProject.id + '"'); return HashBrown.Helpers.ProjectHelper.deleteProject(testProject.id, false); }); } /** * HashBrown.Helpers.SchemaHelper test * * @param {String} project * @param {String} environment * @param {Function} onMessage * * @returns {Promise} */ static testSchemaHelper(project, environment, onMessage) { checkParam(project, 'project', String); checkParam(environment, 'environment', String); checkParam(onMessage, 'onMessage', Function); onMessage('Get native schemas'); return HashBrown.Helpers.SchemaHelper.getNativeSchemas() .then((nativeSchemas) => { let contentBase; for(let i in nativeSchemas) { if(nativeSchemas[i].id === 'contentBase') { contentBase = nativeSchemas[i]; break; } } onMessage('Create schema') return HashBrown.Helpers.SchemaHelper.createSchema( project, environment, contentBase ); }) .then((testSchema) => { onMessage('Get schema by id "' + testSchema.id + '"'); return HashBrown.Helpers.SchemaHelper.getSchemaWithParentFields(project, environment, testSchema.id); }) .then((testSchema) => { onMessage('Update schema by id "' + testSchema.id + '"'); return HashBrown.Helpers.SchemaHelper.setSchemaById(project, environment, testSchema.id, testSchema, false); }) .then((testSchema) => { onMessage('Remove schema by id "' + testSchema.id + '"'); return HashBrown.Helpers.SchemaHelper.removeSchemaById(project, environment, testSchema.id); }) .then(() => { onMessage('Get all schemas'); return HashBrown.Helpers.SchemaHelper.getAllSchemas(project, environment) }); } }
JavaScript
class CastManager extends Observable { constructor(title) { super(); // The last record (Just a help variable for record creation) this.currentRecord = null; // The Audio manager creates audio files audioManager = new AudioManager(); audioManager.addEventListener("audio-recorded", this.onAudioFileRecorded.bind(this)); // These files are stored as records in the Record manager recordManager = new RecordManager(); recordManager.addEventListener("audio-end", event => this.notifyAll(event)); recordManager.addEventListener("audio-start", event => { this.notifyAll(event); }); recordManager.addEventListener("cast-end", event => { this.notifyAll(event); }); this.cast = new Cast(title); } setTitle(title) { this.cast.setTitle(title); } setCastServerID(id) { this.cast.castServerID = id; } setCodeFileID(id) { this.cast.codeFileID = id; } // Starts the record in the audio manager startRecord() { audioManager.record(); } //Stops the record and stores title and time in a new record object stopRecord(event) { this.currentRecord = new Record(event.data.title, event.data.time); audioManager.stopRecord(); } addRecord(record) { recordManager.addRecord(record); let ev = new Event("audio-saved", record); this.notifyAll(ev); } saveRecord(event) { this.currentRecord.title = event.data.title; this.currentRecord.time = event.data.time; recordManager.addRecord(this.currentRecord); let ev = new Event("audio-saved", this.currentRecord); this.notifyAll(ev); } deleteRecord(id) { recordManager.deleteRecord(id); } playRecord(id) { recordManager.playRecord(id); } stopPlayRecord(id) { recordManager.stopRecord(id); } // Adds audio to the current record object and informs the CastController onAudioFileRecorded(event) { if (event.data) { this.currentRecord.setAudio(event.data); let ev = new Event("audio-recorded", this.currentRecord); this.notifyAll(ev); } } // Plays the whole cast playCast() { recordManager.playCast(); } stopCast() { recordManager.stopCast(); } onNextRecord() { recordManager.onNextRecord(); } onPreviousRecord() { recordManager.onPreviousRecord(); } onEntryTitleChanged(data) { recordManager.onEntryTitleChanged(data); } onRecordListChanged(recordIDs) { recordManager.onRecordListChanged(recordIDs); } checkForModal() { let modal; if (audioManager.mediaRecorderIsRecording()) { modal = new Modal("Audio still recording", "There is an audio recording running currently. Stop and save recording?", "Yes, save", "No, discard audio"); modal.addEventListener("onAcceptClicked", () => this.notifyAll(new Event("modal-stop", ""))); modal.addEventListener("onDeclineClicked", () => this.notifyAll(new Event("modal-delete", ""))); } } saveCast(codeHTML) { saveCast(this.cast.getTitle(), codeHTML, this); } onCastDownloaded(cast) { this.cast = cast; this.getAudios(this.cast.records); this.getCodeText(this.cast.codeFileID); } // If the user wants to edit a cast, the id is not undefined async getCast(id) { if (id) { // So we fetch the cast from the DB let cast = await downloadCast(id); this.notifyAll(new Event("cast-downloaded", cast)); } } // Retrieves audio files from the Database, and creates playable Records async getAudios(records) { let audioData = [], recordData = []; for (let record of records) { audioData.push(JSON.parse(record)); } for (let audio of audioData) { let record = new Record(audio.title, audio.time), fileURL = await downloadFile(audio.id), blob; blob = await fetch(fileURL.href).then(r => r.blob()); record.id = audio.id; record.setAudio(URL.createObjectURL(blob)); recordData.push(record); } this.notifyAll(new Event("audio-downloaded", recordData)); } // Retrieves a code file from the DataBase async getCodeText(codeFileID) { let codeFile = await downloadFile(codeFileID), reader = new FileReader(); if (codeFile !== null) { fetch(codeFile.href).then(res => res.blob()).then(blob => { let file = new File([blob], "CodeFile"); reader.readAsText(file); }); } reader.onload = (res) => { let text = res.target.result; this.notifyAll(new Event("codeHTML-downloaded", text)); }; } }
JavaScript
class ImageField extends Field { /** * @type {Object} * @property {String} [src] - Default image path when nothing is selected * @property {number} [fileSize=256Kb] - Maximum file size (Kb) accepted */ static propTypes = Object.assign({}, Field.propTypes, { src: PropTypes.string, fileSize: PropTypes.number, }); /** * @ignore */ static defaultProps = Object.assign({}, Field.defaultProps, { src: '', fileSize: 256, }); /** * @ignore */ constructor(props) { super(props); /** * @ignore */ this.state = Object.assign({}, this.state, { imageData: null, }); } /** * @ignore */ get hasImageClassName() { return this.imageSrc ? 'imageField--hasImage' : ''; } /** * @ignore */ get imageSrc() { const { imageData } = this.state; const { src } = this.props; return imageData || src; } /** * @ignore */ setImage(e) { const file = e.target.files[0]; const maxKb = this.props.fileSize; const maxSize = maxKb * 1024; if (file && file.size > maxSize) { alert(`File cannot be greater than ${maxKb}Kb. Image will be removed.`); e.target.value = null; this.setState({ imageData: null }); return; } this.setImageData(file); } /** * @ignore */ setImageData(file) { if (file) { ImageUtils.getFileData(file) .then((imageData) => { this.setState({ imageData }); this.validate(); }); } } /** * @ignore */ render() { const { id, name, label } = this.props; return ( <div className={`field imageField ${this.hasImageClassName}`}> <div className='field__inputWrapper'> <input className='field__input imageField__input hideAccessible' id={id} name={name} type='file' required={this.props.required} accept='image/*' onBlur={() => this.validate()} onChange={e => this.setImage(e)} /> <label className='button field__label imageField__label' htmlFor={id}> <img className='imageField__image' src={this.imageSrc} alt='Upload' /> <input type='hidden' id={`${id}-value`} name={`${name}-value`} ref={this.input} value={this.imageSrc} /> <FA className='imageField__noImageIcon' icon={faUpload} /> <span className='field__labelSpan imageField__labelSpan'> {label} {this.requiredLabel} </span> </label> </div> {this.renderValidationMessages()} </div> ); } }
JavaScript
class ColorManager { constructor() { const p = palette('mpn65',64) this.colors = p.map((x)=> [x,false]) // all unused this.used_colors = new Set() } // Take a color take() { const color = this.colors[0] for (let i = 0; i < this.colors.length; i++) { if (this.colors[i][1] == false) { this.colors[i][1] = true return this.colors[i][0] } } return '' // no colors left } // Free a color back to the manager free(color) { if (this.used_colors.has(color)) { this.used_colors.delete(color) for (let i = 0; i < this.colors.length; i++) { if (this.colors[i][0] == color) { this.colors[i][1] = false // unused } } } } }
JavaScript
class SimpleLinePlotWidget extends BaseWidget { constructor(el, id) { super(el, id, 250) this.plot_div_name = this.name + '-lineplot-div-' + id.toString() this.legend_div_name = this.name + '-lineplot-legend-div-' + id.toString() this.controls_div_name = this.name + '-lineplot-controls-div-' + id.toString() // Set up the widget // TODO use the class to imply the style //this.plot_div = $(`<div id="${this.plot_div_name}" class="" style="width:100%; height:100%;"></div>`) this.jbody.html('') this.jbody.append(` <div style="display: grid; grid-template-columns: 1fr 160px; grid-template-rows: 1fr auto 10px; grid-template-areas: 'plot legend' 'plot controls' 'plot spacer'; width:100%; height:100%;"> <div id="${this.plot_div_name}" class="" style="grid-area:plot;"></div> <div id="${this.controls_div_name}" class="" style="grid-area:controls; border-top: 1px solid #ccc;"> <span class="smalltext">points/stat:</span> <span id="points">0</span><br/> <span class="smalltext">downsampling:</span> <span id="downsampling">0</span><br/> <span class="smalltext">annotations:</span> <span id="num-annotations">0</span> <a id="clear-annotations" href="javascript:void(0);" class="tinytext">(clear)</a> <span class="tinytext" title="Annotations cannot currently be saved since they are specific to a single data-set">(annotations are not saved)</span> </div> <div id="${this.legend_div_name}" style="grid-area:legend; overflow-y: auto;"></div> <div style="grid-area:spacer;"><!-- this spacer is here to not block the resize handle for the widget with legend/controls content --></div> </div> `) this.plot_div = this.jbody.find('#' + this.plot_div_name) this.controls_div = this.jbody.find('#' + this.controls_div_name) this.legend_div = this.jbody.find('#' + this.legend_div_name) this.num_annotations = this.controls_div.find('#num-annotations') this.downsampling_span = this.controls_div.find('#downsampling') this.points_span = this.controls_div.find('#points') this.controls_div.find('#clear-annotations').on('click', () => { this._clear_annotations() }) this.layout = this._make_layout() // Initial data this.series_time = null this.y_extents = [-1,1] this.cmgr = new ColorManager this._stat_cols = [] this._stat_colors = [] // TODO: should save in layout. Would also need to update the color manager with already-used colors this._unplotted_annotations = [] // annotations that have not yet been applied to the plot } _make_layout() { return { autosize: true, // allows scaling to fit space //height: 150, showlegend: false, title: '', // TODO: grab these from the UI layout (or have the ui pass them in) margin: { t:10, l:50, // roughly match td to the left of time slider r:0, // legend will be manual to the right b:20}, xaxis: { autorange: false, title: '', ticks: '', side: 'bottom' }, yaxis: { autorange: true, title: 'value', ticks: '', ticksuffix: ' ', autosize: true }, font: { size: 10, }, dragmode: 'pan', // default to pan as default control (panning is faster zooming for backend, so discourage zoom) } } // Someone asked us to clear stats on_clear_stats() { this._stat_cols = [] this._stat_colors = {} this.cmgr = new ColorManager() } // Add stats, skipping duplicates, and refresh _add_new_stats(new_stats) { // Prevent duplicate stats for (const stat_item of new_stats) { if (!list_contains(this._stat_cols, stat_item)) { this._stat_cols.push(stat_item) this._stat_colors[stat_item] = this.cmgr.take() } } // Ask for a refresh to redraw with the new stat this.viewer.refresh_widget(this) } // Someone dropped a new stat on us on_add_stat(new_stat_name) { this._add_new_stats([new_stat_name]) } // Called upon start of widget resize on_resize_started() { } // Called upon end of widget resize on_resize_complete() { // Hide the control/info panel below a certain widget height if ($(this.element).height() < 200) { this.controls_div.css({display: 'none', 'grid-area': ''}) } else { this.controls_div.css({display: '', 'grid-area': 'controls'}) } this.render() } // (Save) Get state to be stored in the layout file. This will be given back to apply_config_data later. get_config_data() { return { stat_cols: this._stat_cols, } } // (Load) Apply a dictionary of configuration data specific to this type of widget apply_config_data(d) { this._stat_cols = d.stat_cols this._stat_colors = {} for (const stat of this._stat_cols) { this._stat_colors[stat] = this.cmgr.take() } } // New data was received from the server on_update_data(json) { if (json == null) { this.series_time = null this.series = {} this.instruction_nums = [] this.indices = [] this.addresses = [] this.targets = [] this.modality = {} this.y_extents = [-1,1] this.downsampling = -1 this.add_status_msg(BaseWidget.NO_DATA_FOR_TIME_RANGE) this.downsampling_span.html('?') this.points_span.html('0') return } const msg = json.raw_binary_data const nseries = json.processorSpecific.numSeries const points_per_series = json.processorSpecific.pointsPerSeries const series_blob_offset = json.processorSpecific.seriesBlobOffset const modalities_offset = json.processorSpecific.modalitiesOffset this.downsampling = json.processorSpecific.downsampling const instruction_nums_offset = json.processorSpecific.instructionNumsOffset const indices_offset = json.processorSpecific.indicesOffset const addresses_offset = json.processorSpecific.addressesOffset const targets_offset = json.processorSpecific.targetsOffset this.downsampling_span.html(this.downsampling > 1 ? ('/' + this.downsampling.toString()) : 'none') this.points_span.html(points_per_series.toString()) // Parse out heatmap binary data if (nseries == 0 || points_per_series == 0) { this.series_time = null this.series = {} this.instruction_nums = [] this.indices = [] this.addresses = [] this.targets = [] this.modality = {} this.downsampling = -1 this.y_extents = [-1,1] this.add_status_msg(BaseWidget.NO_DATA_FOR_TIME_RANGE) return } const data = new Float32Array(msg, series_blob_offset, nseries * points_per_series) // Skip dims const modalities = new Int16Array(msg, modalities_offset, nseries) this.series_time = data.subarray(0, points_per_series) this.series = {} this.modality = {} this.y_extents = json.processorSpecific.yExtents for (let i = 0; i < this._stat_cols.length; i++) { const begin = (i + 1) * points_per_series const end = begin + points_per_series this.series[this._stat_cols[i]] = data.subarray(begin, end) this.modality[this._stat_cols[i]] = modalities[i + 1] } // Capture some bp-specific stuff (this should be moved to the bp widget instead) if (typeof instruction_nums_offset != 'undefined') this.instruction_nums = new BigInt64Array(msg, instruction_nums_offset, points_per_series) else this.instruction_nums = [] if (typeof indices_offset != 'undefined') this.indices = new BigInt64Array(msg, indices_offset, points_per_series) else this.indices = [] if (typeof addresses_offset != 'undefined') this.addresses = new BigInt64Array(msg, addresses_offset, points_per_series) else this.addresses = [] if (typeof targets_offset != 'undefined') this.targets = new BigInt64Array(msg, targets_offset, points_per_series) else this.targets = [] } _update_plot(data) { // See if plot existed already and if not const plot_existed = this.plot_div.html() != '' Plotly.react(this.plot_div[0], data, this.layout, {displaylogo: false, modeBarButtonsToRemove: SimpleLinePlotWidget.plotly_buttons_to_remove, scrollZoom: true}) if (!plot_existed) { // Capture layout events (e.g. box selection) to drive the global slider this.plot_div[0].on('plotly_relayout', (evt) => { if (typeof evt['xaxis.range[0]'] != 'undefined') { const first = parseInt(evt['xaxis.range[0]']) const last = parseInt(evt['xaxis.range[1]']) if (this.should_follow_global()) { this.viewer.widget_chose_time(this, first, last) } else { this._request_custom_update(first, last) // Flag as needing a custom update for last range } this.plot_div[0].layout.yaxis.autorange = true // Have to re-enable because zooming scales y data with an explicit range } else { // Could be an annotation change } return false; }) // Handle legend clicks (not perfect - cannot intercept them) this.plot_div[0].on('plotly_restyle', (evt) => { // On a legend click, remote the item if (evt[0].visible[0] == 'legendonly') { // Legend click/change? const indices = evt[1] let num_deleted = 0 for (const i of indices) { // note: assuming indices are sorted ascending const stat = this._stat_cols[i - num_deleted] this.cmgr.free(this._stat_colors[stat]) this._stat_cols.splice(i - num_deleted,1) num_deleted++ // Compensate for removed items } if (num_deleted > 0) { this.viewer.refresh_widget(this) // Request refresh with removed data } } }) // TODO: Figure out what the actually show when hovering this.plot_div[0].on('plotly_hover', (data) => { if (this.downsampling > 1) { return // No hover until zoomed in close enough that there is no downsampling } if ((data.points || []).length > 0) { const point = data.points[0] // bp hovering. TODO: Move this to bp line plot subclasss if (this.instruction_nums.length > 0) { const inst_id = this.instruction_nums[point.pointIndex] const branch_index = this.indices[point.pointIndex] const addr = this.addresses[point.pointIndex] const tgt = this.targets[point.pointIndex] const grid = this.plot_div.find('g.gridlayer')[0] const rect = grid.getBoundingClientRect() const x_offset = -5 const y_offset = 5 const x = point.xaxis.d2p(point.x) + rect.left + x_offset const y = point.yaxis.d2p(point.y) + rect.top + y_offset const content = `inst#:${inst_id}<br>uBrn#:${branch_index}<br>ha:0x${addr.toString(16)}<br>tgt:0x${tgt.toString(16)}` const hover = $(`<div id="bp-line-plot-hover-div" class="smalltext" style="left:0; top:${y};">${content}</div>`) $('body').append(hover) const border_width = parseInt(hover.css('border-width')) hover.css({left: x - hover.width() - 2 * border_width}) // assign left after adding to DOM so we know width } } }) this.plot_div[0].on('plotly_unhover', (data) => { while ($('#bp-line-plot-hover-div').length > 0) $('#bp-line-plot-hover-div').remove() }) this.plot_div[0].on('plotly_click', (data) => { const point = data.points[0] // bp hovering. TODO: Move this to bp line plot subclasss if (this.instruction_nums.length > 0) { const inst_id = this.instruction_nums[point.pointIndex] const branch_index = this.indices[point.pointIndex] const addr = this.addresses[point.pointIndex] const tgt = this.targets[point.pointIndex] const ay = point.y <= 0.5 ? 60 : -60 // pixels (must be larger than the height of the annotation text) const new_index = (this.plot_div[0].layout.annotations || []).length let removed = false if (new_index > 0) { // Remove if clicked on one that is already there this.plot_div[0].layout.annotations.forEach((ann, idx) => { if (ann.branch_index == branch_index) { Plotly.relayout(this.plot_div[0], `annotations[${idx}]`, 'remove') this.num_annotations.html((this.plot_div[0].layout.annotations || []).length.toString()) removed = true } }) } if (!removed) { if (this.downsampling > 1) { this.viewer.show_error_popup('Cannot add annotation', `Annotations can only be added to line plots when viewing data with no downsampling applied. Downsampling is currently ${this.downsampling}. Zoom in to reduce downsampling.`) return } const new_anno = { x: point.xaxis.d2l(point.x), y: point.yaxis.d2l(point.y), arrowhead: 5, arrowsize: 2, arrowwidth: 1, ax: 0, ay: ay, bgcolor: 'rgba(255,255,255,0.8)', font: {size:11, family:'Courier New, monospace', color:'#404040'}, text: `inst#:${inst_id}<br>uBrn#:${branch_index}<br>ha:0x${addr.toString(16)}<br>tgt:0x${tgt.toString(16)}`, branch_index: branch_index, index: new_index, captureevents: true, // allow click events } Plotly.relayout(this.plot_div[0], `annotations[${new_index}]`, new_anno) this.num_annotations.html(this.plot_div[0].layout.annotations.length.toString()) } } }) this.plot_div[0].on('plotly_clickannotation', (event) => { Plotly.relayout(this.plot_div[0], `annotations[${event.index}]`, 'remove') this.num_annotations.html((this.plot_div[0].layout.annotations || []).length.toString()) }) } } // Called when needs to re-render on_render() { // Detect no-data condition if (this.series_time == null) { this._update_plot([]) // draw current range with no data return } // Set a new explicit range for the plot based on the latest update for this widget. // Do not use the data we are given because it could be a subset if some was not applicable. const last_range = this.get_last_update() this.layout.xaxis.range = [last_range.first, last_range.last] const range_length = last_range.last - last_range.first + 1 // Draw some grey boxes beside the data so when panning it is clear that this area is "out of bounds" this.layout.shapes = [] this.layout.shapes.push({ type: 'rect', xref: 'x', yref: 'y', x0: last_range.first - 1 - range_length, x1: last_range.first - 1, y0: this.y_extents[0], y1: this.y_extents[1], line: { width: 0, }, fillcolor: 'rgba(0,0,0,.1)', }) this.layout.shapes.push({ type: 'rect', xref: 'x', yref: 'y', x0: last_range.last + 1, x1: last_range.last + 1 + range_length, y0: this.y_extents[0], y1: this.y_extents[1], line: { width: 0, }, fillcolor: 'rgba(0,0,0,.1)', }) // Now that there is data, clear status warnings this.remove_status_msg(BaseWidget.NO_DATA_FOR_TIME_RANGE) // Grab the x axis const xs = this.series_time this.legend_div.html('') // Grab series value arrays and make them plotly plot items const data = [] const lineWidth = 0.6 // thickness of lines (<1 implies transparency) for (const stat of this._stat_cols) { // Names that are too long shrink the plot area and cause misalignment between stacked line plots const display_name = make_string_length(stat, 24) const color = this._stat_colors[stat] // Choose a size for markers based on the number of points! // NOTE: This should be based on screen size, but it works ok without it const marker_size = xs.length < 50 ? 6 : xs.length < 200 ? 4 : xs.length < 500 ? 3 : 2 // Special visualization for branch correctness only since it is a bit expensive and doesn't look good // if more than one view is like this. // NOTE: The length limit here is important, otherwise this takes too long to do. let legend_icon const fully_zoomed_and_spiky = this.downsampling <= 1 && this.modality[stat] <= 3 && this.modality[stat] != -1 && xs.length < 1000 const ys = this.series[stat] if (this._stat_cols.length == 1 && stat == 'correct' && fully_zoomed_and_spiky) { // no downsampling (can be 0 or 1 depending on calculation) // Turn the points to vertical ticks to make correct/incorrect density more apparant as we zoom in const new_xs = [] const new_ys = [] const new_ys2 = [] for (let i = 0; i < xs.length; i++) { const x = xs[i] const y = ys[i] new_xs.push(x, x,null) new_ys.push(0.5,y,null) } // Add markers first since this is what we'll be adding annotations on (series [0]) data.push({name: display_name, x: xs, y: ys, mode: 'markers', line: { width:lineWidth, color:color }, marker: { size: marker_size }}) data.push({name: '', x: new_xs, y: new_ys, mode: 'lines', line: { width:lineWidth, color:color }, showlegend: false, opacity: 0.5}) //data.push({name: display_name, x: xs, y: this.series[stat], mode: 'lines', line: { width:lineWidth, color:color }, showlegend: false}) legend_icon = `<div style="background-color:${color}; width:3px; height: 3px; display:inline-block; margin-bottom:2px; margin-left: 5px; margin-right: 5px"></div>` } else if (fully_zoomed_and_spiky) { data.push({name: display_name, x: xs, y: ys, mode: 'lines+markers', line: { width:lineWidth, color:color }, marker: { size: marker_size }}) legend_icon = `<div style="background-color:${color}; width:12px; height: 2px; display:inline-block; margin-bottom:3px;"></div>` } else { data.push({name: display_name, x: xs, y: ys, mode: 'lines', line: { width:lineWidth, color:color }}) legend_icon = `<div style="background-color:${color}; width:12px; height: 2px; display:inline-block; margin-bottom:3px;"></div>` } // Build the legend entry const legend_item = $(`<div style="color: ${color}; border-bottom: 1px solid #eee; "> <div class="no-margin-no-padding" style="width: calc(100% - 24px); display: inline-block;"> ${legend_icon} ${display_name.replace(/\./g, '.<wbr/>')} </div> <div class="no-margin-no-padding" style="width: 20px; color: #aaa; display: inline-block; text-align: right;"> <a href="javascript:void(0);" class="stealth-link">[x]</a> </div> </div>`) this.legend_div.append(legend_item) const anchor = legend_item.find('a') anchor.on('click', () => { // Remove this stat this.cmgr.free(this._stat_colors[stat]) const idx = this._stat_cols.indexOf(stat) if (idx >= 0) { this._stat_cols.splice(idx, 1) this.viewer.refresh_widget(this) // Request refresh with removed data } }) } // Update plot this._update_plot(data) //Plotly.react(this.plot_div[0], data, this.layout, {displaylogo: false, modeBarButtonsToRemove: SimpleLinePlotWidget.plotly_buttons_to_remove, scrollZoom: true}) } // kwargs to pass to processor function when we make our requests get_request_kwargs() { const absolute_max_points_per_series = 5000 const absolute_min_points_per_series = 400 const excess_stat_cols = Math.max(0, this._stat_cols.length - 4) const max_points_per_series = Math.max(absolute_min_points_per_series, absolute_max_points_per_series - (1000 * excess_stat_cols)) // Reduce number of points for excessive columns return { stat_cols: this._stat_cols, // TODO: use real stats from this.data_source max_points_per_series : max_points_per_series, // Limit points... Without this, number of points are impossibly large } } _clear_annotations() { const annotations = this.plot_div[0].layout.annotations || [] while (annotations.length > 0) { Plotly.relayout(this.plot_div[0], `annotations[0]`, 'remove') } this.num_annotations.html((this.plot_div[0].layout.annotations || []).length.toString()) } }
JavaScript
class ModelView extends TexturedModelView { /** * @param {Scene} scene */ update(scene) { let data = super.update(scene); if (data) { let batchCount = (this.model.renderMode === 2 ? 2 : 1); let buckets = data.buckets; let renderedInstances = 0; let renderedBuckets = 0; let renderCalls = 0; for (let i = 0, l = data.usedBuckets; i < l; i++) { renderedInstances += buckets[i].count; renderedBuckets += 1; renderCalls += batchCount; } this.renderedInstances = renderedInstances; this.renderedBuckets = renderedBuckets; this.renderCalls = renderCalls; } } }
JavaScript
class Client { /** * Create the client. * @param {Object} credentials User credentials. */ constructor(credentials) { this._config = config.read(credentials); } /** * Send a query request to the API. * * @param {Object} options Configuration values. * @param {function(*)} callback Function to invoke with (error, result). */ query(options, callback) { const opc = this._config.parseQuery(options) if (!helper.config.validate(opc)) { return callback('Invalid options') } httpRequest.create().post(opc, callback) } /** * Send a query request to the API, return a stream. * * @param {Object} options Configuration values. * @returns a ReadableStream that emits one event per row. */ stream(options) { const opc = this._config.parseQuery(options, STREAMING_FORMAT); if (!helper.config.validate(opc)) { throw new Error('Invalid options') } const stream = queryStream.create(this._config, options); httpRequest.create().getResponse(opc, (error, response) => { if (error) { throw new Error('Invalid response: ' + error) } response.pipe(stream) }) return stream } /** * Get the list of pending tasks. * * @param {function(*)=} callback Function to invoke with (error, info). */ getTasks(callback) { const opc = this._config.parseGet(helper.taskPaths.getTasks()) httpRequest.create().get(opc, callback); } /** * Get a list of tasks by type. * * @param {String} type Type of the desired tasks. * @param {function(*)=} callback Function to invoke with (error, info). */ getTasksByType(type, callback) { const opc = this._config.parseGet(helper.taskPaths.getTasksByType(type)) httpRequest.create().get(opc, callback); } /** * Get info for an existing task. * * @param {String} taskId ID of the task. * @param {function(*)=} callback Function to invoke with (error, info). */ getTaskInfo(taskId, callback) { const opc = this._config.parseGet(helper.taskPaths.getTaskInfo(taskId)) httpRequest.create().get(opc, callback); } /** * Start an existing task. * * @param {String} taskId ID of the task. * @param {function(*)=} callback Function to invoke with (error, info). */ startTask(taskId, callback) { const opc = this._config.parseGet(helper.taskPaths.startTask(taskId)) httpRequest.create().get(opc, callback); } /** * Stop an existing task. * * @param {String} taskId ID of the task. * @param {function(*)=} callback Function to invoke with (error, info). */ stopTask(taskId, callback) { const opc = this._config.parseGet(helper.taskPaths.stopTask(taskId)) httpRequest.create().get(opc, callback); } /** * Delete an existing task. * * @param {String} taskId ID of the task. * @param {function(*)=} callback Function to invoke with (error, info). */ deleteTask(taskId, callback) { const opc = this._config.parseGet(helper.taskPaths.deleteTask(taskId)) httpRequest.create().get(opc, callback); } }
JavaScript
class FrontendContainerBlock extends Component { constructor() { super( ...arguments ); const { attributes } = this.props; this.state = { orderby: attributes.orderby, reviewsToDisplay: parseInt( attributes.reviewsOnPageLoad, 10 ), }; this.onAppendReviews = this.onAppendReviews.bind( this ); this.onChangeOrderby = this.onChangeOrderby.bind( this ); } onAppendReviews() { const { attributes } = this.props; const { reviewsToDisplay } = this.state; this.setState( { reviewsToDisplay: reviewsToDisplay + parseInt( attributes.reviewsOnLoadMore, 10 ), } ); } onChangeOrderby( event ) { const { attributes } = this.props; this.setState( { orderby: event.target.value, reviewsToDisplay: parseInt( attributes.reviewsOnPageLoad, 10 ), } ); } onReviewsAppended( { newReviews } ) { speak( sprintf( // Translators: %d is the count of reviews loaded. _n( '%d review loaded.', '%d reviews loaded.', newReviews.length, 'woocommerce' ), newReviews.length ) ); } onReviewsReplaced() { speak( __( 'Reviews list updated.', 'woocommerce' ) ); } onReviewsLoadError() { speak( __( 'There was an error loading the reviews.', 'woocommerce' ) ); } render() { const { attributes } = this.props; const { categoryIds, productId } = attributes; const { reviewsToDisplay } = this.state; const { order, orderby } = getSortArgs( this.state.orderby ); return ( <FrontendBlock attributes={ attributes } categoryIds={ categoryIds } onAppendReviews={ this.onAppendReviews } onChangeOrderby={ this.onChangeOrderby } onReviewsAppended={ this.onReviewsAppended } onReviewsLoadError={ this.onReviewsLoadError } onReviewsReplaced={ this.onReviewsReplaced } order={ order } orderby={ orderby } productId={ productId } reviewsToDisplay={ reviewsToDisplay } /> ); } }
JavaScript
class AbstractHostFeature { /** * @constructor * * @param {core/HostObject} host - The HostObject managing the feature. */ constructor(host) { this._host = host; } /** * Adds a namespace to the host with the name of the feature to contain properties * and methods from the feature that users of the host need access to. */ installApi() { const events = {}; const api = {EVENTS: events}; // Add the class name to event names Object.entries(this.constructor.EVENTS).forEach(([name, value]) => { events[name] = `${this.constructor.name}.${value}`; }); this._host[this.constructor.name] = api; return api; } /** * Gets the host that manages the feature. * * @readonly */ get host() { return this._host; } /** * Gets the engine owner object of the host. * * @readonly */ get owner() { return this._host.owner; } /** * Listen to a feature message from the host object. * * @param {string} message - Message to listen for. * @param {Function} callback - The callback to execute when the message is received. */ listenTo(message, callback) { this._host.listenTo(message, callback); } /** * Stop listening to a message from the host object. * * @param {string} message - Message to stop listening for. * @param {Function=} callback - Optional callback to remove. If none is defined, * remove all callbacks for the message. */ stopListening(message, callback) { this._host.stopListening(message, callback); } /** * Stop listening to all messages. */ stopListeningToAll() { this._host.stopListeningToAll(); } /** * Emit feature messages from the host. Feature messages will be prefixed with * the class name of the feature. * * @param {string} message - The message to emit. * @param {any=} value - Optional parameter to pass to listener callbacks. */ emit(message, value) { message = `${this.constructor.name}.${message}`; this._host.emit(message, value); } /** * Emit feature messages from the global messenger. Feature messages will be prefixed * with the class name of the feature. * * @param {string} message - The message to emit. * @param {any=} value - Optional parameter to pass to listener callbacks. */ static emit(message, value) { message = `${this.name}.${message}`; Messenger.emit(message, value); } /** * Executes each time the host is updated. * * @param {number} deltaTime - Amount of time since the last host update was * called. */ update(deltaTime) { this.emit(this.constructor.EVENTS.update, deltaTime); } /** * Clean up once the feature is no longer in use. Remove the feature namespace * from the host and remove reference to the host. */ discard() { Object.keys(this._host[this.constructor.name]).forEach(name => { delete this._host[this.constructor.name][name]; }); delete this._host[this.constructor.name]; delete this._host; } /** * Applies a sequence of mixin class factory functions to this class and * returns the result. Each function is expected to return a class that * extends the class it was given. The functions are applied in the order * that parameters are given, meaning that the first factory will * extend this base class. * * @param {...Function} mixinClassFactories Class factory functions that will * be applied. * * @returns {Class} A class that is the result of applying the factory functions. * The resulting class will always inherit from AbstractHostFeature. */ static mix(...mixinClassFactories) { let ResultClass = this; mixinClassFactories.forEach(mixinClassFactory => { ResultClass = mixinClassFactory(ResultClass); }); return ResultClass; } }
JavaScript
class Timer extends Stopwatch { constructor(expirationMillis, tickMillis = DEFAULT_RESOLUTION_MILLIS) { super(Math.min(expirationMillis, tickMillis)); this.expirationMillis = expirationMillis; this.on('tick', this, this._expirationHandler); } start() { if (this.isExpired) { this.reset(true); } super.start(); } restart() { this.reset(true); this.start(); this.trigger('restart', this); } // this is a domain convenience that just calls stop() pause(force = false) { this.stop(force); this.trigger('pause', this); } get remainingMillis() { return this.expirationMillis - this.elapsedMillis; } get isExpired() { return this.remainingMillis <= 0; } _expirationHandler() { if (this.isExpired) { this.stop(true); this.trigger('expired', this); } } }
JavaScript
class CoreGradesCourseManager extends _classes_page_items_list_manager__WEBPACK_IMPORTED_MODULE_9__["CorePageItemsListManager"] { constructor(pageComponent, courseId, userId, outsideGradesTab) { super(pageComponent); this.courseId = courseId; this.userId = userId; this.outsideGradesTab = outsideGradesTab; } /** * Set grades table. * * @param table Grades table. */ setTable(table) { this.columns = table.columns; this.rows = table.rows; this.setItems(table.rows.filter(this.isFilledRow)); } /** * @inheritdoc */ select(row) { const _super = Object.create(null, { select: { get: () => super.select } }); return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function* () { if (this.outsideGradesTab) { yield _services_navigator__WEBPACK_IMPORTED_MODULE_10__["CoreNavigator"].navigateToSitePath(`/grades/${this.courseId}/${row.id}`); return; } return _super.select.call(this, row); }); } /** * @inheritdoc */ getDefaultItem() { return null; } /** * @inheritdoc */ getItemPath(row) { return row.id.toString(); } /** * @inheritdoc */ getItemQueryParams() { return { userId: this.userId }; } /** * @inheritdoc */ logActivity() { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function* () { yield _features_grades_services_grades__WEBPACK_IMPORTED_MODULE_4__["CoreGrades"].logCourseGradesView(this.courseId, this.userId); }); } /** * Check whether the given row is filled or not. * * @param row Grades table row. * @return Whether the given row is filled or not. */ isFilledRow(row) { return 'id' in row; } }
JavaScript
class ModelStore extends EventEmitter { /** * Setup */ constructor() { super(); this._state = []; this.__handleOpen = this.__handleOpen.bind(this); this.__handleClose = this.__handleClose.bind(this); ModalActions.on('open', this.__handleOpen); ModalActions.on('close', this.__handleClose); } /** * Return a shallow clone of the state so we con't accidently mutate the state * @public * @return {Array<Object>} */ getState() { return this._state.slice(0); } /** * Used to listen to when modals are added or removed * @public * @param {Function} fn * @return {Object} */ onChange(fn) { this.on('change', fn) return { remove: () => { this.removeListener('change', fn); } } } /** * Handles updating the state and emitting change events when the number of * modals changes * @private * @param {Array<Object>} state This is the updated state to set. It * does not merge like normal. */ __setState(state) { // Check if changed let changed = false; if(state.length !== this._state.length) { changed = true; } this._state = state; if (changed) { // Delay until next loop to let react finish it's life cycles setTimeout(()=>{ // Let the world know this.emit('change'); }, 0); } } /** * Event triggered from ModalActions.on('open') * @param {React} component */ __handleOpen(component) { let state = this.getState(); state.push(component); // Update this.__setState(state); } /** * Event triggered from ModalActions.on('close') * @private * @param {React} component */ __handleClose(component) { // Most likely the first index as we only render the first but check anyway let index = this._state.findIndex(item => item === component); let state = this.getState(); state.splice(index, 1); // Update this.__setState(state); } }
JavaScript
class NavigationDrawer extends PureComponent { static DrawerType = { // deprecated /* eslint-disable no-console */ _warned: false, _msg: 'Invalid use of `NavigationDrawer.DrawerType.{{TYPE}}`. The `NavigationDrawer.DrawerType` ' + 'has been deprecated and will be removed in the next major release. Please use the ' + '`NavigationDrawer.DrawerTypes.{{TYPE}}` instead.', get FULL_HEIGHT() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'FULL_HEIGHT')); } this._warned = true; return DrawerTypes.FULL_HEIGHT; }, get CLIPPED() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'CLIPPED')); } this._warned = true; return DrawerTypes.CLIPPED; }, get FLOATING() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'FLOATING')); } this._warned = true; return DrawerTypes.FLOATING; }, get PERSISTENT() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'PERSISTENT')); } this._warned = true; return DrawerTypes.PERSISTENT; }, get PERSISTENT_MINI() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'PERSISTENT_MINI')); } this._warned = true; return DrawerTypes.PERSISTENT_MINI; }, get TEMPORARY() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'TEMPORARY')); } this._warned = true; return DrawerTypes.TEMPORARY; }, get TEMPORARY_MINI() { if (!this._warned) { console.error(this._msg.replace(/{{TYPE}}/g, 'TEMPORARY_MINI')); } this._warned = true; return DrawerTypes.TEMPORARY_MINI; }, /* eslint-enable no-console */ }; static DrawerTypes = DrawerTypes; static propTypes = { /** * An optional id to provide to the entire div wrapper. */ id: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional id to provide to the drawer. This is generally a good idea to provide if * there are any `navItems` defined. * * @see {@link #navItemsId} * @see {@link #miniDrawerId} */ drawerId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional id to provide to the navItems list. If this is omitted and the `drawerId` prop is * defined, it will be defaulted to `${drawerId}-nav-items`. * * @see {@link #drawerId} * @see {@link Drawer#navItemsId} */ navItemsId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional id to apply to mini drawer that gets created when the `drawerType` is set to * one of the mini types. * * @see {@link #drawerId} * @see {@link #miniNavItemsId} */ miniDrawerId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional id to apply to mini drawer's navigation list that gets created when the `drawerType` * is set to one of the mini types. * * @see {@link #navItemsId} * @see {@link #miniDrawerId} */ miniNavItemsId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional id to provide to the main toolbar. */ toolbarId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An id to give the main content. A hidden link is created in the main drawer's header that links to the main * content. This is used for keyboard only users to jump the navigation and jump straight to the content. * * If you provide your own `drawerHeader`, it is suggested to include the link yourself. */ contentId: isRequiredForA11y(PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ])), /** * An optional style to apply to the surrounding container. */ style: PropTypes.object, /** * An optional className to apply to the surrounding container. */ className: PropTypes.string, /** * An optional style to apply to the main toolbar. */ toolbarStyle: PropTypes.object, /** * An optional className to apply to the toolbar. */ toolbarClassName: PropTypes.string, /** * An optional style to apply to the main toolbar's title. */ toolbarTitleStyle: PropTypes.object, /** * An optional className to apply to the main toolbar's title. */ toolbarTitleClassName: PropTypes.string, /** * An optional style to apply to the drawer. */ drawerStyle: PropTypes.object, /** * An optional className to apply to the drawer. */ drawerClassName: PropTypes.string, /** * An optional style to apply to the `List` surrounding the `navItems`. */ navStyle: PropTypes.object, /** * An optional className to apply to the `List` surrounding the `navItems`. */ navClassName: PropTypes.string, /** * An optional style to apply to the mini drawer that gets created when the `drawerType` is set * to one of the mini types. * * @see {@link #miniDrawerClassName} * @see {@link #miniNavStyle} * @see {@link #miniNavClassName} */ miniDrawerStyle: PropTypes.object, /** * An optional className to apply to the mini drawer that gets created when the `drawerType` is set * to one of the mini types. * * @see {@link #miniDrawerStyle} * @see {@link #miniNavStyle} * @see {@link #miniNavClassName} */ miniDrawerClassName: PropTypes.string, /** * An optional style to apply to the mini drawer's navigation list when the `drawerType` is set * to one of the mini types. * * @see {@link #miniDrawerStyle} * @see {@link #miniDrawerClassName} * @see {@link #miniNavClassName} */ miniNavStyle: PropTypes.object, /** * An optional className to apply to the mini drawer's navigation list when the `drawerType` is set * to one of the mini types. * * @see {@link #miniDrawerStyle} * @see {@link #miniDrawerClassName} * @see {@link #miniNavStyle} */ miniNavClassName: PropTypes.string, /** * An optional style to apply to the content. This is the container surrounding whatever * `children` are passed in. */ contentStyle: PropTypes.object, /** * An optional className to apply to the content. This is the container surrounding whatever * `children` are passed in. */ contentClassName: PropTypes.string, /** * An optional style to apply to the overlay. */ overlayStyle: PropTypes.object, /** * An optional className to apply to the overlay. */ overlayClassName: PropTypes.string, /** * The children to display in the main content. */ children: PropTypes.node, /** * Boolean if the `drawerHeader` component should be built if the `drawerHeader` prop is not * passed in. */ includeDrawerHeader: PropTypes.bool, /** * An optional header to display in the drawer. This will normally be the `Toolbar` component * or any other type of header. You can either use this prop with the `CloseButton` component * when displaying a persistent drawer, or use the `drawerTitle` and `drawerHeaderChildren` prop * to build a toolbar. */ drawerHeader: PropTypes.node, /** * An optional title to use for the drawer's header toolbar. If the `drawerHeader` prop is defined, * this is invalid. */ drawerTitle: invalidIf(PropTypes.node, 'drawerHeader'), /** * An optional zDepth to apply to the drawer. If this is omitted, the value will be set as follows: * - floating || inline = 1 * - temporary = 5 * - all others = 1 * * @see {@link Papers/Paper#zDepth} */ drawerZDepth: PropTypes.number, /** * Any additional children to display after the `drawerHeader` and `navItems` list in the drawer. */ drawerChildren: PropTypes.node, /** * Any additional children to display in the drawer's header `Toolbar`. If the `drawerHeader` prop is defined, * this is invalid. */ drawerHeaderChildren: invalidIf(PropTypes.node, 'drawerHeader'), /** * The position for the drawer to be displayed. */ position: PropTypes.oneOf(['left', 'right']).isRequired, /** * An optional list of elements or props to use to build a navigational list in the drawer. * When the item is an object of props, it will build a `ListItem` component unless a key of * `divider` or `subheader` is set to true. It will then create the Divider or Subheader component * with any other remaining keys. */ navItems: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.element, PropTypes.shape({ divider: PropTypes.bool, subheader: PropTypes.bool, primaryText: PropTypes.node, }), ])), /** * The drawer type to use for mobile devices. */ mobileDrawerType: PropTypes.oneOf([ DrawerTypes.TEMPORARY, DrawerTypes.TEMPORARY_MINI, ]).isRequired, /** * The drawer type to use for tablets. */ tabletDrawerType: PropTypes.oneOf([ DrawerTypes.FULL_HEIGHT, DrawerTypes.CLIPPED, DrawerTypes.FLOATING, DrawerTypes.PERSISTENT, DrawerTypes.PERSISTENT_MINI, DrawerTypes.TEMPORARY, DrawerTypes.TEMPORARY_MINI, ]).isRequired, /** * The drawer type to use for desktop displays. */ desktopDrawerType: PropTypes.oneOf([ DrawerTypes.FULL_HEIGHT, DrawerTypes.CLIPPED, DrawerTypes.FLOATING, DrawerTypes.PERSISTENT, DrawerTypes.PERSISTENT_MINI, DrawerTypes.TEMPORARY, DrawerTypes.TEMPORARY_MINI, ]).isRequired, /** * An optional drawer type to enforce on all screen sizes. If the drawer type is not * `temporary`, you are required to define the `onMediaTypeChange` prop to handle switching * to temporary when the media matches a mobile device. * ``` */ drawerType: PropTypes.oneOf([ DrawerTypes.FULL_HEIGHT, DrawerTypes.CLIPPED, DrawerTypes.FLOATING, DrawerTypes.PERSISTENT, DrawerTypes.PERSISTENT_MINI, DrawerTypes.TEMPORARY, DrawerTypes.TEMPORARY_MINI, ]), /** * The default media match for the drawer. This will be what is displayed on first render. * The component will adjust itself to the current media after it has mounted, but this * is mostly used for server side rendering. */ defaultMedia: PropTypes.oneOf(['mobile', 'tablet', 'desktop']), /** * The min width to use for a mobile media query. This prop should match the `md-mobile-min-width` * variable. * * The media query for a mobile device will be: * * ```js * window.matchMedia( * `screen and (min-width: ${mobileMinWidth}px) and (max-width: ${tabletMinWidth - 1}px` * ).matches; * ``` */ mobileMinWidth: PropTypes.number.isRequired, /** * The min width to use for a tablet media query. This prop should match the `md-tablet-min-width` * variable. * * The media query for a tablet device will be: * * ```js * window.matchMedia( * `screen and (min-width: ${tabletMinWidth}px) and (max-width: ${desktopWidth - 1}px` * ).matches; * ``` */ tabletMinWidth: PropTypes.number.isRequired, /** * The min width to use for a desktop media query. This prop should match the `md-desktop-min-width` * variable. * * The media query for a tablet device will be: * * ```js * window.matchMedia(`screen and (min-width: ${tabletMinWidth}px)`).matches; * ``` */ desktopMinWidth: PropTypes.number.isRequired, /** * An optional function to call when the type of the drawer changes because of the * new media queries. The callback will include the newly selected drawer type * and an object containing the media matches of `mobile`, `tablet`, and `desktop`. * * ```js * this.props.onMediaTypeChange(NavigationDrawer.DrawerTypes.TEMPORARY, { * mobile: true, * tablet: false, * desktop: false, * }); * ``` */ onMediaTypeChange: PropTypes.func, /** * Boolean if the temporary or persistent drawers are visible by default. */ defaultVisible: PropTypes.bool, /** * Boolean if the temporary or persistent drawers are visible. If this is defined, * it will make the component controlled and require the `onVisibilityChange` prop * to be defined. */ visible: controlled(PropTypes.bool, 'onVisibilityChange', 'defaultVisible'), /** * An optional function to call when the visibility of the drawer changes. The callback * will include the new visibility. * * ```js * onVisibilityChange(false); * ``` */ onVisibilityChange: PropTypes.func, /** * A boolean if the mini drawer's list should be generated from the `navItems` prop. When building * the list, it will extract the `leftIcon` or `leftAvatar` from the `navItem` and then create a * mini `ListItem` containing only that icon or image. Any other event listeners will also be applied. * * * @see {@link #miniDrawerHeader} * @see {@link #miniDrawerChildren} */ extractMini: PropTypes.bool, /** * An optional header to display in the mini drawer. This will be displayed above the optional * mini nav list that get generated if the `extractMini` prop is `true` and the `miniDrawerChildren`. * * @see {@link #extractMini} */ miniDrawerHeader: PropTypes.node, /** * Any additional children to display in the mini drawer. This will be displayed after the `miniDrawerHeader` * and the optional mini nav list that gets generated if the `extractMini` prop is `true`. * * @see {@link #extractMini} */ miniDrawerChildren: PropTypes.node, /** * Boolean if the drawer should automatically close after a nav item has been clicked for `temporary` drawers. */ autoclose: PropTypes.bool, /** * An optional title to display in the main toolbar. Either the `toolbarTitle` or the `toolbarTitleMenu` * may be defined, not both. */ toolbarTitle: invalidIf(PropTypes.node, 'toolbarTitleMenu'), /** * An optional select field menu to display in the main toolbar. Either the `toolbarTitle` or the `toolbarTitleMenu` * may be defined, not both. */ toolbarTitleMenu: PropTypes.element, /** * The theme style for the main toolbar. * * @see {@link Toolbars/Toolbar} */ toolbarThemeType: PropTypes.oneOf(['default', 'colored', 'themed']).isRequired, /** * Boolean if the toolbar's nav, actions, and title should share the same color. */ toolbarSingleColor: PropTypes.bool, /** * A boolean if the toolbar should be prominent. */ toolbarProminent: PropTypes.bool, /** * A boolean if the toolbar's title should be prominent. */ toolbarProminentTitle: PropTypes.bool, /** * A list of elements or a single element to display to the right of the * toolbar's nav, title, and children. * * @see {@link Toolbars/Toolbar#actions} */ toolbarActions: Toolbar.propTypes.actions, /** * Any children to display in the toolbar. This will be displayed between the optional title and * actions. */ toolbarChildren: Toolbar.propTypes.children, /** * An optional zDepth to apply to the toolbar. * * @see {@link Toolbars/Toolbar#zDepth} */ toolbarZDepth: PropTypes.number, /** * The component to render the content in. */ contentComponent: PropTypes.oneOfType([ PropTypes.func, PropTypes.string, ]).isRequired, /** * An optional footer display after the main content. */ footer: PropTypes.node, /** * The icon to use to render the button that will toggle the visibility of the * navigation drawer for `temporary` and `persistent` drawers. This is normally a * hamburger menu. */ temporaryIcon: PropTypes.element, /** * The icon to use to render the button that appears on a persistent drawer's open * header. This is used to create the `CloseButton` for drawers. When a persistent * drawer is closed, the `temporaryIcon` will be used to create a button to open the drawer. * * If the `drawerHeader` prop is defined, you will have to either include the `CloseButton` * in your header manually, or create your own controlled button to close the drawer. */ persistentIcon: PropTypes.element, /** * The transition name to use when the page's content changes. If you want to disable * transitions, set both the `transitionEnterTimeout` and `transitionLeaveTimeout` props * to a false-ish value. (`null`, `undefined`, or `0`). */ transitionName: PropTypes.string.isRequired, /** * The transition enter timeout when the page's content changes. If you want to disable * the enter transition, set this to a false-ish value (`null`, `undefined`, or `0`). */ transitionEnterTimeout: PropTypes.number, /** * The transition leave timeout when the page's content changes. If you want to disable * the leave transition, set this to a false-ish value (`null`, `undefined`, or `0`). */ transitionLeaveTimeout: PropTypes.number, /** * The transition duration for the drawer when sliding in and out of view. */ drawerTransitionDuration: PropTypes.number.isRequired, /** * Any additional props to provide to the main content. This will be applied before any of the generated props, * so this should not include `style`, `className`, or `component`. */ contentProps: PropTypes.object, /** * The label to use for a keyboard accessibility link that jumps all the navigation and allows a user to focus * the main content. This is created in the drawer's header. */ jumpLabel: PropTypes.node.isRequired, /** * Boolean if the Portal's functionality of rendering in a separate react tree should be applied * to the drawer. The overlay that appears for temporary type drawers will still appear in the * separate subtree. * * @see {@link Helpers/Portal} */ portal: PropTypes.bool, /** * An optional DOM Node to render the drawer into. The default is to render as * the first child in the `body`. * * > This prop will not be used when the drawer is of the permanent type or `inline` is specified * since the `Portal` component will not be used. */ renderNode: PropTypes.object, /** * Boolean if the drawer should be rendered as the last child instead of the first child * in the `renderNode` or `body`. * * > This prop will not be used when the drawer is of the permanent type or `inline` is specified * since the `Portal` component will not be used. */ lastChild: PropTypes.bool, /** * Boolean if the `drawerType` should remain constant across all media. This is really only valid * if the `drawerType` is one of the temporary types. */ constantDrawerType: PropTypes.bool, menuIconChildren: deprecated(PropTypes.node, 'Use `temporaryIcon` instead'), menuIconClassName: deprecated(PropTypes.string, 'Use `temporaryIcon` instead'), closeIconChildren: deprecated(PropTypes.node, 'Use `persistentIcon` instead'), closeIconClassName: deprecated(PropTypes.string, 'Use `persistentIcon` instead'), temporaryIconChildren: deprecated(PropTypes.node, 'Use the `temporaryIcon` instead'), temporaryIconClassName: deprecated(PropTypes.string, 'Use the `temporaryIcon` instead'), persistentIconChildren: deprecated(PropTypes.node, 'Use the `persistentIcon` instead'), persistentIconClassName: deprecated(PropTypes.string, 'Use the `persistentIcon` prop instead'), onDrawerChange: deprecated(PropTypes.func, 'Use `onVisibilityChange` or `onMediaTypeChange` instead'), onVisibilityToggle: deprecated(PropTypes.func, 'Use `onVisibilityChange` instead'), contentTransitionName: deprecated(PropTypes.string, 'Use `transitionName` instead'), contentTransitionEnterTimeout: deprecated(PropTypes.number, 'Use `transtionEnterTimeout` instead'), contentTransitionLeaveTimeout: deprecated(PropTypes.number, 'Use `transtionLeaveTimeout` instead'), initialDrawerType: deprecated( PropTypes.oneOf(['mobile', 'tablet', 'desktop']), 'Use `defaultMedia` instead' ), }; static contextTypes = { renderNode: PropTypes.object, }; static childContextTypes = { closeIcon: PropTypes.element, onCloseClick: PropTypes.func, id: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]).isRequired, label: PropTypes.node.isRequired, renderNode: PropTypes.object, } static defaultProps = { autoclose: Drawer.defaultProps.autoclose, contentId: 'main-content', // Defaults to false since it keeps the state of the drawerType in sync and makes the Drawer // controlled. On initial mount without any defaultMedia updates, it would always be considered // temporary constantDrawerType: false, jumpLabel: 'Jump to content', extractMini: true, position: Drawer.defaultProps.position, defaultMedia: Drawer.defaultProps.defaultMedia, mobileDrawerType: Drawer.defaultProps.mobileType, tabletDrawerType: Drawer.defaultProps.tabletType, desktopDrawerType: Drawer.defaultProps.desktopType, mobileMinWidth: Drawer.defaultProps.mobileMinWidth, tabletMinWidth: Drawer.defaultProps.tabletMinWidth, desktopMinWidth: Drawer.defaultProps.desktopMinWidth, includeDrawerHeader: true, contentComponent: 'main', temporaryIcon: <FontIcon>menu</FontIcon>, toolbarThemeType: 'colored', persistentIcon: <FontIcon>arrow_back</FontIcon>, transitionName: 'md-cross-fade', transitionEnterTimeout: 300, drawerTransitionDuration: Drawer.defaultProps.transitionDuration, }; /** * Determines the current media and returns an object containing matches for `mobile`, `tablet`, `desktop`, * and the current drawer type. This expects a `props` object of the drawer. * * If this is used server side, it will default to only matching mobile. * * @param {Object=} props - The current drawer's prop shape to extract the mobile, tablet, and desktop type/min * widths. This defaults to the drawer's default props. * @return {Object} an object containing the media matches and the current type to use for the drawer. */ static getCurrentMedia(props = NavigationDrawer.defaultProps) { const { mobileDrawerType: mobileType, tabletDrawerType: tabletType, desktopDrawerType: desktopType, constantDrawerType: constantType, ...others } = props; return Drawer.getCurrentMedia({ mobileType, tabletType, desktopType, constantType, ...others }); } constructor(props) { super(props); const { defaultMedia, defaultVisible, initialDrawerType } = props; this.state = { mobile: initialDrawerType || defaultMedia === 'mobile', tablet: initialDrawerType || defaultMedia === 'tablet', desktop: initialDrawerType || defaultMedia === 'desktop', }; if (typeof props.drawerType === 'undefined') { this.state.drawerType = props[`${initialDrawerType || defaultMedia}DrawerType`]; } const type = getField(props, this.state, 'drawerType'); if (typeof props.visible === 'undefined') { // The logic for determining the visibility is handled by the created mini drawer this.state.visible = isPermanent(type); if (!this.state.visible && typeof defaultVisible !== 'undefined') { this.state.visible = defaultVisible; } } } getChildContext() { const { persistentIcon, contentId: id, jumpLabel: label, // deprecated persistentIconChildren, persistentIconClassName, closeIconChildren, closeIconClassName, } = this.props; return { id, label, closeIcon: getDeprecatedIcon( closeIconClassName || persistentIconClassName, closeIconChildren || persistentIconChildren, persistentIcon, ), onCloseClick: this._toggleVisibility, renderNode: this.context.renderNode, }; } componentWillReceiveProps(nextProps) { const visible = getField(this.props, this.state, 'visible'); const nVisible = getField(nextProps, this.state, 'visible'); if (visible !== nVisible) { this._animate(nextProps); } } componentWillUnmount() { if (this._timeout) { clearTimeout(this._timeout); } } _animate = (props = this.props, state = this.state) => { if (isTemporary(getField(props, state, 'drawerType'))) { return; } if (this._timeout) { clearTimeout(this._timeout); } this._timeout = setTimeout(() => { this.setState({ contentActive: false }); }, props.drawerTransitionDuration); this.setState({ contentActive: true }); }; _toggleVisibility = (e) => { const { onVisibilityToggle, onVisibilityChange, onDrawerChange } = this.props; const visible = !getField(this.props, this.state, 'visible'); const callback = onVisibilityChange || onVisibilityToggle || onDrawerChange; if (callback) { callback(visible, e); } if (typeof this.props.visible === 'undefined') { this.setState({ visible }); this._animate(this.props); } }; _handleVisibility = (visible) => { const { onVisibilityToggle, onVisibilityChange, onDrawerChange } = this.props; const callback = onVisibilityChange || onVisibilityToggle || onDrawerChange; if (callback) { callback(visible); } if (typeof this.props.visible === 'undefined') { this.setState({ visible }); this._animate(this.props); } }; _handleTypeChange = (drawerType, mediaState) => { const { onMediaTypeChange } = this.props; let state = mediaState; if (onMediaTypeChange) { onMediaTypeChange(drawerType, mediaState); } if (typeof this.props.drawerType === 'undefined') { state = { ...mediaState, drawerType }; } this.setState(state); }; render() { const { id, style, className, toolbarStyle, toolbarClassName, drawerStyle, drawerClassName, contentStyle, contentClassName, contentComponent: Content, miniDrawerStyle, miniDrawerClassName, miniNavStyle, miniNavClassName, miniDrawerId, miniNavItemsId, navItems, children, drawerId, drawerTitle, drawerZDepth, drawerChildren, drawerHeaderChildren, drawerTransitionDuration, toolbarId, toolbarTitle, toolbarTitleMenu, toolbarTitleStyle, toolbarTitleClassName, toolbarActions, toolbarProminent, toolbarProminentTitle, toolbarThemeType, toolbarSingleColor, toolbarChildren, toolbarZDepth, mobileDrawerType: mobileType, tabletDrawerType: tabletType, desktopDrawerType: desktopType, transitionName, transitionEnterTimeout, transitionLeaveTimeout, extractMini, miniDrawerHeader, miniDrawerChildren, footer, includeDrawerHeader, contentId, contentProps, constantDrawerType, temporaryIcon, // deprecated temporaryIconChildren, temporaryIconClassName, menuIconChildren, menuIconClassName, /* eslint-disable no-unused-vars */ drawerType: propDrawerType, drawerHeader: propDrawerHeader, renderNode: propRenderNode, jumpLabel, persistentIcon, // deprecated onDrawerChange, closeIconChildren, closeIconClassName, persistentIconChildren, persistentIconClassName, /* eslint-enable no-unused-vars */ ...props } = this.props; let { drawerHeader } = this.props; const { desktop, tablet, contentActive } = this.state; const drawerType = getField(this.props, this.state, 'drawerType'); const visible = getField(this.props, this.state, 'visible'); const renderNode = getField(this.props, this.context, 'renderNode'); const mini = isMini(drawerType); const temporary = isTemporary(drawerType); const persistent = isPersistent(drawerType); const clipped = drawerType === DrawerTypes.CLIPPED; const floating = drawerType === DrawerTypes.FLOATING; const offset = (desktop || tablet ? !temporary && visible : visible); const toolbarRelative = cn({ 'md-toolbar-relative': !toolbarProminent && !toolbarProminentTitle, 'md-toolbar-relative--prominent': toolbarProminent || toolbarProminentTitle, }); let nav; if (temporary || persistent) { nav = ( <Button key="nav" onClick={this._toggleVisibility} disabled={persistent && visible} icon iconEl={getDeprecatedIcon( menuIconClassName || temporaryIconClassName, menuIconChildren || temporaryIconChildren, temporaryIcon )} /> ); } let closeButton; if (persistent) { closeButton = <CloseButton />; } if (!drawerHeader && includeDrawerHeader) { drawerHeader = ( <Toolbar key="drawer-header" title={drawerTitle} actions={visible && nav ? closeButton : null} className={cn('md-divider-border md-divider-border--bottom', { [toolbarRelative]: clipped || floating, })} > {drawerHeaderChildren} <JumpToContentLink /> </Toolbar> ); } let miniDrawer; if (mini) { let miniList; if (extractMini) { miniList = ( <List id={miniNavItemsId} key="mini-nav-items" style={miniNavStyle} className={cn(miniNavClassName, toolbarRelative)} > {navItems.map(toMiniListItem)} </List> ); } miniDrawer = ( <Drawer id={miniDrawerId} key="mini-drawer" type={drawerType} renderNode={renderNode} aria-hidden={visible} style={miniDrawerStyle} className={miniDrawerClassName} > {miniDrawerHeader} {miniList} {miniDrawerChildren} </Drawer> ); } const desktopOffset = !clipped && !floating && offset; return ( <div id={id} style={style} className={className}> <Toolbar id={toolbarId} colored={toolbarThemeType === 'colored'} themed={toolbarThemeType === 'themed'} singleColor={toolbarSingleColor} style={toolbarStyle} className={cn({ 'md-toolbar--over-drawer': clipped || floating || (mini && !visible), }, toolbarClassName)} title={toolbarTitle} titleMenu={toolbarTitleMenu} prominent={toolbarProminent} prominentTitle={toolbarProminentTitle} titleStyle={toolbarTitleStyle} titleClassName={cn({ 'md-title--drawer-active': contentActive, 'md-transition--deceleration': offset && visible, 'md-transition--acceleration': offset && !visible, 'md-title--permanent-offset': desktopOffset && isPermanent(drawerType), 'md-title--persistent-offset': desktopOffset && persistent, }, toolbarTitleClassName)} nav={nav} actions={toolbarActions} fixed zDepth={toolbarZDepth} > {toolbarChildren} </Toolbar> {miniDrawer} <Drawer {...props} id={drawerId} constantType={constantDrawerType} transitionDuration={drawerTransitionDuration} header={drawerHeader} style={drawerStyle} className={drawerClassName} navItems={navItems} renderNode={renderNode} mobileType={mobileType} tabletType={tabletType} desktopType={desktopType} type={getNonMiniType(drawerType)} visible={visible} zDepth={drawerZDepth} onVisibilityChange={this._handleVisibility} onMediaTypeChange={this._handleTypeChange} > {drawerChildren} </Drawer> <CSSTransitionGroup {...contentProps} id={contentId} component={Content} transitionName={transitionName} transitionEnter={!!transitionEnterTimeout} transitionEnterTimeout={transitionEnterTimeout} transitionLeave={!!transitionLeaveTimeout} transitionLeaveTimeout={transitionLeaveTimeout} tabIndex={-1} style={contentStyle} className={cn('md-navigation-drawer-content', { 'md-navigation-drawer-content--active': contentActive, 'md-navigation-drawer-content--inactive': !visible, 'md-navigation-drawer-content--prominent-offset': toolbarProminent || toolbarProminentTitle, 'md-transition--deceleration': visible, 'md-transition--acceleration': !visible, 'md-drawer-relative': offset, 'md-drawer-relative--mini': mini && (!visible || temporary), }, toolbarRelative, contentClassName)} > {children} </CSSTransitionGroup> {footer} </div> ); } }
JavaScript
class Profile extends LinkParent { user() { return Meteor.users.findOne({ _id: this._id }); } checkOwnership() { return this._id === Meteor.userId(); } }
JavaScript
class S3CachePlugin { constructor(context, { key, secret }) { const { log, env } = context; this.log = log; this.key = key; this.secret = secret; const opts = !env.AWS_S3_ACCESS_KEY_ID ? {} : { region: env.AWS_S3_REGION, credentials: { accessKeyId: env.AWS_S3_ACCESS_KEY_ID, secretAccessKey: env.AWS_S3_SECRET_ACCESS_KEY, }, }; this.s3 = new S3Client(opts); } async beforeCacheAccess(cacheContext) { const { log, secret, key } = this; try { log.info('s3: read token cache', key); const res = await this.s3.send(new GetObjectCommand({ Bucket: 'helix-content-bus', Key: key, })); let data = await new Response(res.Body, {}).buffer(); if (secret) { data = decrypt(secret, data).toString('utf-8'); } cacheContext.tokenCache.deserialize(data); return true; } catch (e) { if (e.$metadata?.httpStatusCode === 404) { log.info('s3: unable to deserialize token cache: not found'); } else { log.warn('s3: unable to deserialize token cache', e); } } return false; } async afterCacheAccess(cacheContext) { if (cacheContext.cacheHasChanged) { const { log, secret, key } = this; try { log.info('s3: write token cache', key); let data = cacheContext.tokenCache.serialize(); if (secret) { data = encrypt(secret, Buffer.from(data, 'utf-8')); } await this.s3.send(new PutObjectCommand({ Bucket: 'helix-content-bus', Key: key, Body: data, ContentType: secret ? 'application/octet-stream' : 'text/plain', })); return true; } catch (e) { log.warn('s3: unable to serialize token cache', e); } } return false; } }
JavaScript
class IoMenuItem extends IoItem { static get Style() { return /* css */` :host { display: flex; flex: 0 0 auto; flex-direction: row; border-radius: 0; } :host > * { pointer-events: none; } :host > :empty { display: none; } :host > :not(:empty) { padding: 0 var(--io-spacing); } :host > io-icon { width: var(--io-line-height); height: var(--io-line-height); margin-right: var(--io-spacing); } :host > .io-menu-label { flex: 1 1 auto; text-overflow: ellipsis; } :host > .io-menu-hint { opacity: 0.25; } :host[hasmore][direction="up"]:after { content: '\\25B4'; margin-left: 0.5em; } :host[hasmore][direction="right"]:after { content: '\\25B8'; margin-left: 0.5em; } :host[hasmore][direction="bottom"]:after { content: '\\25BE'; margin-left: 0.5em; } :host[hasmore][direction="left"]:before { content: '\\25C2'; margin-right: 0.5em; } :host[selected][direction="top"], :host[selected][direction="bottom"] { border-bottom-color: var(--io-color-link); } :host[selected][direction="right"], :host[selected][direction="left"] { border-left-color: var(--io-color-link); } `; } static get Properties() { return { option: { type: Item, strict: true, }, expanded: { value: false, reflect: 1, }, direction: { value: 'bottom', reflect: 1, }, icon: String, $parent: null, $options: null, depth: Infinity, lazy: true, }; } static get Listeners() { return { 'click': 'preventDefault', }; } preventDefault(event) { event.stopPropagation(); event.preventDefault(); } get hasmore() { return this.option.hasmore && this.depth > 0; } get inlayer() { return this.$parent && this.$parent.inlayer; } connectedCallback() { super.connectedCallback(); if (this.$options) Layer.appendChild(this.$options); if (!this.inlayer) Layer.addEventListener('pointermove', this._onLayerPointermove); if (!this.inlayer) Layer.addEventListener('pointerup', this._onLayerPointerup); } disconnectedCallback() { super.disconnectedCallback(); if (this.$options && this.$options.inlayer) Layer.removeChild(this.$options); Layer.removeEventListener('pointermove', this._onLayerPointermove); Layer.removeEventListener('pointerup', this._onLayerPointerup); } _onClick() { const option = this.option; if (this.hasmore) { if (!this.expanded) this.expanded = true; } else if (option.select === 'toggle') { option.selected = !option.selected; } else { if (option.action) { option.action.apply(null, [option.value]); } if (option.select === 'pick') { if (option.hasmore && this.depth <= 0) { option.options.selectDefault(); } else { option.selected = true; } } this.dispatchEvent('item-clicked', option, true); this.requestAnimationFrameOnce(this._collapse); } } _onItemClicked(event) { const item = event.composedPath()[0]; if (item !== this) { event.stopImmediatePropagation(); this.dispatchEvent('item-clicked', event.detail, true); } if (this.expanded) this.requestAnimationFrameOnce(this._collapse); } _onPointerdown(event) { event.stopPropagation(); event.preventDefault(); // Prevents focus this.setPointerCapture(event.pointerId); this.addEventListener('pointermove', this._onPointermove); this.addEventListener('pointerup', this._onPointerup); if (this.expanded || event.pointerType === 'mouse' || this.inlayer) { this.focus(); if (this.option.options) this.expanded = true; } hovered = this; hoveredParent = this.parentElement; // TODO: Safari temp fix for event.movement = 0 this._x = event.clientX; this._y = event.clientY; } _onPointermove(event) { event.stopPropagation(); if (!this.expanded && event.pointerType === 'touch' && !this.inlayer) return; const clipped = !!this.$parent && !!this.$parent.style.height; if (event.pointerType === 'touch' && clipped) return; // TODO: Safari temp fix for event.movement = 0 const movementX = event.clientX - this._x; const movementY = event.clientY - this._y; this._x = event.clientX; this._y = event.clientY; Layer.x = event.clientX; Layer.y = event.clientY; clearTimeout(this.__timeoutOpen); hovered = this._gethovered(event); if (hovered) { const v = Math.abs(movementY) - Math.abs(movementX); const h = hovered.parentElement.horizontal; if (hoveredParent !== hovered.parentElement) { hoveredParent = hovered.parentElement; this._expandHovered(); } else if (h ? v < -0.5 : v > 0.5) { this._expandHovered(); } else { this.__timeoutOpen = setTimeout(() => { this._expandHovered(); }, 100); } } } _gethovered(event) { const items = getElementDescendants(getRootElement(this)); for (let i = items.length; i--;) { if (isPointerAboveItem(event, items[i])) return items[i]; } } _expandHovered() { if (hovered) { hovered.focus(); if (hovered.hasmore) { if (hovered.$options) { const descendants = getElementDescendants(hovered.$options); for (let i = descendants.length; i--;) { descendants[i].expanded = false; } } hovered.expanded = true; } } } _onLayerPointermove(event) { if (this.expanded) this._onPointermove(event); } _onLayerPointerup(event) { if (this.expanded) this._onPointerup(event); } _onPointerup(event) { event.stopPropagation(); this.removeEventListener('pointermove', this._onPointermove); this.removeEventListener('pointerup', this._onPointerup); const item = this._gethovered(event); if (item) { item.focus(); item._onClick(event); } else { this.requestAnimationFrameOnce(this._collapseRoot); } } _onKeydown(event) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); this._onClick(event); return; } else if (event.key === 'Escape') { event.preventDefault(); this.requestAnimationFrameOnce(this._collapseRoot); return; } let command = ''; if (this.direction === 'left' || this.direction === 'right') { if (event.key === 'ArrowUp') command = 'prev'; if (event.key === 'ArrowRight') command = 'in'; if (event.key === 'ArrowDown') command = 'next'; if (event.key === 'ArrowLeft') command = 'out'; } else { if (event.key === 'ArrowUp') command = 'out'; if (event.key === 'ArrowRight') command = 'next'; if (event.key === 'ArrowDown') command = 'in'; if (event.key === 'ArrowLeft') command = 'prev'; } if (this.inlayer && event.key === 'Tab') command = 'next'; const siblings = this.$parent ? [...this.$parent.children] : []; const index = siblings.indexOf(this); if (command && (this.inlayer || this.expanded)) { event.preventDefault(); switch (command) { case 'prev': { const prev = siblings[(index + siblings.length - 1) % (siblings.length)]; this.expanded = false; if (prev) { if (prev.hasmore) prev.expanded = true; prev.focus(); } break; } case 'next': { const next = siblings[(index + 1) % (siblings.length)]; this.expanded = false; if (next) { if (next.hasmore) next.expanded = true; next.focus(); } break; } case 'in': if (this.$options && this.$options.children.length) this.$options.children[0].focus(); break; case 'out': this.expanded = false; if (this.$parent && this.$parent.$parent) { this.$parent.$parent.focus(); } break; default: break; } } else { super._onKeydown(event); } } _collapse() { this.expanded = false; } _collapseRoot() { getRootElement(this).expanded = false; } expandedChanged() { if (!this.$options) this.$options = new IoMenuOptions(); if (this.expanded && this.depth > 0) { if (this.$options.parentElement !== Layer) Layer.appendChild(this.$options); const $allitems = getElementDescendants(getRootElement(this)); const $ancestoritems = getElementAncestors(this); for (let i = $allitems.length; i--;) { if ($ancestoritems.indexOf($allitems[i]) === -1) { $allitems[i].expanded = false; } } const $descendants = getElementDescendants(this.$options); for (let i = $descendants.length; i--;) { $descendants[i].expanded = false; } this.$options.addEventListener('item-clicked', this._onItemClicked); } else { const $descendants = getElementDescendants(this); for (let i = $descendants.length; i--;) { $descendants[i].expanded = false; } this.$options.removeEventListener('item-clicked', this._onItemClicked); } } optionChanged(event) { if (event.detail.oldValue) { event.detail.oldValue.removeEventListener('changed', this.onOptionChanged); } if (event.detail.value) { event.detail.value.addEventListener('changed', this.onOptionChanged); } } onOptionChanged() { this.changed(); } changed() { const option = this.option; if (option === undefined) { console.log(this); } const icon = this.icon || option.icon; this.setAttribute('selected', option.selected); this.setAttribute('hasmore', this.hasmore); this.template([ icon ? ['io-icon', {icon: icon}] : null, ['span', {class: 'io-menu-label'}, option.label], ['span', {class: 'io-menu-hint'}, option.hint], ]); if (this.$options) { this.$options.setProperties({ $parent: this, depth: this.depth - 1, expanded: this.bind('expanded'), options: option.options, position: this.direction, }); } } }