text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { auth, host } from '../main'; import { i18n } from '../model/i18n'; import { Utils, _, __ } from '../helpers/utils'; import { Doc, DocType } from '../model/doc'; import { strings } from '../model/strings'; import { PBICloudDataset, PBICloudDatasetConnectionMode, PBICloudDatasetEndorsement } from '../model/pbi-dataset'; import { Tabulator } from 'tabulator-tables'; import { Loader } from '../helpers/loader'; import { ContextMenu } from '../helpers/contextmenu'; import { ConnectMenuItem } from './connect-item'; import * as sanitizeHtml from 'sanitize-html'; import { AppError } from '../model/exceptions'; import { PowerBISignin } from './powerbi-signin'; import { DialogResponse } from './dialog'; export class ConnectRemote extends ConnectMenuItem { table: Tabulator; showUnsupported = false; listElement: HTMLElement; searchBox: HTMLInputElement; render(element: HTMLElement) { super.render(element); let html = ` <div class="list"> </div> `; this.element.insertAdjacentHTML("beforeend", html); this.listElement = _(".list", this.element); if (!auth.signedIn) { this.listElement.innerHTML = ` <div class="quick-signin notice"> <div> <p>${i18n(strings.errorNotConnected)}</p> <div class="signin button">${i18n(strings.signIn)}</div> </div> </div> `; _(".signin", this.element).addEventListener("click", e => { e.preventDefault(); let button = <HTMLHtmlElement>e.currentTarget; button.toggleAttr("disabled", true); let signinDialog = new PowerBISignin(); signinDialog.show() .then((response: DialogResponse) => { if (response.action == "signin") this.getRemoteDatasets(); }) .catch(ignore => {}) .finally(()=>{ button.toggleAttr("disabled", false); }); }); } else { this.getRemoteDatasets(); } } renderTable(id: string, datasets: PBICloudDataset[]) { let unopenedDatasets = datasets.filter(dataset => (this.dialog.openDocIds.indexOf(Doc.getId(DocType.dataset, dataset)) == -1)); if (!unopenedDatasets.length) { this.renderError(this.listElement, i18n(strings.errorDatasetsEmptyListing)); return; } if (this.table) { this.table.setData(unopenedDatasets); } else { this.table = new Tabulator(`#${id}`, { //renderVerticalBuffer: 500, maxHeight: "100%", layout: "fitColumns", //initialFilter: dataset => this.unsupportedFilter(dataset), initialSort:[ {column: "name", dir: "asc"}, ], rowFormatter: row => { try { //Bypass calc rows if ((<any>row)._row && (<any>row)._row.type == "calc") return; const dataset = <PBICloudDataset>row.getData(); if (dataset.connectionMode != PBICloudDatasetConnectionMode.Supported) { let element = row.getElement(); element.classList.add("row-disabled"); } }catch(ignore){} }, columns: [ { //field: "Icon", title: "", hozAlign:"center", resizable: false, width: 40, cssClass: "column-icon", formatter: (cell) => { const dataset = <PBICloudDataset>cell.getData(); let icon = (dataset.connectionMode == PBICloudDatasetConnectionMode.Supported ? "dataset" : "alert"); let tooltip = (dataset.connectionMode != PBICloudDatasetConnectionMode.Supported ? i18n((<any>strings)[`errorDatasetConnection${PBICloudDatasetConnectionMode[dataset.connectionMode]}`]) : ""); return `<div class="icon-${icon}" title="${tooltip}"></div>`; }, sorter: (a, b, aRow, bRow, column, dir, sorterParams) => { const datasetA = <PBICloudDataset>aRow.getData(); const datasetB = <PBICloudDataset>bRow.getData(); a = `${datasetA.connectionMode == PBICloudDatasetConnectionMode.Supported ? "_" : ""}${datasetA.name}`; b = `${datasetB.connectionMode == PBICloudDatasetConnectionMode.Supported ? "_" : ""}${datasetB.name}`; return String(a).toLowerCase().localeCompare(String(b).toLowerCase()); } }, { field: "name", title: i18n(strings.connectDatasetsTableNameCol), }, { field: "endorsement", width: 125, title: i18n(strings.connectDatasetsTableEndorsementCol), formatter: (cell) => { let dataset = <PBICloudDataset>cell.getData(); return (!dataset.endorsement || dataset.endorsement == PBICloudDatasetEndorsement.None ? '' : `<span class="endorsement-badge icon-${dataset.endorsement.toLowerCase()}">${dataset.endorsement}</span>`); }, sorter: (a, b, aRow, bRow, column, dir, sorterParams) => { const datasetA = <PBICloudDataset>aRow.getData(); const datasetB = <PBICloudDataset>bRow.getData(); a = `${(!datasetA.endorsement || datasetA.endorsement == PBICloudDatasetEndorsement.None ? "zzz": datasetA.endorsement)}_${datasetA.name}`; b = `${(!datasetB.endorsement || datasetB.endorsement == PBICloudDatasetEndorsement.None ? "zzz": datasetB.endorsement)}_${datasetB.name}`; return String(a).toLowerCase().localeCompare(String(b).toLowerCase()); } }, { field: "owner", width: 100, title: i18n(strings.connectDatasetsTableOwnerCol), cssClass: "column-owner", }, { field: "workspaceName", title: i18n(strings.connectDatasetsTableWorkspaceCol) }, ], data: unopenedDatasets }); this.table.on("rowClick", (e, row) => { this.deselectRows(); let dataset = <PBICloudDataset>row.getData(); this.dialog.data.doc = new Doc(dataset.name, DocType.dataset, dataset); let rowElement = row.getElement(); rowElement.classList.add("row-active"); this.dialog.okButton.toggleAttr("disabled", false); }); this.table.on("rowDblClick", (e, row) => { this.dialog.trigger("action", "ok"); }); } } deselectRows() { this.dialog.data.doc = null; __(".tabulator-row.row-active", this.element).forEach((el: HTMLElement) => { el.classList.remove("row-active"); }); this.dialog.okButton.toggleAttr("disabled", true); } appear() { this.dialog.okButton.toggle(true); // Use timeout to avoid animation interfering with selection window.setTimeout(()=>{ this.deselectRows(); if (this.table) this.table.redraw(true); }, 0); } applyFilters() { if (this.table) { this.table.clearFilter(); //this.table.addFilter(dataset => this.unsupportedFilter(dataset)); if (this.searchBox.value) this.table.addFilter("name", "like", sanitizeHtml(this.searchBox.value, { allowedTags: [], allowedAttributes: {}})); } } /*unsupportedFilter(dataset: PBICloudDataset) { if (dataset.connectionMode != PBICloudDatasetConnectionMode.Supported && !this.showUnsupported) return false; return true; }*/ getRemoteDatasets() { let loader = new Loader(this.listElement, false); host.listDatasets() .then((datasets: PBICloudDataset[]) => { let tableId = Utils.DOM.uniqueId(); let html = ` ${datasets.length ? ` <div class="toolbar"> <div class="search"> <input type="search" placeholder="${i18n(strings.searchDatasetPlaceholder)}"> </div> <div class="refresh ctrl icon-refresh" title="${i18n(strings.refreshCtrlTitle)}"></div> </div> ` : ""} <div id="${ tableId }"></div> `; /* <div class="filters"> <label class="switch"><input type="checkbox" id="show-unsupported-datasets" ${this.showUnsupported ? "": "checked"}><span class="slider"></span></label> <label for="show-unsupported-datasets">${i18n(strings.hideUnsupportedCtrlTitle)}</label> </div> */ /* */ this.listElement.innerHTML = html; this.searchBox = <HTMLInputElement>_(".search input", this.element); ["keyup", "search", "paste"].forEach(listener => { this.searchBox.addEventListener(listener, e => { this.applyFilters(); }); }); this.searchBox.addEventListener('contextmenu', e => { e.preventDefault(); let el = <HTMLInputElement>e.currentTarget; let selection = el.value.substring(el.selectionStart, el.selectionEnd); ContextMenu.editorContextMenu(e, selection, el.value, el); }); _("#show-unsupported-datasets", this.element).addEventListener("change", e => { e.preventDefault(); this.showUnsupported = !(<HTMLInputElement>e.currentTarget).checked; this.applyFilters(); }); _(".refresh", this.element).addEventListener("click", e => { e.preventDefault(); this.tableDestroy(); this.getRemoteDatasets(); }); if (datasets.length) { this.renderTable(tableId, datasets); } else { this.renderError(this.listElement, i18n(strings.errorDatasetsEmptyListing)); } }) .catch((error: AppError) => { this.renderError(this.listElement, error.toString(), true, ()=>{ this.getRemoteDatasets(); }); }) .finally(() => { loader.remove(); }); } tableDestroy() { if (this.table) { this.table.destroy(); this.table = null; } } destroy() { this.tableDestroy(); super.destroy(); } }
the_stack
import type { Server } from "http"; import type { Server as SecureServer } from "https"; import { Optional } from "typescript-optional"; import type { Express } from "express"; import OAS from "../../json/openapi.json"; import { Secp256k1Keys, Logger, Checks, LoggerProvider, JsObjectSigner, IJsObjectSignerOptions, } from "@hyperledger/cactus-common"; import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { initiateTransfer } from "./common/initiate-transfer-helper"; import { ICactusPlugin, IPluginWebService, IWebServiceEndpoint, Configuration, } from "@hyperledger/cactus-core-api"; import { CommitFinalV1Request, CommitFinalV1Response, CommitPreparationV1Request, CommitPreparationV1Response, TransferInitializationV1Request, TransferInitializationV1Response, LockEvidenceV1Request, LockEvidenceV1Response, SendClientV1Request, TransferCommenceV1Request, TransferCommenceV1Response, TransferCompleteV1Request, DefaultApi as OdapApi, SessionData, TransferCompleteV1Response, } from "../generated/openapi/typescript-axios"; import { SHA256 } from "crypto-js"; import secp256k1 from "secp256k1"; import { CommitFinalEndpointV1 } from "../web-services/commit-final-endpoint"; import { CommitPrepareEndpointV1 } from "../web-services/commite-prepare-endpoint"; import { LockEvidenceEndpointV1 } from "../web-services/lock-evidence-endpoint"; import { LockEvidencePrepareEndpointV1 } from "../web-services/lock-evidence-transfer-commence-endpoint"; import { TransferCompleteEndpointV1 } from "../web-services/transfer-complete"; import { TransferInitiationEndpointV1 } from "../web-services/transfer-initiation-endpoint"; import { SendClientRequestEndpointV1 } from "../web-services/send-client-request"; import { PluginRegistry } from "@hyperledger/cactus-core"; import { DefaultApi as FabricApi, FabricContractInvocationType, FabricSigningCredential, RunTransactionRequest as FabricRunTransactionRequest, } from "@hyperledger/cactus-plugin-ledger-connector-fabric"; import { DefaultApi as BesuApi, Web3SigningCredential, EthContractInvocationType, InvokeContractV1Request as BesuInvokeContractV1Request, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; import { lockEvidence, lockEvidenceTransferCommence, } from "./common/lock-evidence-helper"; import { CommitFinal, CommitPrepare } from "./common/commit-helper"; import { TransferComplete } from "./common/transfer-complete-helper"; /*const log = LoggerProvider.getOrCreate({ level: "INFO", label: "odap-logger", });*/ export interface OdapGatewayConstructorOptions { name: string; dltIDs: string[]; instanceId: string; ipfsPath?: string; fabricPath?: string; besuPath?: string; fabricSigningCredential?: FabricSigningCredential; fabricChannelName?: string; fabricContractName?: string; besuContractName?: string; besuWeb3SigningCredential?: Web3SigningCredential; besuKeychainId?: string; fabricAssetID?: string; besuAssetID?: string; } export interface OdapGatewayKeyPairs { publicKey: Uint8Array; privateKey: Uint8Array; } interface OdapHermesLog { phase: string; step: string; operation: string; nodes: string; } export class OdapGateway implements ICactusPlugin, IPluginWebService { name: string; sessions: Map<string, SessionData>; pubKey: string; privKey: string; public static readonly CLASS_NAME = "OdapGateWay"; private readonly log: Logger; private readonly instanceId: string; public ipfsApi?: ObjectStoreIpfsApi; public fabricApi?: FabricApi; public besuApi?: BesuApi; public pluginRegistry: PluginRegistry; private endpoints: IWebServiceEndpoint[] | undefined; //map[]object, object refer to a state //of a specific comminications public supportedDltIDs: string[]; private odapSigner: JsObjectSigner; public fabricAssetLocked: boolean; public fabricAssetDeleted: boolean; public besuAssetCreated: boolean; public fabricSigningCredential?: FabricSigningCredential; public fabricChannelName?: string; public fabricContractName?: string; public besuContractName?: string; public besuWeb3SigningCredential?: Web3SigningCredential; public besuKeychainId?: string; public fabricAssetID?: string; public besuAssetID?: string; public constructor(options: OdapGatewayConstructorOptions) { const fnTag = `${this.className}#constructor()`; Checks.truthy(options, `${fnTag} arg options`); Checks.truthy(options.instanceId, `${fnTag} arg options.instanceId`); Checks.nonBlankString(options.instanceId, `${fnTag} options.instanceId`); const level = "INFO"; const label = this.className; this.log = LoggerProvider.getOrCreate({ level, label }); this.instanceId = options.instanceId; this.name = options.name; this.supportedDltIDs = options.dltIDs; this.sessions = new Map(); const keyPairs: OdapGatewayKeyPairs = Secp256k1Keys.generateKeyPairsBuffer(); this.pubKey = this.bufArray2HexStr(keyPairs.publicKey); this.privKey = this.bufArray2HexStr(keyPairs.privateKey); const odapSignerOptions: IJsObjectSignerOptions = { privateKey: this.privKey, signatureFunc: this.odapSignatureFunc, logLevel: "debug", }; this.odapSigner = new JsObjectSigner(odapSignerOptions); this.fabricAssetDeleted = false; this.fabricAssetLocked = false; this.besuAssetCreated = false; this.pluginRegistry = new PluginRegistry(); if (options.ipfsPath != undefined) { { const config = new Configuration({ basePath: options.ipfsPath }); const apiClient = new ObjectStoreIpfsApi(config); this.ipfsApi = apiClient; } } if (options.fabricPath != undefined) { { const config = new Configuration({ basePath: options.fabricPath }); const apiClient = new FabricApi(config); this.fabricApi = apiClient; const notEnoughFabricParams: boolean = options.fabricSigningCredential == undefined || options.fabricChannelName == undefined || options.fabricContractName == undefined || options.fabricAssetID == undefined; if (notEnoughFabricParams) { throw new Error( `${fnTag}, fabric params missing should have: signing credentials, contract name, channel name, asset ID`, ); } this.fabricSigningCredential = options.fabricSigningCredential; this.fabricChannelName = options.fabricChannelName; this.fabricContractName = options.fabricContractName; this.fabricAssetID = options.fabricAssetID; } } if (options.besuPath != undefined) { const config = new Configuration({ basePath: options.besuPath }); const apiClient = new BesuApi(config); this.besuApi = apiClient; const notEnoughBesuParams: boolean = options.besuContractName == undefined || options.besuWeb3SigningCredential == undefined || options.besuKeychainId == undefined || options.besuAssetID == undefined; if (notEnoughBesuParams) { throw new Error( `${fnTag}, besu params missing should have: signing credentials, contract name, key chain ID, asset ID`, ); } this.besuContractName = options.besuContractName; this.besuWeb3SigningCredential = options.besuWeb3SigningCredential; this.besuKeychainId = options.besuKeychainId; this.besuAssetID = options.besuAssetID; } } public async Revert(sessionID: string): Promise<void> { const sessionData = this.sessions.get(sessionID); if (sessionData == undefined) return; if ( sessionData.isFabricAssetDeleted != undefined && sessionData.isFabricAssetDeleted ) { if (this.fabricApi == undefined) return; await this.fabricApi.runTransactionV1({ signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: this.fabricContractName, invocationType: FabricContractInvocationType.Send, methodName: "CreateAsset", params: [sessionData.fabricAssetID, sessionData.fabricAssetSize], } as FabricRunTransactionRequest); } else if ( sessionData.isFabricAssetLocked != undefined && sessionData.isFabricAssetLocked ) { if (this.fabricApi == undefined) return; await this.fabricApi.runTransactionV1({ signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: this.fabricContractName, invocationType: FabricContractInvocationType.Send, methodName: "UnLockAsset", params: [sessionData.fabricAssetID], } as FabricRunTransactionRequest); } else if ( sessionData.isFabricAssetCreated != undefined && sessionData.isFabricAssetCreated ) { if (this.fabricApi == undefined) return; await this.fabricApi.runTransactionV1({ signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: this.fabricContractName, invocationType: FabricContractInvocationType.Send, methodName: "CreateAsset", params: [sessionData.fabricAssetID], } as FabricRunTransactionRequest); } else if ( sessionData.isBesuAssetCreated != undefined && sessionData.isBesuAssetCreated ) { if (this.besuApi == undefined) return; await this.besuApi.invokeContractV1({ contractName: this.besuContractName, invocationType: EthContractInvocationType.Send, methodName: "deleteAsset", gas: 1000000, params: [this.besuAssetID], signingCredential: this.besuWeb3SigningCredential, keychainId: this.besuKeychainId, } as BesuInvokeContractV1Request); } else if ( sessionData.isBesuAssetDeleted != undefined && sessionData.isBesuAssetDeleted ) { if (this.besuApi == undefined) return; await this.besuApi.invokeContractV1({ contractName: this.besuContractName, invocationType: EthContractInvocationType.Send, methodName: "createAsset", gas: 1000000, params: [this.besuAssetID], signingCredential: this.besuWeb3SigningCredential, keychainId: this.besuKeychainId, } as BesuInvokeContractV1Request); } else if ( sessionData.isBesuAssetLocked != undefined && sessionData.isBesuAssetLocked ) { if (this.besuApi == undefined) return; await this.besuApi.invokeContractV1({ contractName: this.besuContractName, invocationType: EthContractInvocationType.Send, methodName: "unLockAsset", gas: 1000000, params: [this.besuAssetID], signingCredential: this.besuWeb3SigningCredential, keychainId: this.besuKeychainId, } as BesuInvokeContractV1Request); } return; } public get className(): string { return OdapGateway.CLASS_NAME; } public getOpenApiSpec(): unknown { return OAS; } /*public getAspect(): PluginAspect { return PluginAspect.WEB_SERVICE; }*/ public async onPluginInit(): Promise<unknown> { return; } async registerWebServices(app: Express): Promise<IWebServiceEndpoint[]> { const webServices = await this.getOrCreateWebServices(); await Promise.all(webServices.map((ws) => ws.registerExpress(app))); return webServices; } public async getOrCreateWebServices(): Promise<IWebServiceEndpoint[]> { if (Array.isArray(this.endpoints)) { return this.endpoints; } const transferinitiation = new TransferInitiationEndpointV1({ gateway: this, }); const lockEvidencePreparation = new LockEvidencePrepareEndpointV1({ gateway: this, }); const lockEvidence = new LockEvidenceEndpointV1({ gateway: this }); const commitPreparation = new CommitPrepareEndpointV1({ gateway: this, }); const commitFinal = new CommitFinalEndpointV1({ gateway: this }); const transferComplete = new TransferCompleteEndpointV1({ gateway: this, }); const sendClientrequest = new SendClientRequestEndpointV1({ gateway: this, }); this.endpoints = [ transferinitiation, lockEvidencePreparation, lockEvidence, commitPreparation, commitFinal, transferComplete, sendClientrequest, ]; return this.endpoints; } public getHttpServer(): Optional<Server | SecureServer> { return Optional.empty(); } public async shutdown(): Promise<void> { this.log.info(`Shutting down ${this.className}...`); } public getInstanceId(): string { return this.instanceId; } public getPackageName(): string { return "@hyperledger/cactus-odap-odap-gateway-business-logic-plugin"; } public async odapGatewaySign(msg: string): Promise<Uint8Array> { return this.odapSigner.sign(msg); } // eslint-disable-next-line @typescript-eslint/no-explicit-any public odapSignatureFunc(msg: any, pkey: any): any { const signature = secp256k1.ecdsaSign( new Uint8Array(Buffer.from(SHA256(msg).toString(), `hex`)), Buffer.from(pkey, `hex`), ).signature; return signature; } public async sign(msg: string, privKey: string): Promise<string> { const signature = secp256k1.ecdsaSign( new Uint8Array(Buffer.from(SHA256(msg).toString(), `hex`)), Buffer.from(privKey, `hex`), ).signature; return this.bufArray2HexStr(signature); } public bufArray2HexStr(array: Uint8Array): string { return Buffer.from(array).toString("hex"); } public async publishOdapProof(ID: string, proof: string): Promise<void> { if (this.ipfsApi == undefined) return; const res = await this.ipfsApi.setObjectV1({ key: ID, value: proof, }); const resStatusOk = res.status > 199 && res.status < 300; if (!resStatusOk) { throw new Error("${fnTag}, error when logging to ipfs"); } } public async odapLog( odapHermesLog: OdapHermesLog, ID: string, ): Promise<void> { this.log.info( `<${odapHermesLog.phase}, ${odapHermesLog.step}, ${odapHermesLog.operation}, ${odapHermesLog.nodes}>`, ); if (this.ipfsApi == undefined) return; const res = await this.ipfsApi.setObjectV1({ key: ID, value: `${odapHermesLog.phase}, ${odapHermesLog.phase}, ${odapHermesLog.operation}, ${odapHermesLog.nodes}`, }); const resStatusOk = res.status > 199 && res.status < 300; if (!resStatusOk) { throw new Error("${fnTag}, error when logging to ipfs"); } } public async initiateTransfer( req: TransferInitializationV1Request, ): Promise<TransferInitializationV1Response> { const fnTag = `${this.className}#InitiateTransfer()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const initiateTransferResponse = await initiateTransfer(req, this); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); return initiateTransferResponse; } public async lockEvidenceTransferCommence( req: TransferCommenceV1Request, ): Promise<TransferCommenceV1Response> { const fnTag = `${this.className}#TransferCommence()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const TransferCommenceResponse = await lockEvidenceTransferCommence( req, this, ); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); return TransferCommenceResponse; } public async lockEvidence( req: LockEvidenceV1Request, ): Promise<LockEvidenceV1Response> { const fnTag = `${this.className}#LockEvidence()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const lockEvidenceResponse = await lockEvidence(req, this); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); return lockEvidenceResponse; } public async CommitPrepare( req: CommitPreparationV1Request, ): Promise<CommitPreparationV1Response> { const fnTag = `${this.className}#CommitPrepare()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const commitPrepare = await CommitPrepare(req, this); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); return commitPrepare; } public async CommitFinal( req: CommitFinalV1Request, ): Promise<CommitFinalV1Response> { const fnTag = `${this.className}#CommitFinal()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const commitFinal = await CommitFinal(req, this); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); return commitFinal; } public async TransferComplete( req: TransferCompleteV1Request, ): Promise<TransferCompleteV1Response> { const fnTag = `${this.className}#transferCompleteRequest()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const transferComplete = await TransferComplete(req, this); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); return transferComplete; } public async SendClientRequest(req: SendClientV1Request): Promise<void> { const fnTag = `${this.className}#sendClientRequest()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); const odapServerApiConfig = new Configuration({ basePath: req.serverGatewayConfiguration.apiHost, }); const odapServerApiClient = new OdapApi(odapServerApiConfig); const initializationRequestMessage: TransferInitializationV1Request = { version: req.version, loggingProfile: req.loggingProfile, accessControlProfile: req.accessControlProfile, applicationProfile: req.applicationProfile, payloadProfile: req.payLoadProfile, initializationRequestMessageSignature: "", sourceGatewayPubkey: this.pubKey, sourceGateWayDltSystem: req.sourceGateWayDltSystem, recipientGateWayPubkey: req.recipientGateWayPubkey, recipientGateWayDltSystem: req.recipientGateWayDltSystem, }; initializationRequestMessage.initializationRequestMessageSignature = ""; this.log.info("trying to create signature"); const initializeReqSignature = await this.odapGatewaySign( JSON.stringify(initializationRequestMessage), ); this.log.info("finish to create signature"); initializationRequestMessage.initializationRequestMessageSignature = this.bufArray2HexStr( initializeReqSignature, ); this.log.info(`${fnTag}, send initial transfer req, time: ${Date.now()}`); const transferInitiationRes = await odapServerApiClient.phase1TransferInitiationV1( initializationRequestMessage, ); this.log.info( `${fnTag}, receive initial transfer ack, time: ${Date.now()}`, ); const initializeReqAck: TransferInitializationV1Response = transferInitiationRes.data; if (transferInitiationRes.status != 200) { throw new Error(`${fnTag}, send transfer initiation failed`); } const serverIdentityPubkey = transferInitiationRes.data.serverIdentityPubkey; initializationRequestMessage.initializationRequestMessageSignature = this.bufArray2HexStr( initializeReqSignature, ); const initializationMsgHash = SHA256( JSON.stringify(initializationRequestMessage), ).toString(); if (initializeReqAck.initialRequestMessageHash != initializationMsgHash) { throw new Error( `${fnTag}, initial message hash not match from initial message ack`, ); } const sessionID = initializeReqAck.sessionID; const sessionData: SessionData = {}; sessionData.step = 0; await this.odapLog( { phase: "initiateTransfer", operation: "receive-ack", step: sessionData.step.toString(), nodes: `${serverIdentityPubkey}->${this.pubKey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; const hashAssetProfile = SHA256( JSON.stringify(req.assetProfile), ).toString(); const transferCommenceReq: TransferCommenceV1Request = { sessionID: sessionID, messageType: "urn:ietf:odap:msgtype:transfer-commence-msg", originatorPubkey: req.originatorPubkey, beneficiaryPubkey: req.beneficiaryPubkey, clientIdentityPubkey: this.pubKey, serverIdentityPubkey: serverIdentityPubkey, hashPrevMessage: initializationMsgHash, hashAssetProfile: hashAssetProfile, senderDltSystem: req.clientDltSystem, recipientDltSystem: req.recipientGateWayDltSystem, clientSignature: "", }; const transferCommenceReqSignature = await this.odapGatewaySign( JSON.stringify(transferCommenceReq), ); transferCommenceReq.clientSignature = this.bufArray2HexStr( transferCommenceReqSignature, ); const transferCommenceReqHash = SHA256( JSON.stringify(transferCommenceReq), ).toString(); await this.odapLog( { phase: "transfer-commence", operation: "send-req", step: sessionData.step.toString(), nodes: `${this.pubKey}->${serverIdentityPubkey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; this.log.info(`${fnTag}, send transfer commence req, time: ${Date.now()}`); const transferCommenceRes = await odapServerApiClient.phase2TransferCommenceV1( transferCommenceReq, ); this.log.info( `${fnTag}, receive transfer commence ack, time: ${Date.now()}`, ); if (transferCommenceRes.status != 200) { await this.Revert(sessionID); throw new Error(`${fnTag}, send transfer commence failed`); } const transferCommenceAck: TransferCommenceV1Response = transferCommenceRes.data; if (transferCommenceReqHash != transferCommenceAck.hashCommenceRequest) { await this.Revert(sessionID); throw new Error( `${fnTag}, transfer commence req hash not match from transfer commence ack`, ); } if ( transferCommenceReq.serverIdentityPubkey != transferCommenceAck.serverIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, serverIdentity pub key not match from transfer commence ack`, ); } if ( transferCommenceReq.clientIdentityPubkey != transferCommenceAck.clientIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, clientIdentity pub key not match from transfer commence ack`, ); } const transferCommenceAckSignature = transferCommenceAck.serverSignature; const transferCommenceAckSignatureHex = new Uint8Array( Buffer.from(transferCommenceAckSignature, "hex"), ); const sourcePubkey = new Uint8Array( Buffer.from(serverIdentityPubkey, "hex"), ); transferCommenceAck.serverSignature = ""; if ( !secp256k1.ecdsaVerify( transferCommenceAckSignatureHex, Buffer.from( SHA256(JSON.stringify(transferCommenceAck)).toString(), "hex", ), sourcePubkey, ) ) { await this.Revert(sessionID); throw new Error( `${fnTag}, transfer commence ack signature verify failed`, ); } transferCommenceAck.serverSignature = transferCommenceAckSignature; await this.odapLog( { phase: "transfer-commence", operation: "receive-ack", step: sessionData.step.toString(), nodes: `${serverIdentityPubkey}->${this.pubKey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; const commenceAckHash = SHA256( JSON.stringify(transferCommenceAck), ).toString(); this.sessions.set(sessionID, sessionData); let fabricLockAssetProof = ""; if (this.fabricApi != undefined) { const lockRes = await this.fabricApi.runTransactionV1({ signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: this.fabricContractName, invocationType: FabricContractInvocationType.Send, methodName: "LockAsset", params: [this.fabricAssetID], } as FabricRunTransactionRequest); const receiptLockRes = await this.fabricApi.getTransactionReceiptByTxIDV1( { signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: "qscc", invocationType: FabricContractInvocationType.Call, methodName: "GetBlockByTxID", params: [this.fabricChannelName, lockRes.data.transactionId], } as FabricRunTransactionRequest, ); this.log.warn(receiptLockRes.data); fabricLockAssetProof = JSON.stringify(receiptLockRes.data); if (sessionData == undefined) { await this.Revert(sessionID); throw new Error(`${fnTag}, session data undefined`); } sessionData.isFabricAssetLocked = true; } const lockEvidenceReq: LockEvidenceV1Request = { sessionID: sessionID, messageType: "urn:ietf:odap:msgtype:lock-evidence-req-msg", clientIdentityPubkey: req.clientIdentityPubkey, serverIdentityPubkey: req.serverIdentityPubkey, clientSignature: "", hashCommenceAckRequest: commenceAckHash, lockEvidenceClaim: fabricLockAssetProof, lockEvidenceExpiration: " ", }; const lockEvidenceReqSignature = await this.odapGatewaySign( JSON.stringify(lockEvidenceReq), ); lockEvidenceReq.clientSignature = this.bufArray2HexStr( lockEvidenceReqSignature, ); const lockEvidenceReqHash = SHA256( JSON.stringify(lockEvidenceReq), ).toString(); await this.odapLog( { phase: "lock-evidence-req", operation: "send-req", step: sessionData.step.toString(), nodes: `${this.pubKey}->${serverIdentityPubkey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; this.log.info(`${fnTag}, send lock evidence req, time: ${Date.now()}`); const lockEvidenceRes = await odapServerApiClient.phase2LockEvidenceV1( lockEvidenceReq, ); this.log.info(`${fnTag}, receive lock evidence ack, time: ${Date.now()}`); if (lockEvidenceRes.status != 200) { await this.Revert(sessionID); throw new Error(`${fnTag}, send lock evidence failed`); } const lockEvidenceAck: LockEvidenceV1Response = lockEvidenceRes.data; const lockEvidenceAckHash = SHA256( JSON.stringify(lockEvidenceAck), ).toString(); if (lockEvidenceReqHash != lockEvidenceAck.hashLockEvidenceRequest) { await this.Revert(sessionID); throw new Error( `${fnTag}, lock evidence req hash not match from lock evidence ack`, ); } if ( lockEvidenceReq.serverIdentityPubkey != lockEvidenceAck.serverIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, lock evidence serverIdentity pub key not match from lock evidence ack`, ); } if ( lockEvidenceReq.clientIdentityPubkey != lockEvidenceAck.clientIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, lock evidence clientIdentity pub key not match from lock evidence ack`, ); } const lockEvidenceAckSignature = lockEvidenceAck.serverSignature; const lockEvidenceAckSignatureHex = new Uint8Array( Buffer.from(lockEvidenceAckSignature, "hex"), ); lockEvidenceAck.serverSignature = ""; if ( !secp256k1.ecdsaVerify( lockEvidenceAckSignatureHex, Buffer.from(SHA256(JSON.stringify(lockEvidenceAck)).toString(), "hex"), sourcePubkey, ) ) { await this.Revert(sessionID); throw new Error(`${fnTag}, lock evidence ack signature verify failed`); } lockEvidenceAck.serverSignature = transferCommenceAckSignature; await this.odapLog( { phase: "lock-evidence-req", operation: "receive-ack", step: sessionData.step.toString(), nodes: `${serverIdentityPubkey}->${this.pubKey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; const commitPrepareReq: CommitPreparationV1Request = { sessionID: sessionID, messageType: "urn:ietf:odap:msgtype:commit-prepare-msg", clientIdentityPubkey: req.clientIdentityPubkey, serverIdentityPubkey: req.serverIdentityPubkey, clientSignature: "", hashLockEvidenceAck: lockEvidenceAckHash, }; const commitPrepareReqSignature = await this.odapGatewaySign( JSON.stringify(commitPrepareReq), ); commitPrepareReq.clientSignature = this.bufArray2HexStr( commitPrepareReqSignature, ); const commitPrepareHash = SHA256( JSON.stringify(commitPrepareReq), ).toString(); await this.odapLog( { phase: "commit-prepare", operation: "send-req", step: sessionData.step.toString(), nodes: `${this.pubKey}->${serverIdentityPubkey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; this.log.info(`${fnTag}, send commit prepare req, time: ${Date.now()}`); const commitPrepareRes = await odapServerApiClient.phase3CommitPreparationV1( commitPrepareReq, ); this.log.info(`${fnTag}, receive commit prepare ack, time: ${Date.now()}`); if (commitPrepareRes.status != 200) { await this.Revert(sessionID); throw new Error(`${fnTag}, send commit prepare failed`); } const commitPrepareAck: CommitPreparationV1Response = commitPrepareRes.data; const commitPrepareAckHash = SHA256( JSON.stringify(commitPrepareAck), ).toString(); if (commitPrepareHash != commitPrepareAck.hashCommitPrep) { await this.Revert(sessionID); throw new Error( `${fnTag}, commit prepare hash not match from commit prepare ack`, ); } if ( commitPrepareReq.serverIdentityPubkey != commitPrepareAck.serverIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, commit prepare serverIdentity pub key not match from commit prepare ack`, ); } if ( commitPrepareReq.clientIdentityPubkey != commitPrepareAck.clientIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, commit prepare clientIdentity pub key not match from commit prepare ack`, ); } const commitPrepareAckSignature = commitPrepareAck.serverSignature; const commitPrepareAckSignatureHex = new Uint8Array( Buffer.from(commitPrepareAckSignature, "hex"), ); commitPrepareAck.serverSignature = ""; if ( !secp256k1.ecdsaVerify( commitPrepareAckSignatureHex, Buffer.from(SHA256(JSON.stringify(commitPrepareAck)).toString(), "hex"), sourcePubkey, ) ) { await this.Revert(sessionID); throw new Error(`${fnTag}, commit prepare ack signature verify failed`); } commitPrepareAck.serverSignature = commitPrepareAckSignature; await this.odapLog( { phase: "commit-prepare", operation: "receive-ack", step: sessionData.step.toString(), nodes: `${serverIdentityPubkey}->${this.pubKey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; let fabricDeleteAssetProof = ""; if (this.fabricApi != undefined) { const deleteRes = await this.fabricApi.runTransactionV1({ signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: this.fabricContractName, invocationType: FabricContractInvocationType.Send, methodName: "DeleteAsset", params: [this.fabricAssetID], } as FabricRunTransactionRequest); const receiptDeleteRes = await this.fabricApi.getTransactionReceiptByTxIDV1( { signingCredential: this.fabricSigningCredential, channelName: this.fabricChannelName, contractName: "qscc", invocationType: FabricContractInvocationType.Call, methodName: "GetBlockByTxID", params: [this.fabricChannelName, deleteRes.data.transactionId], } as FabricRunTransactionRequest, ); this.log.warn(receiptDeleteRes.data); fabricDeleteAssetProof = JSON.stringify(receiptDeleteRes.data); sessionData.isFabricAssetDeleted = true; } const commitFinalReq: CommitFinalV1Request = { sessionID: sessionID, messageType: "urn:ietf:odap:msgtype:commit-final-msg", clientIdentityPubkey: req.clientIdentityPubkey, serverIdentityPubkey: req.serverIdentityPubkey, clientSignature: "", hashCommitPrepareAck: commitPrepareAckHash, commitFinalClaim: fabricDeleteAssetProof, }; const commitFinalReqSignature = await this.odapGatewaySign( JSON.stringify(commitFinalReq), ); commitFinalReq.clientSignature = this.bufArray2HexStr( commitFinalReqSignature, ); const commitFinalReqHash = SHA256( JSON.stringify(commitFinalReq), ).toString(); await this.odapLog( { phase: "commit-final", operation: "send-req", step: sessionData.step.toString(), nodes: `${this.pubKey}->${serverIdentityPubkey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; this.log.info(`${fnTag}, send commit final req, time: ${Date.now()}`); const commitFinalRes = await odapServerApiClient.phase3CommitFinalV1( commitFinalReq, ); this.log.info(`${fnTag}, receive commit final ack, time: ${Date.now()}`); if (commitFinalRes.status != 200) { await this.Revert(sessionID); throw new Error(`${fnTag}, send commit final failed`); } const commitFinalAck: CommitFinalV1Response = commitFinalRes.data; const commitFinalAckHash = SHA256( JSON.stringify(commitFinalAck), ).toString(); if (commitFinalReqHash != commitFinalAck.hashCommitFinal) { await this.Revert(sessionID); throw new Error( `${fnTag}, commit final req hash not match from commit final ack`, ); } if ( commitFinalReq.serverIdentityPubkey != commitFinalAck.serverIdentityPubkey ) { await this.Revert(sessionID); throw new Error( `${fnTag}, commit final serverIdentity pub key not match from commit final ack`, ); } const commitFinalAckSignature = commitFinalAck.serverSignature; const commitFinalAckSignatureHex = new Uint8Array( Buffer.from(commitFinalAckSignature, "hex"), ); commitFinalAck.serverSignature = ""; if ( !secp256k1.ecdsaVerify( commitFinalAckSignatureHex, Buffer.from(SHA256(JSON.stringify(commitFinalAck)).toString(), "hex"), sourcePubkey, ) ) { await this.Revert(sessionID); throw new Error(`${fnTag}, commit final ack signature verify failed`); } commitFinalAck.serverSignature = commitFinalAckSignature; await this.odapLog( { phase: "commit-final", operation: "receive-ack", step: sessionData.step.toString(), nodes: `${serverIdentityPubkey}->${this.pubKey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; const transferCompleteReq: TransferCompleteV1Request = { sessionID: sessionID, messageType: "urn:ietf:odap:msgtype:commit-transfer-complete-msg", clientIdentityPubkey: req.clientIdentityPubkey, serverIdentityPubkey: req.serverIdentityPubkey, clientSignature: "", hashTransferCommence: transferCommenceReqHash, hashCommitFinalAck: commitFinalAckHash, }; const transferCompleteReqSignature = await this.odapGatewaySign( JSON.stringify(transferCompleteReq), ); transferCompleteReq.clientSignature = this.bufArray2HexStr( transferCompleteReqSignature, ); await this.odapLog( { phase: "transfer-complete", operation: "send-req", step: sessionData.step.toString(), nodes: `${this.pubKey}`, }, `${sessionID}-${sessionData.step.toString()}`, ); sessionData.step++; this.sessions.set(sessionID, sessionData); this.log.info(`${fnTag}, send transfer complete req, time: ${Date.now()}`); await odapServerApiClient.phase3TransferCompleteV1(transferCompleteReq); this.log.info(`${fnTag}, receive transfer complete, time: ${Date.now()}`); this.log.info(`${fnTag}, complete processing, time: ${Date.now()}`); } }
the_stack
import {Context} from '@rundeck/testdeck/context' import {CreateContext} from '@rundeck/testdeck/test/selenium' import {ProjectCreatePage} from 'pages/projectCreate.page' import {LoginPage} from 'pages/login.page' import {JobCreatePage} from 'pages/jobCreate.page' import {JobShowPage} from "pages/jobShow.page" import {until, By, Key} from 'selenium-webdriver' import '@rundeck/testdeck/test/rundeck' // We will initialize and cleanup in the before/after methods let ctx = CreateContext({projects: ['SeleniumBasic']}) let loginPage: LoginPage let jobCreatePage: JobCreatePage beforeAll( async () => { loginPage = new LoginPage(ctx) jobCreatePage = new JobCreatePage(ctx, 'SeleniumBasic') }) beforeAll(async () => { await loginPage.login('admin', 'admin') }) describe('job', () => { it('job option simple redo', async () => { await jobCreatePage.get() await ctx.driver.wait(until.urlContains('/job/create'), 25000) let jobNameText='a job with options undo-redo test' let jobName=await jobCreatePage.jobNameInput() await jobName.sendKeys(jobNameText) //add workflow step let wfTab=await jobCreatePage.tabWorkflow() await wfTab.click() let addWfStepCommand=await jobCreatePage.addNewWfStepCommand() //click add Command step, and wait until input fields are loaded await addWfStepCommand.click() await jobCreatePage.waitWfStepCommandRemoteText() let wfStepCommandRemoteText=await jobCreatePage.wfStepCommandRemoteText() await wfStepCommandRemoteText.sendKeys('echo selenium test') let wfStep0SaveButton=await jobCreatePage.wfStep0SaveButton() //click step Save button and wait for the step content to display await wfStep0SaveButton.click() await jobCreatePage.waitWfstep0vis() //add options// //1. click new option button let optionNewButton = await jobCreatePage.optionNewButton() await optionNewButton.click() //2. wait for edit form to load await jobCreatePage.waitoptionEditForm("0") let optionName='seleniumOption1' let optionNameInput=await jobCreatePage.optionNameInput("0") await optionNameInput.sendKeys(optionName) //save option let optionFormSaveButton = await jobCreatePage.optionFormSave("0") await optionFormSaveButton.click() //wait for option to save await jobCreatePage.waitOptionli("0") // NEW OPTION //1. click new option button optionNewButton = await jobCreatePage.optionNewButton() await optionNewButton.click() //2. wait for edit form to load await jobCreatePage.waitoptionEditForm("1") optionName='seleniumOption2' optionNameInput=await jobCreatePage.optionNameInput("1") await optionNameInput.sendKeys(optionName) //save option optionFormSaveButton = await jobCreatePage.optionFormSave("1") await optionFormSaveButton.click() //wait for option to save await jobCreatePage.waitOptionli("1") let optionUndo = await jobCreatePage.optionUndoButton() expect(optionUndo).toBeDefined() let optionRedo= await jobCreatePage.optionRedoButton() expect(optionRedo).toBeDefined() optionUndo.click(); await jobCreatePage.waitUndoRedo(5000); let isOptionli=await jobCreatePage.isOptionli("1") expect(isOptionli).toEqual(false) //save the job let save = await jobCreatePage.saveButton() await save.click() await ctx.driver.wait(until.urlContains('/job/show'), 15000) let jobShowPage = new JobShowPage(ctx,'SeleniumBasic','') //verify job name let jobTitleText = await jobShowPage.jobTitleText() expect(jobTitleText).toContain(jobNameText) }) it('job option revert all', async () => { await jobCreatePage.get() await ctx.driver.wait(until.urlContains('/job/create'), 25000) let jobNameText='a job with options revert all test' let jobName=await jobCreatePage.jobNameInput() await jobName.sendKeys(jobNameText) //add workflow step let wfTab=await jobCreatePage.tabWorkflow() await wfTab.click() let addWfStepCommand=await jobCreatePage.addNewWfStepCommand() //click add Command step, and wait until input fields are loaded await addWfStepCommand.click() await jobCreatePage.waitWfStepCommandRemoteText() let wfStepCommandRemoteText=await jobCreatePage.wfStepCommandRemoteText() await wfStepCommandRemoteText.sendKeys('echo selenium test') let wfStep0SaveButton=await jobCreatePage.wfStep0SaveButton() //click step Save button and wait for the step content to display await wfStep0SaveButton.click() await jobCreatePage.waitWfstep0vis() //add options// //1. click new option button let optionNewButton = await jobCreatePage.optionNewButton() await optionNewButton.click() //2. wait for edit form to load await jobCreatePage.waitoptionEditForm("0") let optionName='seleniumOption1' let optionNameInput=await jobCreatePage.optionNameInput("0") await optionNameInput.sendKeys(optionName) //save option let optionFormSaveButton = await jobCreatePage.optionFormSave("0") await optionFormSaveButton.click() //wait for option to save await jobCreatePage.waitOptionli("0") // NEW OPTION //1. click new option button optionNewButton = await jobCreatePage.optionNewButton() await optionNewButton.click() //2. wait for edit form to load await jobCreatePage.waitoptionEditForm("1") optionName='seleniumOption2' optionNameInput=await jobCreatePage.optionNameInput("1") await optionNameInput.sendKeys(optionName) //save option optionFormSaveButton = await jobCreatePage.optionFormSave("1") await optionFormSaveButton.click() //wait for option to save await jobCreatePage.waitOptionli("1") let optionUndo = await jobCreatePage.optionUndoButton() expect(optionUndo).toBeDefined() let revertOptionButton= await jobCreatePage.revertOptionsButton() expect(revertOptionButton).toBeDefined() await revertOptionButton.click(); await jobCreatePage.waitUndoRedo(5000); let revertOptionsConfirm= await jobCreatePage.revertOptionsConfirm() expect(revertOptionsConfirm).toBeDefined() await revertOptionsConfirm.click() await jobCreatePage.waitUndoRedo(5000); let isOptionli0=await jobCreatePage.isOptionli("0") expect(isOptionli0).toEqual(false) let isOptionli1=await jobCreatePage.isOptionli("1") expect(isOptionli1).toEqual(false) //save the job let save = await jobCreatePage.saveButton() await save.click() await ctx.driver.wait(until.urlContains('/job/show'), 15000) let jobShowPage = new JobShowPage(ctx,'SeleniumBasic','') //verify job name let jobTitleText = await jobShowPage.jobTitleText() expect(jobTitleText).toContain(jobNameText) }) it('job option undo redo', async () => { await jobCreatePage.get() await ctx.driver.wait(until.urlContains('/job/create'), 25000) let jobNameText='a job with options undo redo test' let jobName=await jobCreatePage.jobNameInput() await jobName.sendKeys(jobNameText) //add workflow step let wfTab=await jobCreatePage.tabWorkflow() await wfTab.click() let addWfStepCommand=await jobCreatePage.addNewWfStepCommand() //click add Command step, and wait until input fields are loaded await addWfStepCommand.click() await jobCreatePage.waitWfStepCommandRemoteText() let wfStepCommandRemoteText=await jobCreatePage.wfStepCommandRemoteText() await wfStepCommandRemoteText.sendKeys('echo selenium test') let wfStep0SaveButton=await jobCreatePage.wfStep0SaveButton() //click step Save button and wait for the step content to display await wfStep0SaveButton.click() await jobCreatePage.waitWfstep0vis() //add options// //1. click new option button let optionNewButton = await jobCreatePage.optionNewButton() await optionNewButton.click() //2. wait for edit form to load await jobCreatePage.waitoptionEditForm("0") let optionName='seleniumOption1' let optionNameInput=await jobCreatePage.optionNameInput("0") await optionNameInput.sendKeys(optionName) //save option let optionFormSaveButton = await jobCreatePage.optionFormSave("0") await optionFormSaveButton.click() //wait for option to save await jobCreatePage.waitOptionli("0") // NEW OPTION //1. click new option button optionNewButton = await jobCreatePage.optionNewButton() await optionNewButton.click() //2. wait for edit form to load await jobCreatePage.waitoptionEditForm("1") optionName='seleniumOption2' optionNameInput=await jobCreatePage.optionNameInput("1") await optionNameInput.sendKeys(optionName) //save option optionFormSaveButton = await jobCreatePage.optionFormSave("1") await optionFormSaveButton.click() //wait for option to save await jobCreatePage.waitOptionli("1") let optionUndo = await jobCreatePage.optionUndoButton() expect(optionUndo).toBeDefined() await optionUndo.click() await jobCreatePage.waitUndoRedo(5000); let optionRedo = await jobCreatePage.optionRedoButton() expect(optionRedo).toBeDefined() await optionRedo.click() await jobCreatePage.waitUndoRedo(5000); let isOptionli0=await jobCreatePage.isOptionli("0") expect(isOptionli0).toEqual(true) let isOptionli1=await jobCreatePage.isOptionli("1") expect(isOptionli1).toEqual(true) //save the job let save = await jobCreatePage.saveButton() await save.click() await ctx.driver.wait(until.urlContains('/job/show'), 15000) let jobShowPage = new JobShowPage(ctx,'SeleniumBasic','') //verify job name let jobTitleText = await jobShowPage.jobTitleText() expect(jobTitleText).toContain(jobNameText) }) })
the_stack
"use strict"; import { CoeCliCommands, TextParseFunction } from '../../src/commands/commands' import { LoginCommand } from '../../src/commands/login' import { AA4AMCommand } from '../../src/commands/aa4am' import { RunCommand } from '../../src/commands/run' import { CLICommand } from '../../src/commands/cli' import { mock } from 'jest-mock-extended'; import { DevOpsCommand } from '../../src/commands/devops'; import winston from 'winston'; import readline = require('readline'); import { Command, Option } from 'commander'; import { OpenMode, PathLike } from 'fs'; import { FileHandle } from 'fs/promises'; describe('AA4AM', () => { test('Install aad', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockAA4AMCommand = mock<AA4AMCommand>(); commands.createAA4AMCommand = () => mockAA4AMCommand; mockAA4AMCommand.install.mockReturnValue(Promise.resolve()) // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'install', '-c', 'aad', '--subscription=123']) // Assert expect(mockAA4AMCommand.install).toHaveBeenCalled() expect(JSON.stringify(mockAA4AMCommand.install.mock.calls[0][0].components)).toBe(JSON.stringify(['aad'])) expect(mockAA4AMCommand.install.mock.calls[0][0].subscription).toBe("123") expect(mockAA4AMCommand.install.mock.calls[0][0].azureActiveDirectoryServicePrincipal).toBe("ALMAcceleratorServicePrincipal") }) test('User', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockAA4AMCommand = mock<AA4AMCommand>(); commands.createAA4AMCommand = () => mockAA4AMCommand; mockAA4AMCommand.install.mockReturnValue(Promise.resolve()) // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'user', 'add', '-e', 'E1', '-i', '123']) // Assert expect(mockAA4AMCommand.addUser).toHaveBeenCalled() expect(mockAA4AMCommand.addUser.mock.calls[0][0].environment).toBe('E1') expect(mockAA4AMCommand.addUser.mock.calls[0][0].id).toBe('123') expect(mockAA4AMCommand.addUser.mock.calls[0][0].role).toBe('System Administrator') }) test('Install', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockAA4AMCommand = mock<AA4AMCommand>(); commands.createAA4AMCommand = () => mockAA4AMCommand; mockAA4AMCommand.install.mockReturnValue(Promise.resolve()) // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'install', '--subscription', '123', '-o', 'testorg', '-p', 'alm-sandbox', '--environments', 'crm-org', "-r", "repo1"]) // Assert expect(mockAA4AMCommand.install).toHaveBeenCalled() expect(mockAA4AMCommand.install.mock.calls[0][0].subscription).toBe("123") expect(mockAA4AMCommand.install.mock.calls[0][0].organizationName).toBe("testorg") expect(mockAA4AMCommand.install.mock.calls[0][0].project).toBe("alm-sandbox") expect(mockAA4AMCommand.install.mock.calls[0][0].environment).toBe("crm-org") expect(mockAA4AMCommand.install.mock.calls[0][0].repository).toBe("repo1") expect(mockAA4AMCommand.install.mock.calls[0][0].createSecretIfNoExist).toBe(true) }) test('Install - File', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger, null, { readFile: () => Promise.resolve(`{ "account": "123", "organizationName": "testorg", "project": "alm-sandbox", "environment": "crm-org", "repository": "repo1" }`) }); commands.outputText = (text:string) => {} let mockAA4AMCommand = mock<AA4AMCommand>(); commands.createAA4AMCommand = () => mockAA4AMCommand; mockAA4AMCommand.install.mockReturnValue(Promise.resolve()) // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'install', '-f', 'test.json']) // Assert expect(mockAA4AMCommand.install).toHaveBeenCalled() expect(mockAA4AMCommand.install.mock.calls[0][0].organizationName).toBe("testorg") expect(mockAA4AMCommand.install.mock.calls[0][0].project).toBe("alm-sandbox") expect(mockAA4AMCommand.install.mock.calls[0][0].environment).toBe("crm-org") expect(mockAA4AMCommand.install.mock.calls[0][0].repository).toBe("repo1") expect(mockAA4AMCommand.install.mock.calls[0][0].createSecretIfNoExist).toBe(true) }) test('Install - Multi Environment', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockAA4AMCommand = mock<AA4AMCommand>(); commands.createAA4AMCommand = () => mockAA4AMCommand; mockAA4AMCommand.install.mockReturnValue(Promise.resolve()) // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'install', '--subscription=123', '-o', 'testorg', '-p', 'alm-sandbox', "-r", "repo1", "-e", "validation=test1,test=test2"]) // Assert expect(mockAA4AMCommand.install).toHaveBeenCalled() expect(mockAA4AMCommand.install.mock.calls[0][0].subscription).toBe("123") expect(mockAA4AMCommand.install.mock.calls[0][0].organizationName).toBe("testorg") expect(mockAA4AMCommand.install.mock.calls[0][0].project).toBe("alm-sandbox") expect(mockAA4AMCommand.install.mock.calls[0][0].environment).toBe("") expect(mockAA4AMCommand.install.mock.calls[0][0].repository).toBe("repo1") expect(mockAA4AMCommand.install.mock.calls[0][0].environments["validation"]).toBe("test1") expect(mockAA4AMCommand.install.mock.calls[0][0].environments["test"]).toBe("test2") expect(mockAA4AMCommand.install.mock.calls[0][0].createSecretIfNoExist).toBe(true) }) test('Add Connection', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockLoginCommand = mock<LoginCommand>(); let mockDevOpsCommand = mock<DevOpsCommand>(); commands.createLoginCommand = () => mockLoginCommand; commands.createDevOpsCommand = () => mockDevOpsCommand; // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'connection', 'add', '-e', 'E1', '-o', 'O1', '-p', 'P1']) // Assert expect(mockLoginCommand.azureLogin).toHaveBeenCalled() expect(mockDevOpsCommand.createAdvancedMakersServiceConnections).toHaveBeenCalled() expect(mockDevOpsCommand.createAdvancedMakersServiceConnections.mock.calls[0][0].environment).toBe("E1") expect(mockDevOpsCommand.createAdvancedMakersServiceConnections.mock.calls[0][0].organizationName).toBe("O1") expect(mockDevOpsCommand.createAdvancedMakersServiceConnections.mock.calls[0][0].projectName).toBe("P1") }) }) describe('Prompt For Values', () => { test('Generate Text property', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: (prompt: string, callback: (answer: string) => void) => { callback('foo') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline let mockLoginCommand = mock<LoginCommand>(); let mockDevOpsCommand = mock<DevOpsCommand>(); commands.createLoginCommand = () => mockLoginCommand; commands.createDevOpsCommand = () => mockDevOpsCommand; commands.outputText = (text) => {} const program = new Command(); program.command('install') .option("-m, mode <name>", "Mode name") // Act let result = await commands.promptForValues(program, 'install', [], [], {}) // Assert expect(result.mode).toBe("foo") }) test('Generate sub settings', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: (prompt: string, callback: (answer: string) => void) => { if (prompt.indexOf('Mode') >= 0) { callback('foo') return } if (prompt.indexOf('Item 1') >= 0) { callback('test1') return } callback('') }} var commands = new CoeCliCommands(logger, null); commands.readline = readline let mockLoginCommand = mock<LoginCommand>(); let mockDevOpsCommand = mock<DevOpsCommand>(); commands.createLoginCommand = () => mockLoginCommand; commands.createDevOpsCommand = () => mockDevOpsCommand; commands.outputText = (text) => {} const program = new Command(); let install = program.command('install') install.option("-m, --mode <name>", "Mode name") install.option("-s, --settings <settings>", "Optional settings") const settings = new Command() .command('settings') settings.option("-i, --item1", "Item 1"); // Act let result = await commands.promptForValues(program, 'install', [], [], { 'settings': { parse: (text) => text, command: settings } }) // Assert expect(result.mode).toBe("foo") expect(result.settings['item1']).toBe("test1") }) test('Generate Array property', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: (prompt: string, callback: (answer: string) => void) => { callback('1,2') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline let mockLoginCommand = mock<LoginCommand>(); let mockDevOpsCommand = mock<DevOpsCommand>(); commands.createLoginCommand = () => mockLoginCommand; commands.createDevOpsCommand = () => mockDevOpsCommand; commands.outputText = (text:string) => {} const program = new Command(); program.command('install') .option("-m, modes [name]", "Mode name") // Act let result = await commands.promptForValues(program, 'install', [], [], {}) // Assert expect(JSON.stringify(result.modes)).toBe(JSON.stringify(["1", "2"])) }) test('Generate Option - Default', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: (prompt: string, callback: (answer: string) => void) => { callback('') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline let mockLoginCommand = mock<LoginCommand>(); let mockDevOpsCommand = mock<DevOpsCommand>(); commands.createLoginCommand = () => mockLoginCommand; commands.createDevOpsCommand = () => mockDevOpsCommand; commands.outputText = (text:string) => {} let componentOption = new Option('-c, --components [component]', 'The component(s) to install').default(["A"]).choices(['A', 'B', 'C', 'D']); const program = new Command(); program.command('install') .addOption(componentOption) // Act let result = await commands.promptForValues(program, 'install', [], [], {}) // Assert expect(JSON.stringify(result.components)).toBe(JSON.stringify(["A"])) }) }); describe('Prompt for Option', () => { test('Default Value', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: ( title:string, callback: (answer: string) => void) => { callback('') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline commands.outputText = (text:string) => {} let option = <Option> { description: 'Option1', argChoices: [], name: () => { return "option1"}, defaultValue: 'ABC' } let data : any = {} // Act await commands.promptOption('', [], option, data, {}) // Assert expect(data.option1).toBe('ABC') }) test('Single Arg', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: ( title:string, callback: (answer: string) => void) => { callback('a') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline commands.outputText = (text:string) => {} let option = <Option> { description: 'Option1', argChoices: [], name: () => { return "option1"} } let data : any = {} // Act await commands.promptOption('', [], option, data, {}) // Assert expect(data.option1).toBe('a') }) test('Single Arg - Help', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: ( title:string, callback: (answer: string) => void) => { call++ if (call == 1) { callback('?') } else { callback('a') } } } var commands = new CoeCliCommands(logger, null); let output: string[] = [] commands.outputText = (text)=> output.push(text) commands.readline = readline commands.existsSync = (path: PathLike) => true commands.readFile = (path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding) => { return Promise.resolve(`# Test ## Options ### --option1 Some text ### --next Other`) } let call : number = 0 let option = <Option> { description: 'Option1', argChoices: [], long: 'name', flags: '--foo', name: () => { return "option1"} } let data : any = {} // Act await commands.promptOption('help/foo.md', [], option, data, {}) // Assert expect(data.option1).toBe('a') expect(output.filter((text: string) => text.indexOf("Some text")>= 0).length).toBe(1) }) test('Array', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: ( title:string, callback: (answer: string) => void) => { callback('a,b') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline commands.outputText = (text:string) => {} let option = <Option> { description: 'Option1', flags: '--value [values]', argChoices: [], name: () => { return "option1"} } let data : any = {} // Act await commands.promptOption('', [], option, data, {}) // Assert expect(JSON.stringify(data.option1)).toBe(JSON.stringify(['a','b'])) }) test('Args - Select Multiple', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question:( title:string, callback: (answer: string) => void) => { callback('0,1') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline commands.outputText = (text:string) => {} let option = <Option> { description: 'Option1', flags: '--value [values]', argChoices: [ 'Arg 1', 'Arg 2', 'Arg 3' ], name: () => { return "option1"} } let data : any = {} // Act await commands.promptOption('', [], option, data, {}) // Assert expect(data.option1).toBe('Arg 1,Arg 2') }) test('Args - Select Default', async () => { // Arrange let logger = mock<winston.Logger>() let readline : any = { question: ( title:string, callback: (answer: string) => void) => { callback('') } } var commands = new CoeCliCommands(logger, null); commands.readline = readline commands.outputText = (text:string) => {} let option = <Option> { description: 'Option1', flags: '--value [values]', argChoices: [ 'Arg 1', 'Arg 2', 'Arg 3' ], name: () => { return "option1"}, defaultValue: [ 'Arg 1' ], } let data : any = {} // Act await commands.promptOption('', [], option, data, {}) // Assert expect(JSON.stringify(data.option1)).toBe(JSON.stringify(['Arg 1'])) }) }) describe('Run', () => { test('Execute', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockRunCommand = mock<RunCommand>(); commands.createRunCommand = () => mockRunCommand mockRunCommand.execute.mockResolvedValue() // Act await commands.execute(['node', 'commands.spec', 'run', '-f', 'test.json']) // Assert expect(mockRunCommand.execute).toHaveBeenCalled() }) }); describe('CLI', () => { test('Execute', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); let mockCliCommand = mock<CLICommand>(); commands.createCliCommand = () => mockCliCommand mockCliCommand.add.mockResolvedValue() // Act await commands.execute(['node', 'commands.spec', 'cli', 'add', '-n', 'sample']) // Assert expect(mockCliCommand.add).toHaveBeenCalled() }) }); describe('Help', () => { test('Main', async () => { await expectFile(['node', 'commands.spec', 'help'], 'help\\readme.md') }) test('aa4am', async () => { await expectFile(['node', 'commands.spec', 'help', 'aa4am'], 'help\\aa4am\\readme.md') }) test('aa4am genenerate', async () => { await expectFile(['node', 'commands.spec', 'help', 'aa4am', 'generate'], 'help\\aa4am\\generate\\readme.md') }) test('aa4am genenerate install', async () => { await expectFile(['node', 'commands.spec', 'help', 'aa4am', 'generate', 'install'], 'help\\aa4am\\generate\\install.md') }) test('aa4am install', async () => { await expectFile(['node', 'commands.spec', 'help', 'aa4am', 'install'], 'help\\aa4am\\install.md') }) }); describe('Branch', () => { test('Main', async () => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); commands.outputText = (text:string) => {} let mockAA4AMCommand = mock<AA4AMCommand>(); commands.createAA4AMCommand = () => mockAA4AMCommand mockAA4AMCommand.branch.mockResolvedValue() // Act await commands.execute(['node', 'commands.spec', 'aa4am', 'branch', '-o', 'https://dev.azure.com/contoso', '-p', 'alm-sandbox', '--pipelineRepository', 'templates', '-d', 'NewSolution1']) // Assert expect(mockAA4AMCommand.branch).toHaveBeenCalled() }) }); const expectFile = async (args: string[], name: string) : Promise<void> => { // Arrange let logger = mock<winston.Logger>() var commands = new CoeCliCommands(logger); let readFileName = '' commands.readFile = (path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding) => { readFileName = <string>path return Promise.resolve('') } commands.outputText = (text) => {} // Act await commands.execute(args) // Assert expect(readFileName.indexOf(name) >= 0).toBeTruthy() }
the_stack
import {ConnectionManager} from "./connection/ConnectionManager.ts"; import {Connection} from "./connection/Connection.ts"; import {MetadataArgsStorage} from "./metadata-args/MetadataArgsStorage.ts"; import {ConnectionOptions} from "./connection/ConnectionOptions.ts"; import {getFromContainer} from "./container.ts"; import {ObjectType} from "./common/ObjectType.ts"; import {Repository} from "./repository/Repository.ts"; import {EntityManager} from "./entity-manager/EntityManager.ts"; import {PlatformTools} from "./platform/PlatformTools.ts"; import {TreeRepository} from "./repository/TreeRepository.ts"; import {MongoRepository} from "./repository/MongoRepository.ts"; import {ConnectionOptionsReader} from "./connection/ConnectionOptionsReader.ts"; import {PromiseUtils} from "./util/PromiseUtils.ts"; import {MongoEntityManager} from "./entity-manager/MongoEntityManager.ts"; import {SqljsEntityManager} from "./entity-manager/SqljsEntityManager.ts"; import {SelectQueryBuilder} from "./query-builder/SelectQueryBuilder.ts"; import {EntitySchema} from "./entity-schema/EntitySchema.ts"; // ------------------------------------------------------------------------- // Commonly Used exports // ------------------------------------------------------------------------- export * from "./container.ts"; export * from "./common/ObjectType.ts"; export * from "./common/ObjectLiteral.ts"; export * from "./common/DeepPartial.ts"; export * from "./error/QueryFailedError.ts"; export * from "./decorator/columns/Column.ts"; export * from "./decorator/columns/CreateDateColumn.ts"; export * from "./decorator/columns/PrimaryGeneratedColumn.ts"; export * from "./decorator/columns/PrimaryColumn.ts"; export * from "./decorator/columns/UpdateDateColumn.ts"; export * from "./decorator/columns/VersionColumn.ts"; export * from "./decorator/columns/ViewColumn.ts"; export * from "./decorator/columns/ObjectIdColumn.ts"; export * from "./decorator/listeners/AfterInsert.ts"; export * from "./decorator/listeners/AfterLoad.ts"; export * from "./decorator/listeners/AfterRemove.ts"; export * from "./decorator/listeners/AfterUpdate.ts"; export * from "./decorator/listeners/BeforeInsert.ts"; export * from "./decorator/listeners/BeforeRemove.ts"; export * from "./decorator/listeners/BeforeUpdate.ts"; export * from "./decorator/listeners/EventSubscriber.ts"; export * from "./decorator/options/ColumnOptions.ts"; export * from "./decorator/options/IndexOptions.ts"; export * from "./decorator/options/JoinColumnOptions.ts"; export * from "./decorator/options/JoinTableOptions.ts"; export * from "./decorator/options/RelationOptions.ts"; export * from "./decorator/options/EntityOptions.ts"; export * from "./decorator/options/ValueTransformer.ts"; export * from "./decorator/relations/JoinColumn.ts"; export * from "./decorator/relations/JoinTable.ts"; export * from "./decorator/relations/ManyToMany.ts"; export * from "./decorator/relations/ManyToOne.ts"; export * from "./decorator/relations/OneToMany.ts"; export * from "./decorator/relations/OneToOne.ts"; export * from "./decorator/relations/RelationCount.ts"; export * from "./decorator/relations/RelationId.ts"; export * from "./decorator/entity/Entity.ts"; export * from "./decorator/entity/ChildEntity.ts"; export * from "./decorator/entity/TableInheritance.ts"; export * from "./decorator/entity-view/ViewEntity.ts"; export * from "./decorator/transaction/Transaction.ts"; export * from "./decorator/transaction/TransactionManager.ts"; export * from "./decorator/transaction/TransactionRepository.ts"; export * from "./decorator/tree/TreeLevelColumn.ts"; export * from "./decorator/tree/TreeParent.ts"; export * from "./decorator/tree/TreeChildren.ts"; export * from "./decorator/tree/Tree.ts"; export * from "./decorator/Index.ts"; export * from "./decorator/Unique.ts"; export * from "./decorator/Check.ts"; export * from "./decorator/Exclusion.ts"; export * from "./decorator/Generated.ts"; export * from "./decorator/EntityRepository.ts"; export * from "./find-options/operator/Any.ts"; export * from "./find-options/operator/Between.ts"; export * from "./find-options/operator/Equal.ts"; export * from "./find-options/operator/In.ts"; export * from "./find-options/operator/IsNull.ts"; export * from "./find-options/operator/LessThan.ts"; export * from "./find-options/operator/LessThanOrEqual.ts"; export * from "./find-options/operator/Like.ts"; export * from "./find-options/operator/MoreThan.ts"; export * from "./find-options/operator/MoreThanOrEqual.ts"; export * from "./find-options/operator/Not.ts"; export * from "./find-options/operator/Raw.ts"; export * from "./find-options/FindConditions.ts"; export * from "./find-options/FindManyOptions.ts"; export * from "./find-options/FindOneOptions.ts"; export * from "./find-options/FindOperator.ts"; export * from "./find-options/FindOperatorType.ts"; export * from "./find-options/JoinOptions.ts"; export * from "./find-options/OrderByCondition.ts"; export * from "./find-options/FindOptionsUtils.ts"; export * from "./logger/Logger.ts"; export * from "./logger/AdvancedConsoleLogger.ts"; export * from "./logger/SimpleConsoleLogger.ts"; export * from "./logger/FileLogger.ts"; export * from "./metadata/EntityMetadata.ts"; export * from "./entity-manager/EntityManager.ts"; export * from "./repository/AbstractRepository.ts"; export * from "./repository/Repository.ts"; export * from "./repository/BaseEntity.ts"; export * from "./repository/TreeRepository.ts"; export * from "./repository/MongoRepository.ts"; export * from "./repository/RemoveOptions.ts"; export * from "./repository/SaveOptions.ts"; export * from "./schema-builder/table/TableCheck.ts"; export * from "./schema-builder/table/TableColumn.ts"; export * from "./schema-builder/table/TableExclusion.ts"; export * from "./schema-builder/table/TableForeignKey.ts"; export * from "./schema-builder/table/TableIndex.ts"; export * from "./schema-builder/table/TableUnique.ts"; export * from "./schema-builder/table/Table.ts"; // export * from "./driver/mongodb/typings.ts"; export * from "./driver/types/DatabaseType.ts"; // export * from "./driver/sqlserver/MssqlParameter.ts"; export {ConnectionOptionsReader} from "./connection/ConnectionOptionsReader.ts"; export {Connection} from "./connection/Connection.ts"; export {ConnectionManager} from "./connection/ConnectionManager.ts"; export type {ConnectionOptions} from "./connection/ConnectionOptions.ts"; export type {Driver} from "./driver/Driver.ts"; export {QueryBuilder} from "./query-builder/QueryBuilder.ts"; export {SelectQueryBuilder} from "./query-builder/SelectQueryBuilder.ts"; export {DeleteQueryBuilder} from "./query-builder/DeleteQueryBuilder.ts"; export {InsertQueryBuilder} from "./query-builder/InsertQueryBuilder.ts"; export {UpdateQueryBuilder} from "./query-builder/UpdateQueryBuilder.ts"; export {RelationQueryBuilder} from "./query-builder/RelationQueryBuilder.ts"; export {Brackets} from "./query-builder/Brackets.ts"; export type {WhereExpression} from "./query-builder/WhereExpression.ts"; export {InsertResult} from "./query-builder/result/InsertResult.ts"; export {UpdateResult} from "./query-builder/result/UpdateResult.ts"; export {DeleteResult} from "./query-builder/result/DeleteResult.ts"; export type {QueryRunner} from "./query-runner/QueryRunner.ts"; export {EntityManager} from "./entity-manager/EntityManager.ts"; export {MongoEntityManager} from "./entity-manager/MongoEntityManager.ts"; export {Migration} from "./migration/Migration.ts"; export {MigrationExecutor} from "./migration/MigrationExecutor.ts"; export type {MigrationInterface} from "./migration/MigrationInterface.ts"; export {DefaultNamingStrategy} from "./naming-strategy/DefaultNamingStrategy.ts"; export type {NamingStrategyInterface} from "./naming-strategy/NamingStrategyInterface.ts"; export {Repository} from "./repository/Repository.ts"; export {TreeRepository} from "./repository/TreeRepository.ts"; export {MongoRepository} from "./repository/MongoRepository.ts"; export type {FindOneOptions} from "./find-options/FindOneOptions.ts"; export type {FindManyOptions} from "./find-options/FindManyOptions.ts"; export type {InsertEvent} from "./subscriber/event/InsertEvent.ts"; export type {UpdateEvent} from "./subscriber/event/UpdateEvent.ts"; export type {RemoveEvent} from "./subscriber/event/RemoveEvent.ts"; export type {EntitySubscriberInterface} from "./subscriber/EntitySubscriberInterface.ts"; export {BaseEntity} from "./repository/BaseEntity.ts"; export {EntitySchema} from "./entity-schema/EntitySchema.ts"; export type {EntitySchemaColumnOptions} from "./entity-schema/EntitySchemaColumnOptions.ts"; export type {EntitySchemaIndexOptions} from "./entity-schema/EntitySchemaIndexOptions.ts"; export type {EntitySchemaRelationOptions} from "./entity-schema/EntitySchemaRelationOptions.ts"; export type {ColumnType} from "./driver/types/ColumnTypes.ts"; export {PromiseUtils} from "./util/PromiseUtils.ts"; // ------------------------------------------------------------------------- // Deprecated // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Commonly used functionality // ------------------------------------------------------------------------- /** * Gets metadata args storage. */ export function getMetadataArgsStorage(): MetadataArgsStorage { // we should store metadata storage in a global variable otherwise it brings too much problems // one of the problem is that if any entity (or any other) will be imported before consumer will call // useContainer method with his own container implementation, that entity will be registered in the // old old container (default one post probably) and consumer will his entity. // calling useContainer before he imports any entity (or any other) is not always convenient. // another reason is that when we run migrations typeorm is being called from a global package // and it may load entities which register decorators in typeorm of local package // this leads to impossibility of usage of entities in migrations and cli related operations const globalScope = PlatformTools.getGlobalVariable(); if (!globalScope.typeormMetadataArgsStorage) globalScope.typeormMetadataArgsStorage = new MetadataArgsStorage(); return globalScope.typeormMetadataArgsStorage; } /** * Reads connection options stored in ormconfig configuration file. */ export async function getConnectionOptions(connectionName: string = "default"): Promise<ConnectionOptions> { return new ConnectionOptionsReader().get(connectionName); } /** * Gets a ConnectionManager which creates connections. */ export function getConnectionManager(): ConnectionManager { return getFromContainer(ConnectionManager); } /** * Creates a new connection and registers it in the manager. * Only one connection from ormconfig will be created (name "default" or connection without name). */ export async function createConnection(): Promise<Connection>; /** * Creates a new connection from the ormconfig file with a given name. */ export async function createConnection(name: string): Promise<Connection>; /** * Creates a new connection and registers it in the manager. */ export async function createConnection(options: ConnectionOptions): Promise<Connection>; /** * Creates a new connection and registers it in the manager. * * If connection options were not specified, then it will try to create connection automatically, * based on content of ormconfig (json/js/yml/xml/env) file or environment variables. * Only one connection from ormconfig will be created (name "default" or connection without name). */ export async function createConnection(optionsOrName?: any): Promise<Connection> { const connectionName = typeof optionsOrName === "string" ? optionsOrName : "default"; const options = optionsOrName instanceof Object ? optionsOrName : await getConnectionOptions(connectionName); return getConnectionManager().create(options).connect(); } /** * Creates new connections and registers them in the manager. * * If connection options were not specified, then it will try to create connection automatically, * based on content of ormconfig (json/js/yml/xml/env) file or environment variables. * All connections from the ormconfig will be created. */ export async function createConnections(options?: ConnectionOptions[]): Promise<Connection[]> { if (!options) options = await new ConnectionOptionsReader().all(); const connections = options.map(options => getConnectionManager().create(options)); return PromiseUtils.runInSequence(connections, connection => connection.connect()); } /** * Gets connection from the connection manager. * If connection name wasn't specified, then "default" connection will be retrieved. */ export function getConnection(connectionName: string = "default"): Connection { return getConnectionManager().get(connectionName); } /** * Gets entity manager from the connection. * If connection name wasn't specified, then "default" connection will be retrieved. */ export function getManager(connectionName: string = "default"): EntityManager { return getConnectionManager().get(connectionName).manager; } /** * Gets MongoDB entity manager from the connection. * If connection name wasn't specified, then "default" connection will be retrieved. */ export function getMongoManager(connectionName: string = "default"): MongoEntityManager { return getConnectionManager().get(connectionName).manager as MongoEntityManager; } /** * Gets Sqljs entity manager from connection name. * "default" connection is used, when no name is specified. * Only works when Sqljs driver is used. */ export function getSqljsManager(connectionName: string = "default"): SqljsEntityManager { return getConnectionManager().get(connectionName).manager as SqljsEntityManager; } /** * Gets repository for the given entity class. */ export function getRepository<Entity>(entityClass: ObjectType<Entity>|EntitySchema<Entity>|string, connectionName: string = "default"): Repository<Entity> { return getConnectionManager().get(connectionName).getRepository<Entity>(entityClass); } /** * Gets tree repository for the given entity class. */ export function getTreeRepository<Entity>(entityClass: ObjectType<Entity>|string, connectionName: string = "default"): TreeRepository<Entity> { return getConnectionManager().get(connectionName).getTreeRepository<Entity>(entityClass); } /** * Gets tree repository for the given entity class. */ export function getCustomRepository<T>(customRepository: ObjectType<T>, connectionName: string = "default"): T { return getConnectionManager().get(connectionName).getCustomRepository(customRepository); } /** * Gets mongodb repository for the given entity class or name. */ export function getMongoRepository<Entity>(entityClass: ObjectType<Entity>|string, connectionName: string = "default"): MongoRepository<Entity> { return getConnectionManager().get(connectionName).getMongoRepository<Entity>(entityClass); } /** * Creates a new query builder. */ export function createQueryBuilder<Entity>(entityClass?: ObjectType<Entity>|string, alias?: string, connectionName: string = "default"): SelectQueryBuilder<Entity> { if (entityClass) { return getRepository(entityClass, connectionName).createQueryBuilder(alias); } return getConnection(connectionName).createQueryBuilder(); }
the_stack
import { Lambda1, Lambda1_deps, Lambda1_toFunction, Lambda2, Lambda2_deps, Lambda2_toFunction, Lambda3, Lambda3_deps, Lambda3_toFunction, Lambda4, Lambda4_deps, Lambda4_toFunction, Lambda5, Lambda5_deps, Lambda5_toFunction, Lambda6, Lambda6_deps, Lambda6_toFunction, toSources } from "./Lambda"; import { Source, Vertex } from "./Vertex"; import { Transaction } from "./Transaction"; import { CoalesceHandler } from "./CoalesceHandler"; import { Cell } from "./Cell"; //import { StreamLoop } from "./StreamLoop"; import { Listener } from "./Listener"; import { Tuple2 } from "./Tuple2"; import { Lazy } from "./Lazy"; import { LazyCell } from "./LazyCell"; import * as Z from "sanctuary-type-classes"; class MergeState<A> { constructor() {} left : A = null; left_present : boolean = false; right : A = null; right_present : boolean = false; } export class Stream<A> { constructor(vertex? : Vertex) { this.vertex = vertex ? vertex : new Vertex("Stream", 0, []); } getVertex__() : Vertex { return this.vertex; } protected vertex : Vertex; protected listeners : Array<Listener<A>> = []; protected firings : A[] = []; /** * Transform the stream's event values according to the supplied function, so the returned * Stream's event values reflect the value of the function applied to the input * Stream's event values. * @param f Function to apply to convert the values. It may construct FRP logic or use * {@link Cell#sample()} in which case it is equivalent to {@link Stream#snapshot(Cell)}ing the * cell. Apart from this the function must be <em>referentially transparent</em>. */ map<B>(f : ((a : A) => B) | Lambda1<A,B>) : Stream<B> { const out = new StreamWithSend<B>(null); const ff = Lambda1_toFunction(f); out.vertex = new Vertex("map", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(ff(a)); }, false); } ) ].concat(toSources(Lambda1_deps(f))) ); return out; } /** * Transform the stream's event values into the specified constant value. * @param b Constant value. */ mapTo<B>(b : B) : Stream<B> { const out = new StreamWithSend<B>(null); out.vertex = new Vertex("mapTo", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(b); }, false); } ) ] ); return out; } /** * Variant of {@link Stream#merge(Stream, Lambda2)} that merges two streams and will drop an event * in the simultaneous case. * <p> * In the case where two events are simultaneous (i.e. both * within the same transaction), the event from <em>this</em> will take precedence, and * the event from <em>s</em> will be dropped. * If you want to specify your own combining function, use {@link Stream#merge(Stream, Lambda2)}. * s1.orElse(s2) is equivalent to s1.merge(s2, (l, r) -&gt; l). * <p> * The name orElse() is used instead of merge() to make it really clear that care should * be taken, because events can be dropped. */ orElse(s : Stream<A>) : Stream<A> { return this.merge(s, (left : A, right: A) => { return left; }); } /** * Merge two streams of the same type into one, so that events on either input appear * on the returned stream. * <p> * If the events are simultaneous (that is, one event from this and one from <em>s</em> * occurring in the same transaction), combine them into one using the specified combining function * so that the returned stream is guaranteed only ever to have one event per transaction. * The event from <em>this</em> will appear at the left input of the combining function, and * the event from <em>s</em> will appear at the right. * @param f Function to combine the values. It may construct FRP logic or use * {@link Cell#sample()}. Apart from this the function must be <em>referentially transparent</em>. */ merge(s : Stream<A>, f : ((left : A, right : A) => A) | Lambda2<A,A,A>) : Stream<A> { const ff = Lambda2_toFunction(f); const mergeState = new MergeState<A>(); let pumping = false; const out = new StreamWithSend<A>(null); const pump = () => { if (pumping) { return; } pumping = true; Transaction.currentTransaction.prioritized(out.getVertex__(), () => { if (mergeState.left_present && mergeState.right_present) { out.send_(ff(mergeState.left, mergeState.right)); } else if (mergeState.left_present) { out.send_(mergeState.left); } else if (mergeState.right_present) { out.send_(mergeState.right); } mergeState.left = null; mergeState.left_present = false; mergeState.right = null; mergeState.right_present = false; pumping = false; }); }; const vertex = new Vertex("merge", 0, [ new Source( this.vertex, () => this.listen_(out.vertex, (a : A) => { mergeState.left = a; mergeState.left_present = true; pump(); }, false) ), new Source( s.vertex, () => s.listen_(out.vertex, (a : A) => { mergeState.right = a; mergeState.right_present = true; pump(); }, false) ) ].concat(toSources(Lambda2_deps(f))) ); out.vertex = vertex; return out; } /** * Return a stream that only outputs events for which the predicate returns true. */ filter(f : ((a : A) => boolean) | Lambda1<A,boolean>) : Stream<A> { const out = new StreamWithSend<A>(null); const ff = Lambda1_toFunction(f); out.vertex = new Vertex("filter", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { if (ff(a)) out.send_(a); }, false); } ) ].concat(toSources(Lambda1_deps(f))) ); return out; } /** * Return a stream that only outputs events that have present * values, discarding null values. */ filterNotNull() : Stream<A> { const out = new StreamWithSend<A>(null); out.vertex = new Vertex("filterNotNull", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { if (a !== null) out.send_(a); }, false); } ) ] ); return out; } /** * Return a stream that only outputs events from the input stream * when the specified cell's value is true. */ gate(c : Cell<boolean>) : Stream<A> { return this.snapshot(c, (a : A, pred : boolean) => { return pred ? a : null; }).filterNotNull(); } /** * Variant of {@link snapshot(Cell, Lambda2)} that captures the cell's value * at the time of the event firing, ignoring the stream's value. */ snapshot1<B>(c : Cell<B>) : Stream<B> { const out = new StreamWithSend<B>(null); out.vertex = new Vertex("snapshot1", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(c.sampleNoTrans__()); }, false); } ), new Source(c.getVertex__(), null) ] ); return out; } /** * Return a stream whose events are the result of the combination using the specified * function of the input stream's event value and the value of the cell at that time. * <P> * There is an implicit delay: State updates caused by event firings being held with * {@link Stream#hold(Object)} don't become visible as the cell's current value until * the following transaction. To put this another way, {@link Stream#snapshot(Cell, Lambda2)} * always sees the value of a cell as it was before any state changes from the current * transaction. */ snapshot<B,C>(b : Cell<B>, f_ : ((a : A, b : B) => C) | Lambda2<A,B,C>) : Stream<C> { const out = new StreamWithSend<C>(null); const ff = Lambda2_toFunction(f_); out.vertex = new Vertex("snapshot", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(ff(a, b.sampleNoTrans__())); }, false); } ), new Source(b.getVertex__(), null) ].concat(toSources(Lambda2_deps(f_))) ); return out; } /** * Return a stream whose events are the result of the combination using the specified * function of the input stream's event value and the value of the cells at that time. * <P> * There is an implicit delay: State updates caused by event firings being held with * {@link Stream#hold(Object)} don't become visible as the cell's current value until * the following transaction. To put this another way, snapshot() * always sees the value of a cell as it was before any state changes from the current * transaction. */ snapshot3<B,C,D>(b : Cell<B>, c : Cell<C>, f_ : ((a : A, b : B, c : C) => D) | Lambda3<A,B,C,D>) : Stream<D> { const out = new StreamWithSend<D>(null); const ff = Lambda3_toFunction(f_); out.vertex = new Vertex("snapshot", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(ff(a, b.sampleNoTrans__(), c.sampleNoTrans__())); }, false); } ), new Source(b.getVertex__(), null), new Source(c.getVertex__(), null) ].concat(toSources(Lambda3_deps(f_))) ); return out; } /** * Return a stream whose events are the result of the combination using the specified * function of the input stream's event value and the value of the cells at that time. * <P> * There is an implicit delay: State updates caused by event firings being held with * {@link Stream#hold(Object)} don't become visible as the cell's current value until * the following transaction. To put this another way, snapshot() * always sees the value of a cell as it was before any state changes from the current * transaction. */ snapshot4<B,C,D,E>(b : Cell<B>, c : Cell<C>, d : Cell<D>, f_ : ((a : A, b : B, c : C, d : D) => E) | Lambda4<A,B,C,D,E>) : Stream<E> { const out = new StreamWithSend<E>(null); const ff = Lambda4_toFunction(f_); out.vertex = new Vertex("snapshot", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(ff(a, b.sampleNoTrans__(), c.sampleNoTrans__(), d.sampleNoTrans__())); }, false); } ), new Source(b.getVertex__(), null), new Source(c.getVertex__(), null), new Source(d.getVertex__(), null) ].concat(toSources(Lambda4_deps(f_))) ); return out; } /** * Return a stream whose events are the result of the combination using the specified * function of the input stream's event value and the value of the cells at that time. * <P> * There is an implicit delay: State updates caused by event firings being held with * {@link Stream#hold(Object)} don't become visible as the cell's current value until * the following transaction. To put this another way, snapshot() * always sees the value of a cell as it was before any state changes from the current * transaction. */ snapshot5<B,C,D,E,F>(b : Cell<B>, c : Cell<C>, d : Cell<D>, e : Cell<E>, f_ : ((a : A, b : B, c : C, d : D, e : E) => F) | Lambda5<A,B,C,D,E,F>) : Stream<F> { const out = new StreamWithSend<F>(null); const ff = Lambda5_toFunction(f_); out.vertex = new Vertex("snapshot", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(ff(a, b.sampleNoTrans__(), c.sampleNoTrans__(), d.sampleNoTrans__(), e.sampleNoTrans__())); }, false); } ), new Source(b.getVertex__(), null), new Source(c.getVertex__(), null), new Source(d.getVertex__(), null), new Source(e.getVertex__(), null) ].concat(toSources(Lambda5_deps(f_))) ); return out; } /** * Return a stream whose events are the result of the combination using the specified * function of the input stream's event value and the value of the cells at that time. * <P> * There is an implicit delay: State updates caused by event firings being held with * {@link Stream#hold(Object)} don't become visible as the cell's current value until * the following transaction. To put this another way, snapshot() * always sees the value of a cell as it was before any state changes from the current * transaction. */ snapshot6<B,C,D,E,F,G>(b : Cell<B>, c : Cell<C>, d : Cell<D>, e : Cell<E>, f : Cell<F>, f_ : ((a : A, b : B, c : C, d : D, e : E, f : F) => G) | Lambda6<A,B,C,D,E,F,G>) : Stream<G> { const out = new StreamWithSend<G>(null); const ff = Lambda6_toFunction(f_); out.vertex = new Vertex("snapshot", 0, [ new Source( this.vertex, () => { return this.listen_(out.vertex, (a : A) => { out.send_(ff(a, b.sampleNoTrans__(), c.sampleNoTrans__(), d.sampleNoTrans__(), e.sampleNoTrans__(), f.sampleNoTrans__())); }, false); } ), new Source(b.getVertex__(), null), new Source(c.getVertex__(), null), new Source(d.getVertex__(), null), new Source(e.getVertex__(), null), new Source(f.getVertex__(), null) ].concat(toSources(Lambda6_deps(f_))) ); return out; } /** * Create a {@link Cell} with the specified initial value, that is updated * by this stream's event values. * <p> * There is an implicit delay: State updates caused by event firings don't become * visible as the cell's current value as viewed by {@link Stream#snapshot(Cell, Lambda2)} * until the following transaction. To put this another way, * {@link Stream#snapshot(Cell, Lambda2)} always sees the value of a cell as it was before * any state changes from the current transaction. */ hold(initValue : A) : Cell<A> { return new Cell<A>(initValue, this); } /** * A variant of {@link hold(Object)} with an initial value captured by {@link Cell#sampleLazy()}. */ holdLazy(initValue : Lazy<A>) : Cell<A> { return new LazyCell<A>(initValue, this); } /** * Transform an event with a generalized state loop (a Mealy machine). The function * is passed the input and the old state and returns the new state and output value. * @param f Function to apply to update the state. It may construct FRP logic or use * {@link Cell#sample()} in which case it is equivalent to {@link Stream#snapshot(Cell)}ing the * cell. Apart from this the function must be <em>referentially transparent</em>. */ collect<B,S>(initState : S, f : ((a : A, s : S) => Tuple2<B,S>) | Lambda2<A,S,Tuple2<B,S>>) : Stream<B> { return this.collectLazy(new Lazy<S>(() => { return initState; }), f); } /** * A variant of {@link collect(Object, Lambda2)} that takes an initial state returned by * {@link Cell#sampleLazy()}. */ collectLazy<B,S>(initState : Lazy<S>, f : ((a : A, s : S) => Tuple2<B,S>) | Lambda2<A,S,Tuple2<B,S>>) : Stream<B> { const ea = this; return Transaction.run(() => { const es = new StreamLoop<S>(), s = es.holdLazy(initState), ebs = ea.snapshot(s, f), eb = ebs.map((bs : Tuple2<B,S>) => { return bs.a; }), es_out = ebs.map((bs : Tuple2<B,S>) => { return bs.b; }); es.loop(es_out); return eb; }); } /** * Accumulate on input event, outputting the new state each time. * @param f Function to apply to update the state. It may construct FRP logic or use * {@link Cell#sample()} in which case it is equivalent to {@link Stream#snapshot(Cell)}ing the * cell. Apart from this the function must be <em>referentially transparent</em>. */ accum<S>(initState : S, f : ((a : A, s : S) => S) | Lambda2<A,S,S>) : Cell<S> { return this.accumLazy(new Lazy<S>(() => { return initState; }), f); } /** * A variant of {@link accum(Object, Lambda2)} that takes an initial state returned by * {@link Cell#sampleLazy()}. */ accumLazy<S>(initState : Lazy<S>, f : ((a : A, s : S) => S) | Lambda2<A,S,S>) : Cell<S> { const ea = this; return Transaction.run(() => { const es = new StreamLoop<S>(), s = es.holdLazy(initState), es_out = ea.snapshot(s, f); es.loop(es_out); return es_out.holdLazy(initState); }); } /** * Return a stream that outputs only one value: the next event of the * input stream, starting from the transaction in which once() was invoked. */ once() : Stream<A> { /* return Transaction.run(() => { const ev = this, out = new StreamWithSend<A>(); let la : () => void = null; la = ev.listen_(out.vertex, (a : A) => { if (la !== null) { out.send_(a); la(); la = null; } }, false); return out; }); */ // We can't use the implementation above, beacuse deregistering // listeners triggers the exception // "send() was invoked before listeners were registered" // We can revisit this another time. For now we will use the less // efficient implementation below. const me = this; return Transaction.run(() => me.gate(me.mapTo(false).hold(true))); } listen(h : (a : A) => void) : () => void { return Transaction.run<() => void>(() => { return this.listen_(Vertex.NULL, h, false); }); } listen_(target : Vertex, h : (a : A) => void, suppressEarlierFirings : boolean) : () => void { if (this.vertex.register(target)) Transaction.currentTransaction.requestRegen(); const listener = new Listener<A>(h, target); this.listeners.push(listener); if (!suppressEarlierFirings && this.firings.length != 0) { const firings = this.firings.slice(); Transaction.currentTransaction.prioritized(target, () => { // Anything sent already in this transaction must be sent now so that // there's no order dependency between send and listen. for (let i = 0; i < firings.length; i++) h(firings[i]); }); } return () => { let removed = false; for (let i = 0; i < this.listeners.length; i++) { if (this.listeners[i] == listener) { this.listeners.splice(i, 1); removed = true; break; } } if (removed) this.vertex.deregister(target); }; } /** * Fantasy-land Algebraic Data Type Compatability. * Stream satisfies the Functor and Monoid Categories (and hence Semigroup) * @see {@link https://github.com/fantasyland/fantasy-land} for more info */ //map :: Functor f => f a ~> (a -> b) -> f b 'fantasy-land/map'<B>(f : ((a : A) => B)) : Stream<B> { return this.map(f); } //concat :: Semigroup a => a ~> a -> a 'fantasy-land/concat'(a:Stream<A>) : Stream<A> { return this.merge(a, (left:any, right) => { return (Z.Semigroup.test(left)) ? Z.concat(left, right) : left; }); } //empty :: Monoid m => () -> m 'fantasy-land/empty'() : Stream<A> { return new Stream<A>(); } } export class StreamWithSend<A> extends Stream<A> { constructor(vertex? : Vertex) { super(vertex); } setVertex__(vertex : Vertex) { // TO DO figure out how to hide this this.vertex = vertex; } send_(a : A) : void { if (this.firings.length == 0) Transaction.currentTransaction.last(() => { this.firings = []; }); this.firings.push(a); const listeners = this.listeners.slice(); for (let i = 0; i < listeners.length; i++) { const h = listeners[i].h; Transaction.currentTransaction.prioritized(listeners[i].target, () => { Transaction.currentTransaction.inCallback++; try { h(a); Transaction.currentTransaction.inCallback--; } catch (err) { Transaction.currentTransaction.inCallback--; throw err; } }); } } } /** * A forward reference for a {@link Stream} equivalent to the Stream that is referenced. */ export class StreamLoop<A> extends StreamWithSend<A> { assigned__ : boolean = false; // to do: Figure out how to hide this constructor() { super(); this.vertex.name = "StreamLoop"; if (Transaction.currentTransaction === null) throw new Error("StreamLoop/CellLoop must be used within an explicit transaction"); } /** * Resolve the loop to specify what the StreamLoop was a forward reference to. It * must be invoked inside the same transaction as the place where the StreamLoop is used. * This requires you to create an explicit transaction with {@link Transaction#run(Lambda0)} * or {@link Transaction#runVoid(Runnable)}. */ loop(sa_out : Stream<A>) : void { if (this.assigned__) throw new Error("StreamLoop looped more than once"); this.assigned__ = true; this.vertex.addSource( new Source( sa_out.getVertex__(), () => { return sa_out.listen_(this.vertex, (a : A) => { this.send_(a); }, false); } ) ); } }
the_stack
declare const Module: any; export const enum MarshalType { String, Int, Long, Float, Double, Handle } export class Handle { private readonly _value: number get value(): number { return this._value } constructor(value: number) { this._value = value } } export const enum MonoObjectType { Integer = 1, FloatingPoint = 2, String = 3, ReferenceType = 4, ValueType = 5 } class MonoApiObject { private _handle: Handle protected runtime: MonoRuntime get handle(): Handle { return this._handle } get valid(): boolean { return this.runtime && this._handle.value !== 0 } get runtimeType(): MonoObjectType { return this.runtime.getObjectType(this.handle.value) } constructor(handle: Handle, runtime: MonoRuntime) { this._handle = handle this.runtime = runtime } } export class MonoAssembly extends MonoApiObject { private _name: string public get name(): string { return this._name } constructor(assemblyName: string, handle: Handle, runtime: MonoRuntime) { super(handle, runtime) this._name = assemblyName } findClass(namespace: string, name: string): MonoClass { return this.runtime.findClass(this, namespace, name) } } export class MonoClass extends MonoApiObject { private _assembly: MonoAssembly private _namespace: string private _name: string public get assembly(): MonoAssembly { return this._assembly } public get namespace(): string { return this._namespace } public get name(): string { return this._name } constructor(assembly: MonoAssembly, namespace: string, name: string, handle: Handle, runtime: MonoRuntime) { super(handle, runtime) this._namespace = namespace this._name = name this._assembly = assembly } findMethod(name: string, argc: number = -1): MonoMethod { return this.runtime.findMethod(this, name, argc) } } export class MonoMethod extends MonoApiObject { private _assembly: MonoAssembly private _class: MonoClass private _name: string private _argc: number public get assembly(): MonoAssembly { return this._assembly } public get class(): MonoClass { return this._class } public get name(): string { return this._name } public get argc(): number { return this._argc } constructor(assembly: MonoAssembly, klass: MonoClass, name: string, argc: number, handle: Handle, runtime: MonoRuntime) { super(handle, runtime) this._assembly = assembly this._class = klass this._name = name this._argc = argc } private callMethod(method: MonoMethod, thisArg: (Handle | null), argsMarshal: MarshalType[], ...args: (Handle | number | string)[]) { let extraArgsMemSize = 0 for (var i = 0; i < args.length; ++i) { // long/double memory must be 8 bytes aligned and I'm being lazy here. - kumpera // allocate extra memory size for all but string and handle, to keep the conditional more readable - bojan if (argsMarshal[i] !== MarshalType.String && argsMarshal[i] !== MarshalType.Handle) extraArgsMemSize += 8 } const extraArgsMem = extraArgsMemSize ? Module._malloc(extraArgsMemSize) : 0 let extraArgIndex = 0; const argsMemory = Module._malloc(args.length * 4) var ehThrow = Module._malloc(4) for (var i = 0; i < args.length; ++i) { if (argsMarshal[i] === MarshalType.String) { if (typeof args[i] !== "string") throw new Error(`Type of argument ${i} is ${typeof args[i]}, but string marshalling was requested!`) Module.setValue(argsMemory + i * 4, this.runtime.convertStringToMonoString(<string>args[i]), "i32") } else if (argsMarshal[i] === MarshalType.Handle) { if (typeof args[i] === "string" || typeof args[i] === "number") throw new Error(`Type of argument ${i} is ${typeof args[i]}, but handle marshalling was requested!`) Module.setValue(argsMemory + i * 4, (<Handle>args[i]).value, "i32") } else { if (typeof args[i] !== "number") throw new Error(`Type of argument ${i} is ${typeof args[i]}, but number marshalling was requested!`) // upstream has an else if here with a bigger conditional, but having limited the // enum here, we don't need to do that. we'll need to treat the extra cell // specially for int/long/float/double values, but for handles (the remaining enum member) // we can ignore the extra cell bit and just set the arg memory normally - bojan const extraCell = extraArgsMemSize + extraArgIndex extraArgIndex += 8 if (argsMarshal[i] === MarshalType.Int) Module.setValue(extraCell, <number>args[i], "i32") else if (argsMarshal[i] === MarshalType.Long) Module.setValue(extraCell, <number>args[i], "i64") else if (argsMarshal[i] === MarshalType.Float) Module.setValue(extraCell, <number>args[i], "float") else if (argsMarshal[i] === MarshalType.Double) Module.setValue(extraCell, <number>args[i], "double") Module.setValue(argsMemory + i * 4, extraCell, "i32") } } Module.setValue(ehThrow, 0, "i32") const res = this.runtime.invokeMethod(method.handle.value, (thisArg ? thisArg.value : null), argsMemory, ehThrow) const ehRes = Module.getValue(ehThrow, "i32") if (extraArgsMemSize) Module._free(extraArgsMem) Module._free(argsMemory) Module._free(ehThrow) if (ehRes != 0) { const msg = new MonoString(new Handle(res), this.runtime).toString() throw new Error(msg) } if (!res) return res const objectType = this.runtime.getObjectType(res) switch (objectType) { case MonoObjectType.Integer: return this.runtime.unboxInteger(res) case MonoObjectType.FloatingPoint: return this.runtime.unboxFloat(res) case MonoObjectType.String: return new MonoString(new Handle(res), this.runtime).toString() default: return new Handle(res); } } invoke(thisArg: ManagedObject | null, argsMarshal: MarshalType[] = [], ...args: (Handle | string | number)[]): (Handle | number | string) { return this.callMethod(this, (thisArg ? thisArg.handle : null), argsMarshal, ...args) } } export class MonoString extends MonoApiObject { private cachedString: (string | null) constructor(strOrHandle: (string | Handle), runtime: MonoRuntime) { if (typeof strOrHandle === 'string') { const handle = new Handle(runtime.convertStringToMonoString(<string>strOrHandle)) super(handle, runtime) } else super(<Handle>strOrHandle, runtime) this.cachedString = null } toString(): string { if (!this.valid) throw new Error("Tried to convert null string") if (this.cachedString) return this.cachedString const rawString = this.runtime.convertMonoStringToUtf8(this.handle.value) this.cachedString = Module.UTF8ToString(rawString) // We're responsible for freeing this, see driver.c Module._free(rawString) if (this.cachedString) return this.cachedString throw new Error("Could not convert string, should not be reached") } } export class ManagedObject { private _handle: Handle protected runtime: MonoRuntime protected assembly: MonoAssembly protected class: MonoClass private corlib: MonoAssembly private object: MonoClass private _toString: MonoMethod get handle(): Handle { return this._handle } get valid(): boolean { return this.runtime && this._handle.value !== 0 } get type(): Type { const type = this.corlib.findClass("System", "Type") let getType: MonoMethod try { getType = this.class.findMethod("GetType") } catch { getType = this.object.findMethod("GetType") } // This is always a handle, because Type is a ref type. See the // switch at the end of callMethod. return new Type(type, <Handle>getType.invoke(this), this.runtime) } get typeFullName(): string { return this.runtime.getTypeFullName(this.handle.value) } toString(): string { return <string>this._toString.invoke(this) } constructor(klass: (MonoClass | undefined), handle: Handle, runtime: MonoRuntime) { this.class = klass ? klass : runtime.getClassForObject(handle.value) this.assembly = this.class.assembly this._handle = handle this.runtime = runtime this.corlib = this.runtime.loadAssembly("mscorlib") this.object = this.corlib.findClass("System", "Object") try { this._toString = this.class.findMethod("ToString") } catch { this._toString = this.object.findMethod("ToString") } } } export class Type extends ManagedObject { toString(): string { const toStringMethod = this.class.findMethod("ToString") return <string>toStringMethod.invoke(this) } get fullName(): string { const fullNameGetter = this.class.findMethod("get_FullName") return <string>fullNameGetter.invoke(this) } } export class MonoRuntime { private assemblyCache: any = {} private classCache: any = {} private methodCache: any = {} constructor() { this._loadRuntime = Module.cwrap('mono_wasm_load_runtime', null, ['string', 'number']) this._loadAssembly = Module.cwrap('mono_wasm_assembly_load', 'number', ['string']) this._findClass = Module.cwrap('mono_wasm_assembly_find_class', 'number', ['number', 'string', 'string']) this._findMethod = Module.cwrap('mono_wasm_assembly_find_method', 'number', ['number', 'string', 'number']) this._getClass = Module.cwrap('mono_wasm_get_class', 'number', ['number']) this._getType = Module.cwrap('mono_wasm_get_type', 'number', ['number']) this._getTypeFullName = Module.cwrap('mono_wasm_get_type_full_name', 'number', ['number']) this._getAssemblyFromClass = Module.cwrap('mono_wasm_get_assembly_from_class', 'number', ['number']) this._getAssemblyName = Module.cwrap('mono_wasm_get_assembly_name', 'number', ['number']) this._getClassNamespace = Module.cwrap('mono_wasm_get_class_namespace', 'number', ['number']) this._getClassName = Module.cwrap('mono_wasm_get_class_name', 'number', ['number']) this._createObject = Module.cwrap('mono_wasm_object_new', 'number', ['number']) this.invokeMethod = Module.cwrap('mono_wasm_invoke_method', 'number', ['number', 'number', 'number', 'number']) this.convertMonoStringToUtf8 = Module.cwrap('mono_wasm_string_get_utf8', 'number', ['number']) this.convertStringToMonoString = Module.cwrap('mono_wasm_string_from_js', 'number', ['string']) this.getObjectType = Module.cwrap('mono_wasm_get_obj_type', 'number', ['number']) this.unboxInteger = Module.cwrap('mono_wasm_unbox_int', 'number', ['number']) this.unboxFloat = Module.cwrap('mono_wasm_unbox_float', 'number', ['number']) this._loadRuntime("managed", 1) } // These are all fake definitions—the constructor will replace them with proper method // calls via the WASM C wrapping interface. They're here because this is easier a bunch // of function-typed "fields" private _loadRuntime(managedPath: string, enableDebugging: number): void { } private _loadAssembly(assemblyName: string): number { return 0; } private _findClass(assembly: number, namespace: string, name: string): number { return 0 } private _findMethod(klass: number, name: string, argc: number): number { return 0 } private _getTypeFullName(type: number): number { return 0 } private _getClass(object: number): number { return 0 } private _getType(klass: number): number { return 0 } private _getAssemblyFromClass(klass: number): number { return 0 } private _getAssemblyName(assembly: number): number { return 0 } private _getClassNamespace(klass: number): number { return 0 } private _getClassName(klass: number): number { return 0 } _createObject(klass: number): number { return 0 } unboxInteger(int: number): number { return 0 } unboxFloat(float: number): number { return 0 } getObjectType(object: number): MonoObjectType { return 0 } invokeMethod(method: number, thisArg: (number | null), params: number, gotException: number): number { return 0 } convertMonoStringToUtf8(string: number): number { return 0 } convertStringToMonoString(str: string): number { return 0 } getTypeFullName(obj: number): string { const klass = this._getClass(obj) const type = this._getType(klass) const typeName = this._getTypeFullName(type) const jsString = Module.UTF8ToString(typeName) return jsString } getClassForObject(obj: number): MonoClass { const klass = this._getClass(obj) const assembly = this._getAssemblyFromClass(klass) const assemblyName = Module.UTF8ToString(this._getAssemblyName(assembly)) const classNamespace = Module.UTF8ToString(this._getClassNamespace(klass)) const className = Module.UTF8ToString(this._getClassName(klass)) const monoAssembly = new MonoAssembly( assemblyName, new Handle(assembly), this) return new MonoClass( monoAssembly, classNamespace, className, new Handle(klass), this ) } loadAssembly(assemblyName: string): MonoAssembly { let asmHandle = this.assemblyCache[assemblyName] if (!asmHandle) { asmHandle = new Handle(this._loadAssembly(assemblyName)) if (!asmHandle.value) throw new Error(`Could not load assembly ${assemblyName}`) this.assemblyCache[assemblyName] = asmHandle; } return new MonoAssembly(assemblyName, asmHandle, this) } findClass(assembly: MonoAssembly, namespace: string, name: string): MonoClass { const key = `${assembly.handle}_${namespace}_${name}` let klass = this.classCache[key] if (!klass) { klass = new Handle(this._findClass(assembly.handle.value, namespace, name)) if (!klass.value) throw new Error(`Could not load class ${namespace}.${name} from ${assembly.name}`) this.classCache[key] = klass } return new MonoClass(assembly, namespace, name, klass, this) } createObject(klass: MonoClass): ManagedObject { const newObject = new Handle(this._createObject(klass.handle.value)) return new ManagedObject(klass, newObject, this) } findMethod(klass: MonoClass, name: string, argc: number): MonoMethod { const key = `${klass.handle}_${name}_${argc}` let method = this.methodCache[key] if (!method) { method = new Handle(this._findMethod(klass.handle.value, name, argc)) if (!method.value) throw new Error( `Could not load method ${name} with ${argc} argument(s) from class ` + `${klass.namespace}.${klass.name} in ${klass.assembly.name}`) this.methodCache[key] = method } return new MonoMethod(klass.assembly, klass, name, argc, method, this) } /** * Boxes a number so it can be passed to Mono. Must be freed by the caller! * @param number The number to box * @returns A pointer to some memory with the integer boxed into it. */ boxInteger(number: number): number { const memory: number = Module._malloc(4) Module.setValue(memory, number, "i32") return memory } /** * Boxes a boolean so it can be passed to Mono. Must be freed by the caller! * @param bool The boolean to box * @returns A pointer to some memory with the boolean boxed into it. */ boxBoolean(bool: boolean): number { const memory: number = Module._malloc(1) Module.setValue(memory, bool, "i8") return memory } free(ptr: number): void { Module._free(ptr) } }
the_stack
import "./folder-icon.less"; import "./focus.less"; import { getApi } from "@aidenlx/obsidian-icon-shortcodes"; import { AFItem, CachedMetadata, debounce, EventRef, FileExplorer, FolderItem, TAbstractFile, TFile, TFolder, } from "obsidian"; import { dirname } from "path"; import ALxFolderNote from "../fn-main"; import { afItemMark, isFolder } from "../misc"; import getClickHandler from "./click-handler"; import AddLongPressEvt, { LongPressEvent } from "./long-press"; const folderNoteClass = "alx-folder-note"; const folderClass = "alx-folder-with-note"; const emptyFolderClass = "alx-empty-folder"; const focusedFolderCls = "alx-focused-folder"; const focusModeCls = "alx-folder-focus"; class FEHandler_Base { private _fe: FileExplorer; constructor(public plugin: ALxFolderNote, fe: FileExplorer) { this._fe = fe; AddLongPressEvt(plugin, fe.dom.navFileContainerEl); } get fileExplorer() { return this._fe; } set fileExplorer(fe: FileExplorer) { if (this._fe !== fe) { AddLongPressEvt(this.plugin, fe.dom.navFileContainerEl); } this._fe = fe; } get fncApi() { return this.plugin.CoreApi; } get app() { return this.plugin.app; } get files() { return this.fileExplorer.files; } getAfItem = (path: string): afItemMark | null => this.fileExplorer.fileItems[path] ?? null; iterateItems = (callback: (item: AFItem) => any): void => { const items = this.fileExplorer.fileItems; if (items) for (const key in items) { if (!Object.prototype.hasOwnProperty.call(items, key)) continue; callback(items[key]); } }; } /** File Explorer Handler */ export default class FEHandler extends FEHandler_Base { constructor(plugin: ALxFolderNote, explorer: FileExplorer) { super(plugin, explorer); const { vault, metadataCache, workspace } = plugin.app; let refs = [] as EventRef[]; const updateIcon = () => { for (const path of this.foldersWithIcon) { this.setMark(path); } }; //#region focus folder setup refs.push( workspace.on("file-menu", (menu, af, source) => { if (!(af instanceof TFolder) || af.isRoot()) return; menu.addItem((item) => item .setTitle("Toggle Focus") .setIcon("crossed-star") .onClick(() => this.toggleFocusFolder(af)), ); }), ); this.plugin.register( () => this.focusedFolder && this.toggleFocusFolder(null), ); //#endregion //#region folder note events setup refs.push( vault.on("create", (af) => af instanceof TFolder && this.setClick(af)), vault.on("folder-note:create", (note: TFile, folder: TFolder) => { this.setMark(note); this.setMark(folder); this.setClick(folder); }), vault.on("folder-note:delete", (note: TFile, folder: TFolder) => { this.setMark(note, true); this.setMark(folder, true); }), vault.on("folder-note:rename", () => { // fe-item in dom will be reused, do nothing for now }), vault.on("folder-note:cfg-changed", () => { this.markAll(true); window.setTimeout(this.markAll, 200); }), metadataCache.on("changed", (file) => { let folder; if ((folder = this.fncApi.getFolderFromNote(file))) { this.setMark(folder); } }), vault.on("iconsc:initialized", updateIcon), vault.on("iconsc:changed", updateIcon), ); //#endregion //#region empty folder detection if (this.plugin.settings.hideCollapseIndicator) { refs.push( vault.on("create", (file) => this.setChangedFolder(file.parent.path)), vault.on("delete", (file) => { let parent = dirname(file.path); this.setChangedFolder(parent === "." ? "/" : parent); }), vault.on("rename", (file, oldPath) => { this.setChangedFolder(file.parent.path); let parent = dirname(oldPath); this.setChangedFolder(parent === "." ? "/" : parent); }), ); } //#endregion refs.forEach((ref) => this.plugin.registerEvent(ref)); } //#region set class mark for folder notes and folders private setMarkQueue: Map<string, boolean> = new Map(); private updateMark = debounce( () => { if (this.setMarkQueue.size > 0) { this.setMarkQueue.forEach((revert, path) => this._setMark(path, revert), ); this.setMarkQueue.clear(); } }, 200, true, ); private _setMark = (path: string, revert: boolean) => { const item = this.getAfItem(path); if (!item) { console.warn("no afitem found for path %s, escaping...", path); return; } if (isFolder(item)) { if (revert === !!item.isFolderWithNote) { item.el.toggleClass(folderClass, !revert); item.isFolderWithNote = revert ? undefined : true; if (this.plugin.settings.hideCollapseIndicator) item.el.toggleClass( emptyFolderClass, revert ? false : item.file.children.length === 1, ); } this._updateIcon(path, revert, item); } else if (revert === !!item.isFolderNote) { item.el.toggleClass(folderNoteClass, !revert); item.isFolderNote = revert ? undefined : true; } }; setMark = (target: AFItem | TAbstractFile | string, revert = false) => { if (!target) return; if (target instanceof TAbstractFile) { this.setMarkQueue.set(target.path, revert); } else if (typeof target === "string") { this.setMarkQueue.set(target, revert); } else { this.setMarkQueue.set(target.file.path, revert); } this.updateMark(); }; markAll = (revert = false) => { this.iterateItems((item: AFItem) => { if (isFolder(item) && !revert) { this.markFolderNote(item.file); } else if (revert) { this.setMark(item, true); } }); }; markFolderNote = (af: TAbstractFile): boolean => { if (af instanceof TFolder && af.isRoot()) return false; const { getFolderNote, getFolderFromNote } = this.fncApi; let found: TAbstractFile | null = null; if (af instanceof TFile) found = getFolderFromNote(af); else if (af instanceof TFolder) found = getFolderNote(af); if (found) { this.setMark(found); this.setMark(af); } else { this.setMark(af, true); } return !!found; }; // #endregion //#region set click handler for folders with folder note private clickHandler = getClickHandler(this); private setClickQueue: Map< string, [folder: AFItem | TFolder, revert: boolean] > = new Map(); private updateClick = debounce( () => { if (this.setClickQueue.size > 0) { this.setClickQueue.forEach((param) => this._setClick(...param)); this.setClickQueue.clear(); } }, 200, true, ); /** * @param revert when revert is true, set item.evtDone to undefined */ _setClick = (target: AFItem | TFolder, revert = false) => { const item: afItemMark | null = target instanceof TFolder ? this.getAfItem(target.path) : target; if (!item) { console.error("item not found with path %s", target); return; } if (isFolder(item)) { if (revert) { item.evtDone = undefined; } else if (!item.evtDone) { const { titleInnerEl } = item; // handle regular click this.plugin.registerDomEvent( titleInnerEl, "click", this.clickHandler.click, ); // handle middle click this.plugin.registerDomEvent( titleInnerEl, "auxclick", this.clickHandler.click, ); // handle double click // @ts-ignore this.plugin.registerDomEvent( titleInnerEl, "long-press", this.clickHandler.press, ); item.evtDone = true; } } }; setClick = (target: AFItem | TFolder, revert = false) => { if (!target) return; if (target instanceof TFolder) { this.setClickQueue.set(target.path, [target, revert]); } else { this.setClickQueue.set(target.file.path, [target, revert]); } this.updateClick(); }; //#endregion //#region set hide collapse indicator private setChangedFolderQueue: Set<string> = new Set(); private updateChangedFolder = debounce( () => { if (this.setChangedFolderQueue.size > 0) { this.setChangedFolderQueue.forEach((path) => { let note = this.fncApi.getFolderNote(path); if (note) { (this.getAfItem(path) as FolderItem)?.el.toggleClass( emptyFolderClass, note.parent.children.length === 1, ); } }); this.setChangedFolderQueue.clear(); } }, 200, true, ); setChangedFolder = (folderPath: string) => { if (!folderPath || folderPath === "/") return; this.setChangedFolderQueue.add(folderPath); this.updateChangedFolder(); }; //#endregion //#region folder icon setup foldersWithIcon = new Set<string>(); private get shouldSetIcon(): boolean { return this.plugin.settings.folderIcon && !!getApi(this.plugin); } private _updateIcon(path: string, revert: boolean, item: afItemMark) { if (!this.shouldSetIcon) return; const api = getApi(this.plugin) as NonNullable<ReturnType<typeof getApi>>; let folderNotePath: string | undefined, metadata: CachedMetadata | undefined; const revertIcon = () => { delete item.el.dataset.icon; this.foldersWithIcon.delete(path); item.el.style.removeProperty("--alx-folder-icon-txt"); item.el.style.removeProperty("--alx-folder-icon-url"); }; if (revert) { revertIcon(); } else if ( (folderNotePath = this.fncApi.getFolderNotePath(path)?.path) && (metadata = this.plugin.app.metadataCache.getCache(folderNotePath)) ) { let iconId = metadata.frontmatter?.icon, icon; if ( iconId && typeof iconId === "string" && (icon = api.getIcon(iconId, true)) ) { this.foldersWithIcon.add(path); item.el.dataset.icon = iconId.replace(/^:|:$/g, ""); if (!api.isEmoji(iconId)) { item.el.style.setProperty("--alx-folder-icon-url", `url("${icon}")`); item.el.style.setProperty("--alx-folder-icon-txt", '" "'); } else { item.el.style.setProperty("--alx-folder-icon-url", '""'); item.el.style.setProperty("--alx-folder-icon-txt", `"${icon}"`); } } else if (item.el.dataset.icon) { revertIcon(); } } } //#endregion //#region folder focus setup private _focusedFolder: { folder: FolderItem; collapsedCache: boolean; } | null = null; get focusedFolder() { return this._focusedFolder?.folder ?? null; } set focusedFolder(item: FolderItem | null) { // restore previous folder collapse state if (this._focusedFolder) { const { folder, collapsedCache } = this._focusedFolder; if (folder.collapsed !== collapsedCache) folder.setCollapsed(collapsedCache); } this._focusedFolder = item ? { folder: item, collapsedCache: item.collapsed } : null; // unfold folder if it's collapsed if (item && item.collapsed) { item.setCollapsed(false); // @ts-ignore this.plugin.app.nextFrame(() => { // @ts-ignore this.fileExplorer.dom.infinityScroll.computeSync(); // @ts-ignore this.fileExplorer.dom.infinityScroll.scrollIntoView(item); }); } this.fileExplorer.dom.navFileContainerEl.toggleClass(focusModeCls, !!item); } toggleFocusFolder(folder: TFolder | null) { const folderItem = folder ? (this.getAfItem(folder.path) as FolderItem | null) : null; if (this.focusedFolder) { this._focusFolder(this.focusedFolder, true); } // if given same folder as current cached, toggle it off if (folderItem && folderItem.file.path === this.focusedFolder?.file.path) { this.focusedFolder = null; } else { folderItem && this._focusFolder(folderItem, false); this.focusedFolder = folderItem; } } private _focusFolder(folder: FolderItem, revert = false) { if (folder.file.isRoot()) throw new Error("Cannot focus on root dir"); folder.el.toggleClass(focusedFolderCls, !revert); } //#endregion }
the_stack
import { IBlockType } from '../store/storetype'; import { LinesTypes } from './calcRender'; import { marklineConfig } from './marklineConfig'; export interface RealStyle { width: number; height: number; left: number; right: number; top: number; bottom: number; } /** * * * @export 吸附间距之前已经算出,该函数直接做处理 * @param {RealStyle} focusStyle * @param {RealStyle} unFocusStyle * @param {LinesTypes} lines * @param {IBlockType} focus * @param {number} diff 绝对值 * @param {('left' | 'top' | 'bottom' | 'right' | 't-b' | 'b-t' | 'l-r' | 'r-l')} direction */ export function marklineDisplay( focusStyle: RealStyle, unFocusStyle: RealStyle, lines: LinesTypes, focus: IBlockType, diff: number, dirty: { dirtyX: boolean; dirtyY: boolean }, direction: 'left' | 'top' | 'bottom' | 'right' | 't-b' | 'b-t' | 'l-r' | 'r-l' ) { const { top, height, left, width } = focusStyle; const { top: t, height: h, left: l, width: w } = unFocusStyle; let diffY = 0; let diffX = 0; switch (direction) { case 'left': if (dirty.dirtyY) { if (diff <= 1) { lines.y.push(l); } } else { lines.y.push(l); diffX = l - left; dirty.dirtyY = true; } break; case 'right': if (dirty.dirtyY) { if (diff <= 1) { lines.y.push(l + w); } } else { lines.y.push(l + w); diffX = l + w - left - width; dirty.dirtyY = true; } break; case 'l-r': if (dirty.dirtyY) { if (diff <= 1) { lines.y.push(l + w); } } else { lines.y.push(l + w); diffX = l + w - left; dirty.dirtyY = true; } break; case 'r-l': if (dirty.dirtyY) { if (diff <= 1) { lines.y.push(l); } } else { lines.y.push(l); diffX = l - (left + width); dirty.dirtyY = true; } break; case 'top': if (dirty.dirtyX) { if (diff <= 1) { lines.x.push(t); } } else { lines.x.push(t); diffY = t - top; dirty.dirtyX = true; } break; case 'bottom': if (dirty.dirtyX) { if (diff <= 1) { lines.x.push(t + h); } } else { lines.x.push(t + h); diffY = t + h - top - height; dirty.dirtyX = true; } break; case 't-b': if (dirty.dirtyX) { if (diff <= 1) { lines.x.push(t + h); } } else { lines.x.push(t + h); diffY = t + h - top; dirty.dirtyX = true; } break; case 'b-t': if (dirty.dirtyX) { if (diff <= 1) { lines.x.push(t); } } else { lines.x.push(t); diffY = t - (top + height); dirty.dirtyX = true; } break; } if (marklineConfig.isAbsorb) { focus.top = Math.round(focus.top + diffY); focus.left = Math.round(focus.left + diffX); } } /** * * 第一次运算时需要 * @export * @param {RealStyle} focusStyle * @param {RealStyle} unFocusStyle * @param {LinesTypes} lines * @param {IBlockType} focus */ export function newMarklineDisplay( focusStyle: RealStyle, unFocusStyle: RealStyle, lines: LinesTypes ) { const { top, height, left, width } = focusStyle; const { top: t, height: h, left: l, width: w } = unFocusStyle; // 头对头 if (Math.abs(t - top) <= 1) { lines.x.push(t); } // 尾对头 else if (Math.abs(t - (top + height)) <= 1) { lines.x.push(t); } // 头对尾 else if (Math.abs((t + h - top) / 2) <= 1) { lines.x.push(t + h); } // 尾对尾 else if (Math.abs((t + h - top - height) / 2) <= 1) { lines.x.push(t + h); } // 纵线 // 头对头 if (Math.abs(l - left) <= 1) { lines.y.push(l); } // 尾对头 else if (Math.abs(l - (left + width)) <= 1) { lines.y.push(l); } // 头对尾 else if (Math.abs(l + w - left) <= 1) { lines.y.push(l + w); } // 尾对尾 else if (Math.abs(l + w - left - width) <= 1) { lines.y.push(l + w); } } /** * * @deprecated */ export function switchMarklineDisplay( l: number, t: number, w: number | string | undefined, h: number | string | undefined, left: number, top: number, width: number, height: number, lines: LinesTypes, focus: IBlockType ) { // 做吸附只能选择一个接近的吸,所以只匹配一个即可。 // 头对头 if (marklineConfig.isAbsorb) { if (Math.abs(top - t) < marklineConfig.indent) { lines.x.push(t); focus.top = t; } // 中对头 else if (Math.abs(top + height / 2 - t) < marklineConfig.indent) { lines.x.push(t); focus.top = t - height / 2; } // 尾对头 else if (Math.abs(top + height - t) < marklineConfig.indent) { lines.x.push(t); focus.top = t - height; } else if (h && typeof h === 'number') { // 头对中 if (Math.abs(t + h / 2 - top) < marklineConfig.indent) { lines.x.push(t + h / 2); focus.top = t + h / 2; } // 中对中 else if (Math.abs(t + h / 2 - top - height / 2) < marklineConfig.indent) { lines.x.push(t + h / 2); focus.top = t + h / 2 - height / 2; } // 尾对中 else if (Math.abs(t + h / 2 - top - height) < marklineConfig.indent) { lines.x.push(t + h / 2); focus.top = t + h / 2 - height; } // 头对尾 else if (Math.abs((t + h - top) / 2) < marklineConfig.indent) { lines.x.push(t + h); focus.top = t + h; } // 中对尾 else if (Math.abs(t + h - top - height / 2) < marklineConfig.indent) { lines.x.push(t + h); focus.top = t + h - height / 2; } // 尾对尾 else if (Math.abs((t + h - top - height) / 2) < marklineConfig.indent) { lines.x.push(t + h); focus.top = t + h - height; } } // x轴方向 // 头对头 if (Math.abs(left - l) < marklineConfig.indent) { lines.y.push(l); focus.left = l; } // 中对头 else if (Math.abs(left + width / 2 - l) < marklineConfig.indent) { lines.y.push(l); focus.left = l - width / 2; } // 尾对头 else if (Math.abs(left + width - l) < marklineConfig.indent) { lines.y.push(l); focus.left = l - width; } else if (w && typeof w === 'number') { // 头对中 if (Math.abs(l + w / 2 - left) < marklineConfig.indent) { lines.y.push(l + w / 2); focus.left = l + w / 2; } // 中对中 else if (Math.abs(l + w / 2 - left - width / 2) < marklineConfig.indent) { lines.y.push(l + w / 2); focus.left = l + w / 2 - width / 2; } // 尾对中 else if (Math.abs(l + w / 2 - left - width) < marklineConfig.indent) { lines.y.push(l + w / 2); focus.left = l + w / 2 - width; } // 头对尾 else if (Math.abs((l + w - left) / 2) < marklineConfig.indent) { lines.y.push(l + w); focus.left = l + w; } // 中对尾 else if (Math.abs(l + w - left - width / 2) < marklineConfig.indent) { lines.y.push(l + w); focus.left = l + w - width / 2; } // 尾对尾 else if (Math.abs((l + w - left - width) / 2) < marklineConfig.indent) { lines.y.push(l + w); focus.left = l + w - width; } } } else { if (Math.abs(top - t) < marklineConfig.indent) { lines.x.push(t); } // 中对头 if (Math.abs(top + height / 2 - t) < marklineConfig.indent) { lines.x.push(t); } // 尾对头 if (Math.abs(top + height - t) < marklineConfig.indent) { lines.x.push(t); } if (h && typeof h === 'number') { // 头对中 if (Math.abs(t + h / 2 - top) < marklineConfig.indent) { lines.x.push(t + h / 2); } // 中对中 if (Math.abs(t + h / 2 - top - height / 2) < marklineConfig.indent) { lines.x.push(t + h / 2); } // 尾对中 if (Math.abs(t + h / 2 - top - height) < marklineConfig.indent) { lines.x.push(t + h / 2); } // 头对尾 if (Math.abs((t + h - top) / 2) < marklineConfig.indent) { lines.x.push(t + h); } // 中对尾 if (Math.abs(t + h - top - height / 2) < marklineConfig.indent) { lines.x.push(t + h); } // 尾对尾 if (Math.abs((t + h - top - height) / 2) < marklineConfig.indent) { lines.x.push(t + h); } } // x轴方向 // 头对头 if (Math.abs(left - l) < marklineConfig.indent) { lines.y.push(l); } // 中对头 if (Math.abs(left + width / 2 - l) < marklineConfig.indent) { lines.y.push(l); } // 尾对头 if (Math.abs(left + width - l) < marklineConfig.indent) { lines.y.push(l); } if (w && typeof w === 'number') { // 头对中 if (Math.abs(l + w / 2 - left) < marklineConfig.indent) { lines.y.push(l + w / 2); } // 中对中 if (Math.abs(l + w / 2 - left - width / 2) < marklineConfig.indent) { lines.y.push(l + w / 2); } // 尾对中 if (Math.abs(l + w / 2 - left - width) < marklineConfig.indent) { lines.y.push(l + w / 2); } // 头对尾 if (Math.abs((l + w - left) / 2) < marklineConfig.indent) { lines.y.push(l + w); } // 中对尾 if (Math.abs(l + w - left - width / 2) < marklineConfig.indent) { lines.y.push(l + w); } // 尾对尾 if (Math.abs((l + w - left - width) / 2) < marklineConfig.indent) { lines.y.push(l + w); } } } } /** * @todo 暂时无效 */ export function switchMarklineResizeDisplay( l: number, t: number, w: number | string | undefined, h: number | string | undefined, left: number, top: number, width: number, height: number, lines: LinesTypes ) { // 头对头 if (Math.abs(top - t) <= marklineConfig.resizeIndent) { lines.x.push(t); } // 中对头 if (Math.abs(top + height / 2 - t) <= marklineConfig.resizeIndent) { lines.x.push(t); } // 尾对头 if (Math.abs(top + height - t) <= marklineConfig.resizeIndent) { lines.x.push(t); } if (h && typeof h === 'number') { // 头对中 if (Math.abs(t + h / 2 - top) <= marklineConfig.resizeIndent) { lines.x.push(t + h / 2); } // 中对中 if (Math.abs(t + h / 2 - top - height / 2) <= marklineConfig.resizeIndent) { lines.x.push(t + h / 2); } // 尾对中 if (Math.abs(t + h / 2 - top - height) <= marklineConfig.resizeIndent) { lines.x.push(t + h / 2); } // 头对尾 if (Math.abs((t + h - top) / 2) <= marklineConfig.resizeIndent) { lines.x.push(t + h); } // 中对尾 if (Math.abs(t + h - top - height / 2) <= marklineConfig.resizeIndent) { lines.x.push(t + h); } // 尾对尾 if (Math.abs((t + h - top - height) / 2) <= marklineConfig.resizeIndent) { lines.x.push(t + h); } } // x轴方向 // 头对头 if (Math.abs(left - l) <= marklineConfig.resizeIndent) { lines.y.push(l); } // 中对头 if (Math.abs(left + width / 2 - l) <= marklineConfig.resizeIndent) { lines.y.push(l); } // 尾对头 if (Math.abs(left + width - l) <= marklineConfig.resizeIndent) { lines.y.push(l); } if (w && typeof w === 'number') { // 头对中 if (Math.abs(l + w / 2 - left) <= marklineConfig.resizeIndent) { lines.y.push(l + w / 2); } // 中对中 if (Math.abs(l + w / 2 - left - width / 2) <= marklineConfig.resizeIndent) { lines.y.push(l + w / 2); } // 尾对中 if (Math.abs(l + w / 2 - left - width) <= marklineConfig.resizeIndent) { lines.y.push(l + w / 2); } // 头对尾 if (Math.abs((l + w - left) / 2) <= marklineConfig.resizeIndent) { lines.y.push(l + w); } // 中对尾 if (Math.abs(l + w - left - width / 2) <= marklineConfig.resizeIndent) { lines.y.push(l + w); } // 尾对尾 if (Math.abs((l + w - left - width) / 2) <= marklineConfig.resizeIndent) { lines.y.push(l + w); } } }
the_stack
import {Annotation, Position} from './position' import {Socket} from './gtp_socket' import {Color, Move, N, Nullable, gtpColor, movesEqual, setBoardSize, stonesEqual, toGtp} from './base' import {Graph} from './graph' import * as lyr from './layer' import {Log} from './log' import {Board} from './board' import * as util from './util' class Player { gtp = new Socket(); board: Board; log: Log; activePosition: Nullable<Position>; latestPosition: Nullable<Position>; numWins = 0; nameElem: HTMLElement; scoreElem: HTMLElement; capturesElem: HTMLElement; timeElapsedElem: HTMLElement; timeTotalElem: HTMLElement; private genmoveTimerId = 0; private genmoveStartTimeSecs = 0; private genmoveTotalTimeSecs = 0; private searchLayer: lyr.Layer; private pvLayer: lyr.Layer; private dummyPosition: Position; private bookmarks: Element[] = []; constructor(public color: Color, public name: string) { this.dummyPosition = new Position({ id: `${name}-dummy-position`, moveNum: 0, toPlay: 'b', }); let gtpCol = gtpColor(color); this.log = new Log(`${gtpCol}-log`, `${gtpCol}-console`); let elem = util.getElement(`${gtpCol}-board`); this.searchLayer = new lyr.Search(); this.pvLayer = new lyr.Variation('pv'); this.board = new Board(elem, this.dummyPosition, [ new lyr.Label(), new lyr.BoardStones(), this.searchLayer, this.pvLayer, new lyr.Annotations()]); this.pvLayer.show = false; this.log.onConsoleCmd((cmd: string) => { this.gtp.send(cmd).then(() => { this.log.scroll(); }); }); this.gtp.onText((line: string) => { this.log.log(line); if (this.activePosition == this.latestPosition) { this.log.scroll(); } }); this.newGame() } newGame() { this.log.clear(); this.bookmarks = []; this.activePosition = null; this.latestPosition = null; this.board.position = this.dummyPosition; this.genmoveTotalTimeSecs = 0; // Look up all HTML elements each game because the players swap sides. let gtpCol = gtpColor(this.color); this.nameElem = util.getElement(`${gtpCol}-name`); this.scoreElem = util.getElement(`${gtpCol}-score`); this.capturesElem = util.getElement(`${gtpCol}-captures`); this.timeElapsedElem = util.getElement(`${gtpCol}-time-elapsed`); this.timeTotalElem = util.getElement(`${gtpCol}-time-total`); } addPosition(position: Position) { if (this.latestPosition == null) { this.activePosition = position; } else { this.latestPosition.children.push(position); position.parent = this.latestPosition; } this.latestPosition = position; } updatePosition(update: Position.Update) { if (this.latestPosition == null) { return; } if (update.id != this.latestPosition.id) { console.log(`update ${update.id} doesn't match latest position ${this.latestPosition.id}`); return; } this.latestPosition.update(update); if (this.activePosition == this.latestPosition) { this.board.update(update); } } selectMove(moveNum: number) { if (this.activePosition == null) { return; } let position = this.activePosition; while (position.moveNum < moveNum && position.children.length > 0) { position = position.children[0]; } while (position.moveNum > moveNum && position.parent != null) { position = position.parent; } this.activePosition = position; this.board.setPosition(position); this.pvLayer.show = this.color != position.toPlay; this.searchLayer.show = !this.pvLayer.show; } startGenmoveTimer() { this.genmoveStartTimeSecs = Date.now() / 1000; this.genmoveTimerId = window.setInterval(() => { this.updateTimerDisplay( Date.now() / 1000 - this.genmoveStartTimeSecs, this.genmoveTotalTimeSecs); }, 1000); } stopGenmoveTimer() { this.genmoveTotalTimeSecs += Date.now() / 1000 - this.genmoveStartTimeSecs; window.clearInterval(this.genmoveTimerId); this.genmoveTimerId = 0; this.updateTimerDisplay(0, this.genmoveTotalTimeSecs); } setBookmark(moveNum: number) { if (this.log.logElem.lastElementChild != null) { this.bookmarks[moveNum] = this.log.logElem.lastElementChild; } } scrollToBookmark(moveNum: number) { if (this.bookmarks[moveNum] != null) { this.bookmarks[moveNum].scrollIntoView(); } } private updateTimerDisplay(elapsed: number, total: number) { this.timeElapsedElem.innerText = this.formatDuration(elapsed); this.timeTotalElem.innerText = this.formatDuration(total); } private formatDuration(durationSecs: number) { durationSecs = Math.floor(durationSecs); let s = durationSecs % 60; let m = Math.floor((durationSecs / 60)) % 60; let h = Math.floor(durationSecs / 3600); let ss = s < 10 ? '0' + s : s.toString(); let mm = m < 10 ? '0' + m : m.toString(); let hh = h < 10 ? '0' + h : m.toString(); return `${hh}:${mm}:${ss}`; } } class ReadsGraph extends Graph { private plots: number[][] = [[], []]; constructor(elem: string) { super(elem, { xStart: 0, xEnd: 10, yStart: 10, yEnd: 0, xTicks: true, yTicks: true, marginTop: 0.05, marginBottom: 0.05, marginLeft: 0.08, marginRight: 0.05, }); this.draw(); } newGame() { for (let plot of this.plots) { plot.length = 0; } this.xEnd = 10; this.yStart = 10; this.draw(); } drawImpl() { this.xEnd = Math.max(this.xEnd, this.moveNum); super.drawImpl(); // Draw a dotted line for the current move number. this.drawPlot( [[this.moveNum, this.yStart], [this.moveNum, this.yEnd]], { dash: [0, 3], width: 1, style: '#96928f', snap: true, }); for (let i = 0; i < this.plots.length; ++i) { let plot = this.plots[i]; let points: number[][] = []; for (let x = 0; x < plot.length; ++x) { if (plot[x] != null) { points.push([x, plot[x]]); } } this.drawPlot(points, { width: 3, style: i == 0 ? '#fff' : '#000' }); } let pr = util.pixelRatio(); let ctx = this.ctx; let textHeight = 0.06 * ctx.canvas.height; ctx.font = `${textHeight}px sans-serif`; ctx.fillStyle = '#96928f'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; let y = this.yTickPoints[this.yTickPoints.length - 1]; ctx.fillText(y.toString(), -6 * pr, this.yScale * (y - this.yStart)); } update(position: Position) { if (position.treeStats.maxDepth > 0) { let plot = position.toPlay == Color.Black ? this.plots[1] : this.plots[0]; plot[position.moveNum] = position.treeStats.maxDepth; this.yStart = Math.max(this.yStart, position.treeStats.maxDepth); } this.xEnd = Math.max(this.xEnd, position.moveNum); this.draw(); } } class WinrateGraph extends Graph { private plots: number[][] = [[], []]; constructor(elem: string) { super(elem, {xStart: -1, xEnd: 1, yStart: 0, yEnd: 10, yTicks: true}); } newGame() { for (let plot of this.plots) { plot.length = 0; } this.yEnd = 10; this.moveNum = 0; this.draw(); } drawImpl() { this.yEnd = Math.max(this.yEnd, this.moveNum); super.drawImpl(); let pr = util.pixelRatio(); let ctx = this.ctx; // Draw a dotted line for the current move number. this.drawPlot( [[this.xStart, this.moveNum], [this.xEnd, this.moveNum]], { dash: [0, 3], width: 1, style: '#96928f', snap: true, }); // Draw the plots. for (let i = 0; i < this.plots.length; ++i) { let plot = this.plots[i]; let points: number[][] = []; for (let y = 0; y < plot.length; ++y) { if (plot[y] != null) { points.push([-plot[y], y]); } } this.drawPlot(points, { width: 3, style: i == 0 ? '#fff' : '#000', }); } } update(position: Position) { if (position.n > 0) { // Q is only valid if we've performed at least one read. let plot = position.toPlay == Color.Black ? this.plots[1] : this.plots[0]; if (position.q != null) { plot[position.moveNum] = position.q; } } this.yEnd = Math.max(this.yEnd, position.moveNum); this.draw(); } } // App base class used by the different Minigui UI implementations. class VsApp { private players: Player[] = []; private black: Player; // = players[0] private white: Player; // = players[1] private currPlayer: Player; private nextPlayer: Player; private winrateGraph = new WinrateGraph('winrate-graph'); private readsGraph = new ReadsGraph('reads-graph'); private activeMoveNum = 0; private maxMoveNum = 0; private paused = false; private engineThinking = false; private gameOver = false; private startNextGameTimerId: Nullable<number> = null; constructor() { this.connect().then(() => { this.initEventListeners(); this.newGame(); }); } private initEventListeners() { for (let player of this.players) { player.gtp.onData('mg-update', (j: Position.Update) => { player.updatePosition(j); if (player.latestPosition != null) { this.winrateGraph.update(player.latestPosition); this.readsGraph.update(player.latestPosition); } }); player.gtp.onData('mg-position', (j: Position.Definition | Position.Update) => { let position = new Position(j as Position.Definition); position.update(j); this.maxMoveNum = Math.max(this.maxMoveNum, position.moveNum); if (player.latestPosition != null && position.lastMove != null) { // Copy the principal variation from the parent node. let gtpMove = toGtp(position.lastMove); let variation = player.latestPosition.variations.get(gtpMove); if (variation != null && !position.variations.has(gtpMove)) { variation = { n: variation.n, q: variation.q, moves: variation.moves.slice(1), }; position.variations.set(gtpMove, variation); position.variations.set('pv', variation); } } player.addPosition(position); this.winrateGraph.update(position); this.readsGraph.update(position); if (player.board.position.moveNum + 1 == position.moveNum) { this.selectMove(position.moveNum); } }); } window.addEventListener('keydown', (e: KeyboardEvent) => { if (this.isInLog(document.activeElement)) { return; } let handled = true; switch (e.key) { case 'ArrowUp': case 'ArrowLeft': this.goBack(1); break; case 'ArrowRight': case 'ArrowDown': this.goForward(1); break; case 'PageUp': this.goBack(10); break; case 'PageDown': this.goForward(10); break; case 'Home': this.goBack(Infinity); break; case 'End': this.goForward(Infinity); break; default: handled = false; break; } if (handled) { e.preventDefault(); return false; } }); window.addEventListener('wheel', (e: WheelEvent) => { if (this.isInLog(e.target as Element)) { return; } let delta: number; if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) { delta = e.deltaX; } else { delta = e.deltaY; } if (delta < 0) { this.goBack(1); } else if (delta > 0) { this.goForward(1); } }); let pauseElem = util.getElement('pause'); pauseElem.addEventListener('click', () => { this.paused = !this.paused; pauseElem.innerText = this.paused ? 'Resume' : 'Pause'; if (!this.paused && !this.engineThinking) { if (this.gameOver) { if (this.startNextGameTimerId != null) { window.clearTimeout(this.startNextGameTimerId); this.startNextGameTimerId = null; } this.startNextGame(); } else { this.genmove(); } } }); } private isInLog(elem: Nullable<Element>) { while (elem != null) { if (elem.classList.contains('log-container')) { return true; } elem = elem.parentElement; } return false; } private goBack(n: number) { this.selectMove(this.activeMoveNum - n); } private goForward(n: number) { this.selectMove(this.activeMoveNum + n); } private selectMove(moveNum: number) { this.activeMoveNum = Math.max(0, Math.min(moveNum, this.maxMoveNum)); for (let player of this.players) { player.selectMove(this.activeMoveNum); if (player.color == player.board.position.toPlay) { player.nameElem.classList.add('underline'); } else { player.nameElem.classList.remove('underline'); } player.scrollToBookmark(moveNum); } this.winrateGraph.setMoveNum(this.activeMoveNum); this.readsGraph.setMoveNum(this.activeMoveNum); this.updatePositionInfo(); } private onGameOver() { this.gameOver = true; this.currPlayer.gtp.send('final_score').then((score: string) => { if (score[0] == 'B') { this.black.numWins += 1; } else { this.white.numWins += 1; } this.updatePlayerDisplay(); }).finally(() => { // Wait a few seconds, then start the next game. this.startNextGameTimerId = window.setTimeout(() => { if (!this.paused) { this.startNextGame(); } }, 5000); }); } private startNextGame() { // Swap which engine is black and which is white, making sure the black // board is always on the left. for (let prop of ['color', 'board', 'log']) { let b = this.black as any; let w = this.white as any; [b[prop], w[prop]] = [w[prop], b[prop]]; } [this.black, this.white] = [this.white, this.black]; [this.currPlayer, this.nextPlayer] = [this.black, this.white]; this.newGame(); this.updatePlayerDisplay(); } private updatePlayerDisplay() { for (let player of this.players) { player.nameElem.innerText = player.name; player.scoreElem.innerText = player.numWins.toString(); } } private updatePositionInfo() { let position = this.currPlayer.activePosition; if (position != null) { this.black.capturesElem.innerText = position.captures[0].toString(); this.white.capturesElem.innerText = position.captures[1].toString(); util.getElement('move-num').innerText = `move: ${this.activeMoveNum}`; } } private genmove() { let gtpCol = gtpColor(this.currPlayer.color); this.engineThinking = true; let currPosition = this.currPlayer.latestPosition; if (currPosition != null) { this.currPlayer.setBookmark(currPosition.moveNum); } this.currPlayer.startGenmoveTimer(); this.currPlayer.gtp.send(`genmove ${gtpCol}`).then((gtpMove: string) => { if (gtpMove == 'resign') { this.onGameOver(); } if (this.currPlayer.latestPosition != null && this.currPlayer.latestPosition.gameOver) { this.onGameOver(); } else { if (currPosition != null) { this.nextPlayer.setBookmark(currPosition.moveNum); } this.nextPlayer.gtp.send(`play ${gtpCol} ${gtpMove}`).then(() => { [this.currPlayer, this.nextPlayer] = [this.nextPlayer, this.currPlayer]; if (!this.paused && !this.gameOver) { this.genmove(); } }); } }).finally(() => { this.engineThinking = false; this.currPlayer.stopGenmoveTimer(); }); } protected connect() { let uri = `http://${document.domain}:${location.port}/minigui`; let params = new URLSearchParams(window.location.search); let p = params.get('gtp_debug'); let debug = (p != null) && (p == '' || p == '1' || p.toLowerCase() == 'true'); return fetch('config').then((response) => { return response.json(); }).then((cfg: any) => { // TODO(tommadams): Give cfg a real type. // setBoardSize sets the global variable N to the board size for the game // (as provided by the backend engine). The code uses N from hereon in. setBoardSize(cfg.boardSize); if (cfg.players.length != 2) { throw new Error(`expected 2 players, got ${cfg.players}`); } let promises = []; for (let i = 0; i < cfg.players.length; ++i) { let color = [Color.Black, Color.White][i]; let name = cfg.players[i]; let player = new Player(color, name); this.players.push(player); promises.push(player.gtp.connect(uri, name, debug)); } [this.black, this.white] = this.players; [this.currPlayer, this.nextPlayer] = this.players; return Promise.all(promises); }); } protected newGame() { this.gameOver = false; this.activeMoveNum = 0; this.maxMoveNum = 0; this.winrateGraph.newGame(); this.readsGraph.newGame(); this.updatePlayerDisplay(); let promises: Promise<any>[] = []; for (let player of this.players) { player.newGame(); promises.push(player.gtp.send('clear_board')); } Promise.all(promises).then(() => { this.selectMove(0); this.genmove(); }); } } (window as any)['app'] = new VsApp();
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { Endpoint, EndpointsListByProfileOptionalParams, ResourceUsage, EndpointsListResourceUsageOptionalParams, EndpointsGetOptionalParams, EndpointsGetResponse, EndpointsCreateOptionalParams, EndpointsCreateResponse, EndpointUpdateParameters, EndpointsUpdateOptionalParams, EndpointsUpdateResponse, EndpointsDeleteOptionalParams, EndpointsStartOptionalParams, EndpointsStartResponse, EndpointsStopOptionalParams, EndpointsStopResponse, PurgeParameters, EndpointsPurgeContentOptionalParams, LoadParameters, EndpointsLoadContentOptionalParams, ValidateCustomDomainInput, EndpointsValidateCustomDomainOptionalParams, EndpointsValidateCustomDomainResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a Endpoints. */ export interface Endpoints { /** * Lists existing CDN endpoints. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param options The options parameters. */ listByProfile( resourceGroupName: string, profileName: string, options?: EndpointsListByProfileOptionalParams ): PagedAsyncIterableIterator<Endpoint>; /** * Checks the quota and usage of geo filters and custom domains under the given endpoint. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ listResourceUsage( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsListResourceUsageOptionalParams ): PagedAsyncIterableIterator<ResourceUsage>; /** * Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ get( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsGetOptionalParams ): Promise<EndpointsGetResponse>; /** * Creates a new CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param endpoint Endpoint properties * @param options The options parameters. */ beginCreate( resourceGroupName: string, profileName: string, endpointName: string, endpoint: Endpoint, options?: EndpointsCreateOptionalParams ): Promise< PollerLike< PollOperationState<EndpointsCreateResponse>, EndpointsCreateResponse > >; /** * Creates a new CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param endpoint Endpoint properties * @param options The options parameters. */ beginCreateAndWait( resourceGroupName: string, profileName: string, endpointName: string, endpoint: Endpoint, options?: EndpointsCreateOptionalParams ): Promise<EndpointsCreateResponse>; /** * Updates an existing CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. Only tags can be updated after creating an endpoint. To update origins, * use the Update Origin operation. To update origin groups, use the Update Origin group operation. To * update custom domains, use the Update Custom Domain operation. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param endpointUpdateProperties Endpoint update properties * @param options The options parameters. */ beginUpdate( resourceGroupName: string, profileName: string, endpointName: string, endpointUpdateProperties: EndpointUpdateParameters, options?: EndpointsUpdateOptionalParams ): Promise< PollerLike< PollOperationState<EndpointsUpdateResponse>, EndpointsUpdateResponse > >; /** * Updates an existing CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. Only tags can be updated after creating an endpoint. To update origins, * use the Update Origin operation. To update origin groups, use the Update Origin group operation. To * update custom domains, use the Update Custom Domain operation. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param endpointUpdateProperties Endpoint update properties * @param options The options parameters. */ beginUpdateAndWait( resourceGroupName: string, profileName: string, endpointName: string, endpointUpdateProperties: EndpointUpdateParameters, options?: EndpointsUpdateOptionalParams ): Promise<EndpointsUpdateResponse>; /** * Deletes an existing CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ beginDelete( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes an existing CDN endpoint with the specified endpoint name under the specified subscription, * resource group and profile. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsDeleteOptionalParams ): Promise<void>; /** * Starts an existing CDN endpoint that is on a stopped state. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ beginStart( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsStartOptionalParams ): Promise< PollerLike< PollOperationState<EndpointsStartResponse>, EndpointsStartResponse > >; /** * Starts an existing CDN endpoint that is on a stopped state. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ beginStartAndWait( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsStartOptionalParams ): Promise<EndpointsStartResponse>; /** * Stops an existing running CDN endpoint. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ beginStop( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsStopOptionalParams ): Promise< PollerLike<PollOperationState<EndpointsStopResponse>, EndpointsStopResponse> >; /** * Stops an existing running CDN endpoint. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param options The options parameters. */ beginStopAndWait( resourceGroupName: string, profileName: string, endpointName: string, options?: EndpointsStopOptionalParams ): Promise<EndpointsStopResponse>; /** * Removes a content from CDN. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param contentFilePaths The path to the content to be purged. Path can be a full URL, e.g. * '/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g. '/pictures/*' * which removes all folders and files in the directory. * @param options The options parameters. */ beginPurgeContent( resourceGroupName: string, profileName: string, endpointName: string, contentFilePaths: PurgeParameters, options?: EndpointsPurgeContentOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Removes a content from CDN. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param contentFilePaths The path to the content to be purged. Path can be a full URL, e.g. * '/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g. '/pictures/*' * which removes all folders and files in the directory. * @param options The options parameters. */ beginPurgeContentAndWait( resourceGroupName: string, profileName: string, endpointName: string, contentFilePaths: PurgeParameters, options?: EndpointsPurgeContentOptionalParams ): Promise<void>; /** * Pre-loads a content to CDN. Available for Verizon Profiles. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param contentFilePaths The path to the content to be loaded. Path should be a full URL, e.g. * ‘/pictures/city.png' which loads a single file * @param options The options parameters. */ beginLoadContent( resourceGroupName: string, profileName: string, endpointName: string, contentFilePaths: LoadParameters, options?: EndpointsLoadContentOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Pre-loads a content to CDN. Available for Verizon Profiles. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param contentFilePaths The path to the content to be loaded. Path should be a full URL, e.g. * ‘/pictures/city.png' which loads a single file * @param options The options parameters. */ beginLoadContentAndWait( resourceGroupName: string, profileName: string, endpointName: string, contentFilePaths: LoadParameters, options?: EndpointsLoadContentOptionalParams ): Promise<void>; /** * Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param profileName Name of the CDN profile which is unique within the resource group. * @param endpointName Name of the endpoint under the profile which is unique globally. * @param customDomainProperties Custom domain to be validated. * @param options The options parameters. */ validateCustomDomain( resourceGroupName: string, profileName: string, endpointName: string, customDomainProperties: ValidateCustomDomainInput, options?: EndpointsValidateCustomDomainOptionalParams ): Promise<EndpointsValidateCustomDomainResponse>; }
the_stack
import cheerio from 'cheerio'; import htmlToText from 'html-to-text'; import * as _ from 'underscore'; import { Comments } from '../lib/collections/comments/collection'; import { questionAnswersSort } from '../lib/collections/comments/views'; import { postGetCommentCountStr } from '../lib/collections/posts/helpers'; import { Revisions } from '../lib/collections/revisions/collection'; import { answerTocExcerptFromHTML, truncate } from '../lib/editor/ellipsize'; import { forumTypeSetting } from '../lib/instanceSettings'; import { Utils } from '../lib/vulcan-lib'; import { updateDenormalizedHtmlAttributions } from './resolvers/tagResolvers'; import { annotateAuthors } from './attributeEdits'; export interface ToCSection { title?: string answer?: any anchor: string level: number divider?: boolean, } export interface ToCData { html: string|null sections: ToCSection[] headingsCount: number } // Number of headings below which a table of contents won't be generated. const MIN_HEADINGS_FOR_TOC = 3; // Tags which define headings. Currently <h1>-<h4>, <strong>, and <b>. Excludes // <h5> and <h6> because their usage in historical (HTML) wasn't as a ToC- // worthy heading. const headingTags = { h1: 1, h2: 2, h3: 3, h4: 4, // <b> and <strong> are at the same level strong: 7, b: 7, } const headingIfWholeParagraph = { strong: true, b: true, }; const headingSelector = _.keys(headingTags).join(","); // Given an HTML document, extract a list of sections for a table of contents // from it, and add anchors. The result is modified HTML with added anchors, // plus a JSON array of sections, where each section has a // `title`, `anchor`, and `level`, like this: // { // html: "<a anchor=...">, // sections: [ // {title: "Preamble", anchor: "preamble", level: 1}, // {title: "My Cool Idea", anchor: "mycoolidea", level: 1}, // {title: "An Aspect of My Cool Idea", anchor:"anaspectofmycoolidea", level: 2}, // {title: "Why This Is Neat", anchor:"whythisisneat", level: 2}, // {title: "Conclusion", anchor: "conclusion", level: 1}, // ] // } export function extractTableOfContents(postHTML: string) { if (!postHTML) return null; // @ts-ignore DefinitelyTyped annotation is wrong, and cheerio's own annotations aren't ready yet const postBody = cheerio.load(postHTML, null, false); let headings: Array<ToCSection> = []; let usedAnchors: Record<string,boolean> = {}; // First, find the headings in the document, create a linear list of them, // and insert anchors at each one. let headingTags = postBody(headingSelector); for (let i=0; i<headingTags.length; i++) { let tag = headingTags[i]; if (tag.type !== "tag") { continue; } if (tagIsHeadingIfWholeParagraph(tag.tagName) && !tagIsWholeParagraph(tag)) { continue; } let title = elementToToCText(tag); if (title && title.trim()!=="") { let anchor = titleToAnchor(title, usedAnchors); usedAnchors[anchor] = true; cheerio(tag).attr("id", anchor); headings.push({ title: title, anchor: anchor, level: tagToHeadingLevel(tag.tagName), }); } } // Filter out unused heading levels, mapping the heading levels to consecutive // numbers starting from 1. So if a post uses <h1>, <h3> and <strong>, those // will be levels 1, 2, and 3 (not 1, 3 and 7). // Get a list of heading levels used let headingLevelsUsedDict: Partial<Record<number,boolean>> = {}; for(let i=0; i<headings.length; i++) headingLevelsUsedDict[headings[i].level] = true; // Generate a mapping from raw heading levels to compressed heading levels let headingLevelsUsed = _.keys(headingLevelsUsedDict).sort(); let headingLevelMap = {}; for(let i=0; i<headingLevelsUsed.length; i++) headingLevelMap[ headingLevelsUsed[i] ] = i; // Mark sections with compressed heading levels for(let i=0; i<headings.length; i++) headings[i].level = headingLevelMap[headings[i].level]+1; if (headings.length) { headings.push({divider:true, level: 0, anchor: "postHeadingsDivider"}) } return { html: postBody.html(), sections: headings, headingsCount: headings.length } } function elementToToCText(cheerioTag: cheerio.Element) { const tagHtml = cheerio(cheerioTag).html(); if (!tagHtml) return null; const tagClone = cheerio.load(tagHtml); tagClone("style").remove(); return tagClone.root().text(); } const reservedAnchorNames = ["top", "comments"]; // Given the text in a heading block and a dict of anchors that have been used // in the post so far, generate an anchor, and return it. An anchor is a // URL-safe string that can be used for within-document links, and which is // not one of a few reserved anchor names. function titleToAnchor(title: string, usedAnchors: Record<string,boolean>): string { let charsToUse = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789"; let sb: Array<string> = []; for(let i=0; i<title.length; i++) { let ch = title.charAt(i); if(charsToUse.indexOf(ch) >= 0) { sb.push(ch); } else { sb.push('_'); } } let anchor = sb.join(''); if(!usedAnchors[anchor] && !_.find(reservedAnchorNames, x=>x===anchor)) return anchor; let anchorSuffix = 1; while(usedAnchors[anchor + anchorSuffix]) anchorSuffix++; return anchor+anchorSuffix; } // `<b>` and `<strong>` tags are headings iff they are the only thing in their // paragraph. Return whether the given tag name is a tag with that property // (ie, is `<strong>` or `<b>`). function tagIsHeadingIfWholeParagraph(tagName: string): boolean { return tagName.toLowerCase() in headingIfWholeParagraph; } function tagIsWholeParagraph(tag): boolean { if (!tag) return false; let parents = cheerio(tag).parent(); if (!parents || !parents.length) return false; let parent = parents[0]; if (parent.type !== 'tag') return false; if (parent.tagName.toLowerCase() !== 'p') return false; let selfAndSiblings = cheerio(parent).contents(); if (selfAndSiblings.length != 1) return false; return true; } function tagToHeadingLevel(tagName: string): number { let lowerCaseTagName = tagName.toLowerCase(); if (lowerCaseTagName in headingTags) return headingTags[lowerCaseTagName]; else if (lowerCaseTagName in headingIfWholeParagraph) return headingIfWholeParagraph[lowerCaseTagName]; else return 0; } async function getTocAnswers (document: DbPost) { if (!document.question) return [] let answersTerms: MongoSelector<DbComment> = { answer:true, postId: document._id, deleted:false, } if (forumTypeSetting.get() === 'AlignmentForum') { answersTerms.af = true } const answers = await Comments.find(answersTerms, {sort:questionAnswersSort}).fetch() const answerSections: ToCSection[] = answers.map((answer: DbComment): ToCSection => { const { html = "" } = answer.contents || {} const highlight = truncate(html, 900) let shortHighlight = htmlToText.fromString(answerTocExcerptFromHTML(html), {ignoreImage:true, ignoreHref:true}) return { title: `${answer.baseScore} ${answer.author}`, answer: { baseScore: answer.baseScore, voteCount: answer.voteCount, postedAt: answer.postedAt, author: answer.author, highlight, shortHighlight, }, anchor: answer._id, level: 2 }; }) if (answerSections.length) { return [ {anchor: "answers", level:1, title:'Answers'}, ...answerSections, {divider:true, level: 0, anchor: "postAnswersDivider"} ] } else { return [] } } async function getTocComments (document: DbPost) { const commentSelector: any = { ...Comments.defaultView({}).selector, answer: false, parentAnswerId: null, postId: document._id } if (document.af && forumTypeSetting.get() === 'AlignmentForum') { commentSelector.af = true } const commentCount = await Comments.find(commentSelector).count() return [{anchor:"comments", level:0, title: postGetCommentCountStr(document, commentCount)}] } const getToCforPost = async ({document, version, context}: { document: DbPost, version: string|null, context: ResolverContext, }): Promise<ToCData|null> => { let html: string; if (version) { const revision = await Revisions.findOne({documentId: document._id, version, fieldName: "contents"}) if (!revision) return null; if (!await Revisions.checkAccess(context.currentUser, revision, context)) return null; html = revision.html; } else { html = document?.contents?.html; } const tableOfContents = extractTableOfContents(html) let tocSections = tableOfContents?.sections || [] if (tocSections.length >= MIN_HEADINGS_FOR_TOC) { const tocAnswers = await getTocAnswers(document) const tocComments = await getTocComments(document) tocSections.push(...tocAnswers) tocSections.push(...tocComments) return { html: tableOfContents?.html||null, sections: tocSections, headingsCount: tocSections.length } } return null; } const getToCforTag = async ({document, version, context}: { document: DbTag, version: string|null, context: ResolverContext, }): Promise<ToCData|null> => { let html: string; if (version) { try { html = await annotateAuthors(document._id, "Tags", "description", version); } catch(e) { // eslint-disable-next-line no-console console.log("Author annotation failed"); // eslint-disable-next-line no-console console.log(e); const revision = await Revisions.findOne({documentId: document._id, version, fieldName: "description"}) if (!revision) return null; if (!await Revisions.checkAccess(context.currentUser, revision, context)) return null; html = revision.html; } } else { try { if (document.htmlWithContributorAnnotations) { html = document.htmlWithContributorAnnotations; } else { html = await updateDenormalizedHtmlAttributions(document); } } catch(e) { // eslint-disable-next-line no-console console.log("Author annotation failed"); // eslint-disable-next-line no-console console.log(e); html = document.description?.html; } } const tableOfContents = extractTableOfContents(html) let tocSections = tableOfContents?.sections || [] return { html: tableOfContents?.html||null, sections: tocSections, headingsCount: tocSections.length } } Utils.getToCforPost = getToCforPost; Utils.getToCforTag = getToCforTag;
the_stack
import type { DataStore, SortParams, Schema, BaseConfig } from '@tanker/datastore-base'; import { errors as dbErrors, transform } from '@tanker/datastore-base'; const { deserializeBinary: fromDB, serializeBinary: toDB } = transform; export type Config = BaseConfig; export type { Schema }; function extractSortKey(sort: SortParams): string { const [sortParam] = sort; if (typeof sortParam === 'string') return sortParam; const [sortKey] = Object.keys(sortParam as Record<string, any>); return sortKey!; } /* eslint-disable no-underscore-dangle */ export default ((PouchDB: any, prefix?: string) => class PouchDBStoreBase implements DataStore { declare _dbs: Record<string, typeof PouchDB>; constructor(dbs: Record<string, typeof PouchDB>) { // _ properties won't be enumerable, nor reconfigurable Object.defineProperty(this, '_dbs', { value: dbs, writable: true }); return this; } get className(): string { return this.constructor.name; } parallelEachDb<R>(fun: (arg0: typeof PouchDB) => Promise<R>): Promise<Array<R>> { const promises = Object.keys(this._dbs!).map(k => fun(this._dbs[k]!)); return Promise.all(promises); } async close(): Promise<void> { if (!this._dbs) return; try { await this.parallelEachDb((db: PouchDBStoreBase) => db.close()); // @ts-expect-error this._dbs = null; } catch (error) { console.error(`Error when closing ${this.className}: `, error); } } /// WARNING: This WILL destroy ALL YOUR DATA! No refunds. async destroy(): Promise<void> { if (!this._dbs) return; await this.parallelEachDb(db => db.destroy()); // @ts-expect-error this._dbs = null; } async clear(table: string): Promise<void> { // naive RAM-consuming implementation const records = await this.getAll(table); records.forEach(record => { record['_deleted'] = true; }); // eslint-disable-line await this._dbs[table].bulkDocs(records); } static async open(config: BaseConfig): Promise<PouchDBStoreBase> { if (!config) { throw new Error('Invalid empty config'); } const { dbName, schemas } = config; if (!dbName) { throw new Error('Invalid empty dbName in config'); } if (!schemas) { throw new Error('The PouchDB adapter requires schemas in open()\'s config'); } const openingDatabases: Record<string, Promise<void>> = {}; const openedDatabases: Record<string, typeof PouchDB> = {}; // In PouchDB, each table requires its own database. We'll start creating // databases starting from the latest schema and going back in time to // delete flagged tables. const reversedSchemas = [...schemas].reverse(); for (const schema of reversedSchemas) { for (const table of schema.tables) { const { name, deleted } = table; // Open db only if not already opening if (!(name in openingDatabases)) { openingDatabases[name] = (async () => { const db = await this._openDatabase({ dbName, tableName: name, }); // Immediately destroy deleted databases if (deleted) { await db.destroy(); } else { openedDatabases[name] = db; } })(); } } } // Waiting for parallel opening to finish await Promise.all(Object.values(openingDatabases)); const store = new PouchDBStoreBase(openedDatabases); await store.defineSchemas(schemas); return store; } static async _openDatabase(config: Record<string, any>): Promise<typeof PouchDB> { const { dbName, tableName } = config; const name = `${dbName}_${tableName}`; // wait for the db to be ready before returning the store return new Promise((resolve, reject) => { // but timeout after 30s if db not ready yet // declare error outside the setTimeout for a better callstack const error = new Error(`Could not open PouchDB for: ${name}`); const timeout = setTimeout(() => reject(error), 30000); try { const db = new PouchDB(prefix ? prefix + name : name); db.addListener('created', () => resolve(db)); // resolve if already created if (db.taskqueue.isReady) { resolve(db); } } catch (e) { reject(e); } clearTimeout(timeout); }); } async defineSchemas(schemas: Array<Schema>): Promise<void> { // Create indexes from the latest schema only const schema = schemas[schemas.length - 1]!; const { tables } = schema; for (const table of tables) { const { name, indexes, deleted } = table; // Skip deleted tables if (!deleted && indexes) { for (const index of indexes) { await this._dbs[name].createIndex({ index: { fields: index } }); } } } } add = async (table: string, record: Record<string, any>) => { try { const recordWithoutRev = { ...record }; delete recordWithoutRev['_rev']; const result = await this._dbs[table].put(toDB(recordWithoutRev)); return { ...recordWithoutRev, _rev: result.rev }; } catch (err) { const e = err as Error & { status: number }; if (e.status === 409) { throw new dbErrors.RecordNotUnique(e); } throw new dbErrors.UnknownError(e); } }; put = async (table: string, record: Record<string, any>) => { const rec = { ...record }; try { if (typeof rec['_rev'] !== 'string') { try { const result = await this.get(table, rec['_id']); rec['_rev'] = result._rev; } catch (e) { if (!(e instanceof dbErrors.RecordNotFound)) { throw e; } } } await this._dbs[table].put(toDB(rec)); } catch (err) { const e = err as Error & { status: number }; if (e.status === 409) { throw new dbErrors.RecordNotUnique(e); } throw new dbErrors.UnknownError(e); } }; // Warning: will only update the records that contain _id // since it is required for bulkDocs to operate. // see: https://pouchdb.com/api.html#batch_create bulkAdd = async (table: string, records: Array<Record<string, any>> | Record<string, any>, ...otherRecords: Array<Record<string, any>>) => { const all = (records instanceof Array) ? records : [records, ...otherRecords]; try { const allWithoutRevs = all.map(record => { const recordWithoutRev = { ...record }; delete recordWithoutRev['_rev']; return recordWithoutRev; }); await this._dbs[table].bulkDocs(toDB(allWithoutRevs)); } catch (err) { const e = err as Error & { status: number }; if (e.status === 409) { throw new dbErrors.RecordNotUnique(e); } throw new dbErrors.UnknownError(e); } }; // Warning: will only update the records that contain both _id and _rev keys, // since they are both required for bulkDocs to operate. // see: https://pouchdb.com/api.html#batch_create bulkPut = async (table: string, records: Array<Record<string, any>> | Record<string, any>, ...otherRecords: Array<Record<string, any>>) => { let all = (records instanceof Array) ? records : [records, ...otherRecords]; try { // find records with missing _rev const ids = all.filter(rec => typeof rec['_rev'] !== 'string').map(rec => rec['_id']); if (ids.length > 0) { const idToRev: Record<string, any> = {}; const previousRecords: Array<Record<string, any>> = await this.find(table, { selector: { _id: { $in: ids } } }); previousRecords.forEach(rec => { idToRev[rec['_id']] = rec['_rev']; }); // add missing _rev all = all.map(rec => { const rev = idToRev[rec['_id']]; return rev ? { ...rec, _rev: rev } : rec; }); } await this._dbs[table].bulkDocs(toDB(all)); } catch (err) { const e = err as Error & { status: number }; if (e.status === 409) { throw new dbErrors.RecordNotUnique(e); } throw new dbErrors.UnknownError(e); } }; bulkDelete = async (table: string, records: Array<Record<string, any>> | Record<string, any>, ...otherRecords: Array<Record<string, any>>) => { const allRecords = (records instanceof Array) ? records : [records, ...otherRecords]; const idsToDelete = allRecords.map(r => r['_id']); // This round trip is required to ensure the _rev key is present in records // so that the bulkDocs() call in bulkPut will properly update the records. const recordsToDelete: Array<Record<string, any>> = await this.find(table, { selector: { _id: { $in: idsToDelete } } }); return this.bulkPut(table, recordsToDelete.map(r => ({ ...r, _deleted: true }))); }; get = async (table: string, id: string) => { try { return fromDB(await this._dbs[table].get(id)); } catch (err) { const e = err as Error & { status: number }; if (e.status === 404) { throw new dbErrors.RecordNotFound(e); } else { throw new dbErrors.UnknownError(e); } } }; getAll = async (table: string) => { const result: PouchDB.Core.AllDocsResponse<any> = await this._dbs[table].allDocs({ include_docs: true }); const records: Array<Record<string, any>> = []; result.rows.forEach(row => { const { doc } = row; // skip _design records stored alongside the data! if (doc._id.substr(0, 7) !== '_design') { records.push(fromDB(doc)); } }); return records; }; find = async (table: string, query: { selector?: Record<string, any>; sort?: SortParams; limit?: number; } = {}) => { const { selector: optSelector, sort } = query; const selector = optSelector || { _id: { $exists: true } }; // PouchDB cannot sort if the field is not present in the selector too if (sort) { const sortKey = extractSortKey(sort); if (!selector[sortKey]) { selector[sortKey] = { $gte: null }; // dumb selector to get all } } const { docs } = await this._dbs[table].find({ ...query, selector }); const records = fromDB(docs); return records; }; first = async (table: string, query: { selector?: Record<string, any>; sort?: SortParams; } = {}) => { const results = await this.find(table, { ...query, limit: 1 }); return results[0]; }; delete = async (table: string, id: string) => { try { const recordToDelete = await this.get(table, id); await this.put(table, { ...recordToDelete, _deleted: true }); } catch (e) { if (!(e instanceof dbErrors.RecordNotFound)) { throw e; } } }; });
the_stack
import anyTest, { TestInterface } from 'ava'; import { NohmClass } from '../ts'; import * as child_process from 'child_process'; import * as testArgs from './testArgs'; import { cleanUpPromise, sleep } from './helper'; import { IPropertyDiff } from '../ts/model.header'; import { register } from './pubsub/Model'; interface IChildProcessWithAsk extends child_process.ChildProcess { ask(...args: Array<any>): Promise<void>; } const test = anyTest as TestInterface<{ child: IChildProcessWithAsk; nohm: NohmClass; prefix: string; }>; const prefix = testArgs.prefix + 'pubsub'; let testCounter = 0; // We create a child process with a question/answer protocol to ./pubsub/child.ts . // The returned object has a "child" node which is a normal child_process.fork but with an added .ask() method that // resolves once the question has been acknowledged (e.g. the child.ts process was asked to subscribe and sends ACK // after it has done so) and receives a callback argument that is called for each answer it has (e.g. for a subscribe // it is called every time the subscription yields a published event) const initializeChild = (childPrefix) => { return new Promise<IChildProcessWithAsk>((resolve, reject) => { const child = child_process.fork(childPath, process.argv); child.on('message', (msg) => { if (msg.question === 'initialize' && msg.answer === true) { resolve(child as IChildProcessWithAsk); } if (msg.error) { console.error( 'Error message from child process in pubsub tests!', msg.error, ); reject(msg.error); process.exit(1); } }); (child as any).ask = (request, callback) => { return new Promise((resolveInner) => { child.on('message', (msg) => { if (msg.question === request.question) { if (msg.answer === 'ACK') { // this happens on things like subscribe where it acknowledges the subscribe has happened resolveInner(); } else { // in case of a subscribe this is a message the subscription has received callback(msg); } } }); child.send(request); }); }; child.send({ question: 'initialize', args: { prefix: childPrefix } }); }); }; test.beforeEach(async (t) => { // setup a local nohm for each test with a separate prefix, so that they can run concurrently const localPrefix = `${prefix}/t${++testCounter}/`; const localNohm = new NohmClass({ prefix: localPrefix, }); await testArgs.setClient(localNohm, testArgs.redis); await cleanUpPromise(testArgs.redis, localPrefix); register(localNohm); t.context.child = await initializeChild(localPrefix); t.context.nohm = localNohm; t.context.prefix = localPrefix; }); test.afterEach(async (t) => { await cleanUpPromise(testArgs.redis, t.context.prefix); }); const childPath = __dirname + '/pubsub/child_wrapper.js'; const secondaryClient = testArgs.secondaryClient; test('set/get pubSub client', async (t) => { await t.context.nohm.setPubSubClient(secondaryClient); const client = t.context.nohm.getPubSubClient(); t.is(client, secondaryClient, "Second redis client wasn't set properly"); const isIoRedis = client.connected === undefined && (client as any).status === 'ready'; if (isIoRedis) { t.true( (client as any).condition.subscriber !== false, "Second redis client isn't subscribed to anything", ); } else { t.truthy( (client as any).subscription_set, "Second redis client isn't subscribed to to any channels", ); } }); test('close pubSub client', async (t) => { await t.context.nohm.setPubSubClient(secondaryClient); const client = await t.context.nohm.closePubSub(); t.is(client, secondaryClient, 'closePubSub returned a wrong redis client'); }); test('set/get publish bool', async (t) => { const noPublish = await t.context.nohm.factory('no_publish'); t.false( // @ts-ignore noPublish.getPublish(), 'model without publish returned true', ); const publish = await t.context.nohm.factory('Tester'); // @ts-ignore t.true(publish.getPublish(), 'model with publish returned false'); t.context.nohm.setPublish(true); t.true( // @ts-ignore noPublish.getPublish(), 'model without publish but global publish returned false', ); t.context.nohm.setPublish(false); t.true( // @ts-ignore publish.getPublish(), 'model with publish and global publish false returned false', ); }); test.cb("nohm in child process doesn't have pubsub yet", (t) => { t.plan(1); const question = 'does nohm have pubsub?'; const child = child_process.fork(childPath); const checkNohmPubSubNotInitialized = (msg) => { if (msg.question === question) { t.is( msg.answer, undefined, 'PubSub in the child process was already initialized.', ); child.kill(); t.end(); } }; child.on('message', checkNohmPubSubNotInitialized); child.send({ question }); }); test.afterEach.cb((t) => { t.context.child.on('exit', () => { t.end(); }); t.context.child.kill(); }); test('create', async (t) => { t.plan(4); const instance = await t.context.nohm.factory('Tester'); instance.property('dummy', 'create'); const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribe', args: { event: 'create', modelName: 'Tester', }, }, (msg) => { const target = msg.answer.target; t.true( (instance.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instance.id, target.id, 'Id from create event wrong'); t.is( instance.modelName, target.modelName, 'Modelname from create event wrong', ); t.deepEqual( instance.allProperties(), target.properties, 'Properties from create event wrong', ); resolve(); }, ); await instance.save(); }); await childResponded; }); test('update', async (t) => { t.plan(5); const instance = await t.context.nohm.factory('Tester'); instance.property('dummy', 'update'); let diff: Array<void | IPropertyDiff<string | number | symbol>>; const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribe', args: { event: 'update', modelName: 'Tester', }, }, (msg) => { const answer = msg.answer; t.true( (instance.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instance.id, answer.target.id, 'Id from update event wrong'); t.is( instance.modelName, answer.target.modelName, 'Modelname from update event wrong', ); t.deepEqual( instance.allProperties(), answer.target.properties, 'Properties from update event wrong', ); t.deepEqual(diff, answer.target.diff, 'Diffs from update event wrong'); resolve(); }, ); await instance.save(); instance.property('dummy', 'updatededed'); diff = instance.propertyDiff(); await instance.save(); }); await childResponded; }); test('save', async (t) => { t.plan(8); const instance = await t.context.nohm.factory('Tester'); instance.property('dummy', 'save'); let counter = 0; const props: Array<any> = []; const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribe', args: { event: 'save', modelName: 'Tester', }, }, (msg) => { const answer = msg.answer; t.true( (instance.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instance.id, answer.target.id, 'Id from save event wrong'); t.is( instance.modelName, answer.target.modelName, 'Modelname from save event wrong', ); t.deepEqual( props[counter], answer.target.properties, 'Properties from save event wrong', ); counter++; if (counter >= 2) { resolve(); } }, ); await instance.save(); props.push(instance.allProperties()); instance.property('dummy', 'save_the_second'); props.push(instance.allProperties()); await instance.save(); }); await childResponded; }); test('remove', async (t) => { t.plan(4); const instance = await t.context.nohm.factory('Tester'); instance.property('dummy', 'remove'); let oldId; const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribe', args: { event: 'remove', modelName: 'Tester', }, }, (msg) => { const answer = msg.answer; t.is( instance.id, null, 'ID was not reset properly before the child returned the event.', ); t.is(oldId, answer.target.id, 'Id from remove event wrong'); t.is( instance.modelName, answer.target.modelName, 'Modelname from remove event wrong', ); t.deepEqual( instance.allProperties(), answer.target.properties, 'Properties from remove event wrong', ); resolve(); }, ); await instance.save(); oldId = instance.id; await instance.remove(); }); await childResponded; }); test('link', async (t) => { t.plan(8); const instanceChild = await t.context.nohm.factory('Tester'); const instanceParent = await t.context.nohm.factory('Tester'); instanceChild.property('dummy', 'link_child'); instanceParent.property('dummy', 'link_parent'); instanceChild.link(instanceParent); const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribe', args: { event: 'link', modelName: 'Tester', }, }, (msg) => { const answer = msg.answer; t.true( (instanceChild.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instanceChild.id, answer.child.id, 'Id from link event wrong'); t.is( instanceChild.modelName, answer.child.modelName, 'Modelname from link event wrong', ); t.deepEqual( instanceChild.allProperties(), answer.child.properties, 'Properties from link event wrong', ); t.true( (instanceParent.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instanceParent.id, answer.parent.id, 'Id from link event wrong'); t.is( instanceParent.modelName, answer.parent.modelName, 'Modelname from link event wrong', ); t.deepEqual( instanceParent.allProperties(), answer.parent.properties, 'Properties from link event wrong', ); resolve(); }, ); await instanceChild.save(); }); await childResponded; }); test('unlink', async (t) => { t.plan(8); const instanceChild = await t.context.nohm.factory('Tester'); const instanceParent = await t.context.nohm.factory('Tester'); instanceChild.property('dummy', 'unlink_child'); instanceParent.property('dummy', 'unlink_parent'); instanceChild.link(instanceParent); const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribe', args: { event: 'unlink', modelName: 'Tester', }, }, (msg) => { const answer = msg.answer; t.true( (instanceChild.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instanceChild.id, answer.child.id, 'Id from unlink event wrong'); t.is( instanceChild.modelName, answer.child.modelName, 'Modelname from unlink event wrong', ); t.deepEqual( instanceChild.allProperties(), answer.child.properties, 'Properties from unlink event wrong', ); t.true( (instanceParent.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instanceParent.id, answer.parent.id, 'Id from unlink event wrong'); t.is( instanceParent.modelName, answer.parent.modelName, 'Modelname from unlink event wrong', ); t.deepEqual( instanceParent.allProperties(), answer.parent.properties, 'Properties from unlink event wrong', ); resolve(); }, ); await instanceChild.save(); instanceChild.unlink(instanceParent); await instanceChild.save(); }); await childResponded; }); test('createOnce', async (t) => { // because testing a once event is a pain in the ass and really doesn't have many ways it can fail // if the on method on the same event works, we only do on once test. t.plan(5); const instance = await t.context.nohm.factory('Tester'); instance.property('dummy', 'create_once'); let answerCount = 0; const childResponded = new Promise(async (resolve) => { await t.context.child.ask( { question: 'subscribeOnce', args: { event: 'create', modelName: 'Tester', }, }, async (msg) => { const answer = msg.answer; answerCount++; t.true( (instance.id as any).length > 0, 'ID was not set properly before the child returned the event.', ); t.is(instance.id, answer.target.id, 'Id from createOnce event wrong'); t.is( instance.modelName, answer.target.modelName, 'Modelname from createOnce event wrong', ); t.deepEqual( instance.allProperties(), answer.target.properties, 'Properties from createOnce event wrong', ); const instanceInner = await t.context.nohm.factory('Tester'); instanceInner.property('dummy', 'create_once_again'); instanceInner.save(); setTimeout(() => { t.is( answerCount, 1, 'subscribeOnce called the callback more than once.', ); resolve(); }, 150); // this is fucked up :( }, ); await instance.save(); }); await childResponded; }); test('silenced', async (t) => { t.plan(1); const instance = await t.context.nohm.factory('Tester'); instance.property('dummy', 'silenced'); let answered = false; const events = ['create', 'update', 'save', 'remove', 'link', 'unlink']; await Promise.all( events.map((event) => { return t.context.child.ask( { question: 'subscribe', args: { event, modelName: 'Tester', }, }, (msg) => { if (msg.event === event) { console.log('Received message from child:', msg); answered = true; } }, ); }), ); await instance.save({ silent: true }); instance.property('dummy', 'updated'); await instance.save({ silent: true }); const second = await t.context.nohm.factory('Tester'); instance.link(second); await instance.save({ silent: true }); instance.unlink(second); await instance.save({ silent: true }); await instance.remove(true); await sleep(500); t.is(answered, false, 'There was an event!'); });
the_stack
import { ButtonGroup, Classes, Dialog, Intent, NonIdealState, Spinner } from '@blueprintjs/core'; import { IconNames } from '@blueprintjs/icons'; import classNames from 'classnames'; import * as React from 'react'; import { InterpreterOutput } from '../application/ApplicationTypes'; import { Assessment, AssessmentOverview, IMCQQuestion, IProgrammingQuestion, Library, Question, QuestionTypes, Testcase } from '../assessment/AssessmentTypes'; import { ControlBarProps } from '../controlBar/ControlBar'; import { ControlBarClearButton } from '../controlBar/ControlBarClearButton'; import { ControlBarEvalButton } from '../controlBar/ControlBarEvalButton'; import { ControlBarNextButton } from '../controlBar/ControlBarNextButton'; import { ControlBarPreviousButton } from '../controlBar/ControlBarPreviousButton'; import { ControlBarQuestionViewButton } from '../controlBar/ControlBarQuestionViewButton'; import { ControlBarResetButton } from '../controlBar/ControlBarResetButton'; import { ControlBarRunButton } from '../controlBar/ControlBarRunButton'; import { ControlButtonSaveButton } from '../controlBar/ControlBarSaveButton'; import { ControlBarToggleEditModeButton } from '../controlBar/ControlBarToggleEditModeButton'; import controlButton from '../ControlButton'; import { AutograderTab } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentAutograderTab'; import { DeploymentTab } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentDeploymentTab'; import { GradingTab } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentGradingTab'; import { ManageQuestionTab } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentManageQuestionTab'; import { MCQQuestionTemplateTab } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentMcqQuestionTemplateTab'; import { ProgrammingQuestionTemplateTab } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentProgrammingQuestionTemplateTab'; import { TextAreaContent } from '../editingWorkspaceSideContent/EditingWorkspaceSideContentTextAreaContent'; import { HighlightedLines, Position } from '../editor/EditorTypes'; import Markdown from '../Markdown'; import { SideContentProps } from '../sideContent/SideContent'; import SideContentToneMatrix from '../sideContent/SideContentToneMatrix'; import { SideContentTab, SideContentType } from '../sideContent/SideContentTypes'; import { history } from '../utils/HistoryHelper'; import Workspace, { WorkspaceProps } from '../workspace/Workspace'; import { WorkspaceState } from '../workspace/WorkspaceTypes'; import { retrieveLocalAssessment, storeLocalAssessment, storeLocalAssessmentOverview } from '../XMLParser/XMLParserHelper'; export type EditingWorkspaceProps = DispatchProps & StateProps & OwnProps; export type DispatchProps = { handleBrowseHistoryDown: () => void; handleBrowseHistoryUp: () => void; handleChapterSelect: (chapter: any, changeEvent: any) => void; handleClearContext: (library: Library, shouldInitLibrary: boolean) => void; handleDeclarationNavigate: (cursorPosition: Position) => void; handleEditorEval: () => void; handleEditorValueChange: (val: string) => void; handleEditorHeightChange: (height: number) => void; handleEditorWidthChange: (widthChange: number) => void; handleEditorUpdateBreakpoints: (breakpoints: string[]) => void; handleInterruptEval: () => void; handleReplEval: () => void; handleReplOutputClear: () => void; handleReplValueChange: (newValue: string) => void; handleResetWorkspace: (options: Partial<WorkspaceState>) => void; handleUpdateWorkspace: (options: Partial<WorkspaceState>) => void; handleSave: (id: number, answer: number | string) => void; handleSideContentHeightChange: (heightChange: number) => void; handleTestcaseEval: (testcaseId: number) => void; handleDebuggerPause: () => void; handleDebuggerResume: () => void; handleDebuggerReset: () => void; handleUpdateCurrentAssessmentId: (assessmentId: number, questionId: number) => void; handleUpdateHasUnsavedChanges: (hasUnsavedChanges: boolean) => void; handlePromptAutocomplete: (row: number, col: number, callback: any) => void; }; export type OwnProps = { assessmentId: number; questionId: number; assessmentOverview: AssessmentOverview; updateAssessmentOverview: (overview: AssessmentOverview) => void; notAttempted: boolean; closeDate: string; }; export type StateProps = { editorHeight?: number; editorValue: string | null; editorWidth: string; breakpoints: string[]; highlightedLines: HighlightedLines[]; hasUnsavedChanges: boolean; isRunning: boolean; isDebugging: boolean; enableDebugging: boolean; newCursorPosition?: Position; output: InterpreterOutput[]; replValue: string; sideContentHeight?: number; storedAssessmentId?: number; storedQuestionId?: number; }; type State = { assessment: Assessment | null; activeTab: SideContentType; editingMode: string; hasUnsavedChanges: boolean; showResetTemplateOverlay: boolean; originalMaxXp: number; }; class EditingWorkspace extends React.Component<EditingWorkspaceProps, State> { public constructor(props: EditingWorkspaceProps) { super(props); this.state = { assessment: retrieveLocalAssessment(), activeTab: SideContentType.editorQuestionOverview, editingMode: 'question', hasUnsavedChanges: false, showResetTemplateOverlay: false, originalMaxXp: 0 }; } /** * After mounting (either an older copy of the assessment * or a loading screen), try to fetch a newer assessment, * and show the briefing. */ public componentDidMount() { if (this.state.assessment) { this.resetWorkspaceValues(); this.setState({ originalMaxXp: this.getMaxXp() }); } } /** * Once there is an update (due to the assessment being fetched), check * if a workspace reset is needed. */ public componentDidUpdate() { this.checkWorkspaceReset(this.props); } public render() { if (this.state.assessment === null || this.state.assessment!.questions.length === 0) { return ( <NonIdealState className={classNames('WorkspaceParent', Classes.DARK)} description="Getting mission ready..." icon={<Spinner size={Spinner.SIZE_LARGE} />} /> ); } const questionId = this.formatedQuestionId(); const question: Question = this.state.assessment.questions[questionId]; const workspaceProps: WorkspaceProps = { controlBarProps: this.controlBarProps(questionId), editorProps: question.type === QuestionTypes.programming ? { editorSessionId: '', editorValue: this.props.editorValue || question.editorValue || (question as IProgrammingQuestion).solutionTemplate, handleDeclarationNavigate: this.props.handleDeclarationNavigate, handleEditorEval: this.props.handleEditorEval, handleEditorValueChange: this.props.handleEditorValueChange, breakpoints: this.props.breakpoints, highlightedLines: this.props.highlightedLines, newCursorPosition: this.props.newCursorPosition, handleEditorUpdateBreakpoints: this.props.handleEditorUpdateBreakpoints, handleUpdateHasUnsavedChanges: this.props.handleUpdateHasUnsavedChanges, handlePromptAutocomplete: this.props.handlePromptAutocomplete, isEditorAutorun: false } : undefined, editorHeight: this.props.editorHeight, editorWidth: this.props.editorWidth, handleEditorHeightChange: this.props.handleEditorHeightChange, handleEditorWidthChange: this.props.handleEditorWidthChange, handleSideContentHeightChange: this.props.handleSideContentHeightChange, hasUnsavedChanges: this.state.hasUnsavedChanges, mcqProps: { mcq: question as IMCQQuestion, handleMCQSubmit: (option: number) => this.props.handleSave(this.state.assessment!.questions[questionId].id, option) }, sideContentHeight: this.props.sideContentHeight, sideContentProps: this.sideContentProps(this.props, questionId), replProps: { handleBrowseHistoryDown: this.props.handleBrowseHistoryDown, handleBrowseHistoryUp: this.props.handleBrowseHistoryUp, handleReplEval: this.props.handleReplEval, handleReplValueChange: this.props.handleReplValueChange, output: this.props.output, replValue: this.props.replValue, sourceChapter: question?.library?.chapter || 4, sourceVariant: 'default', externalLibrary: question?.library?.external?.name || 'NONE', replButtons: this.replButtons() } }; return ( <div className={classNames('WorkspaceParent', Classes.DARK)}> {this.resetTemplateOverlay()} <Workspace {...workspaceProps} /> </div> ); } /* If questionId is out of bounds, set it within range. */ private formatedQuestionId = () => { let questionId = this.props.questionId; if (questionId < 0) { questionId = 0; } else if (questionId >= this.state.assessment!.questions.length) { questionId = this.state.assessment!.questions.length - 1; } return questionId; }; /** * Resets to last save. */ private resetTemplateOverlay = () => ( <Dialog className="assessment-reset" icon={IconNames.ERROR} isCloseButtonShown={true} isOpen={this.state.showResetTemplateOverlay} title="Confirmation: Reset editor?" > <div className={Classes.DIALOG_BODY}> <Markdown content="Are you sure you want to reset to your last save?" /> </div> <div className={Classes.DIALOG_FOOTER}> <ButtonGroup> {controlButton('Cancel', null, () => this.setState({ showResetTemplateOverlay: false }), { minimal: false })} {controlButton( 'Confirm', null, () => { const assessment = retrieveLocalAssessment()!; this.setState({ assessment, hasUnsavedChanges: false, showResetTemplateOverlay: false, originalMaxXp: this.getMaxXp() }); this.handleRefreshLibrary(); this.resetWorkspaceValues(); }, { minimal: false, intent: Intent.DANGER } )} </ButtonGroup> </div> </Dialog> ); /** * Checks if there is a need to reset the workspace, then executes * a dispatch (in the props) if needed. */ private checkWorkspaceReset(props: EditingWorkspaceProps) { /* Don't reset workspace if assessment not fetched yet. */ if (this.state.assessment === undefined) { return; } /* Reset assessment if it has changed.*/ const assessmentId = -1; const questionId = this.formatedQuestionId(); if ( this.props.storedAssessmentId !== assessmentId || this.props.storedQuestionId !== questionId ) { this.resetWorkspaceValues(); this.props.handleUpdateCurrentAssessmentId(assessmentId, questionId); this.props.handleUpdateHasUnsavedChanges(false); if (this.state.hasUnsavedChanges) { this.setState({ assessment: retrieveLocalAssessment(), hasUnsavedChanges: false }); } this.handleRefreshLibrary(); } } private handleRefreshLibrary = (library: Library | undefined = undefined) => { const question = this.state.assessment!.questions[this.formatedQuestionId()]; if (!library) { library = question.library.chapter === -1 ? this.state.assessment!.globalDeployment! : question.library; } if (library && library.globals.length > 0) { const globalsVal = library.globals.map((x: any) => x[0]); const symbolsVal = library.external.symbols.concat(globalsVal); library = { ...library, external: { name: library.external.name, symbols: uniq(symbolsVal) } }; } this.props.handleClearContext(library, true); }; private resetWorkspaceValues = () => { const question: Question = this.state.assessment!.questions[this.formatedQuestionId()]; let editorValue: string; let editorPrepend = ''; let editorPostpend = ''; if (question.type === QuestionTypes.programming) { if (question.editorValue) { editorValue = question.editorValue; } else { editorValue = (question as IProgrammingQuestion).solutionTemplate as string; } editorPrepend = (question as IProgrammingQuestion).prepend; editorPostpend = (question as IProgrammingQuestion).postpend; } else { editorValue = '//If you see this, this is a bug. Please report bug.'; } this.props.handleResetWorkspace({ editorPrepend, editorValue, editorPostpend }); this.props.handleEditorValueChange(editorValue); }; private handleTestcaseEval = (testcase: Testcase) => { const editorTestcases = [testcase]; this.props.handleUpdateWorkspace({ editorTestcases }); this.props.handleTestcaseEval(0); }; private handleSave = () => { const assessment = this.state.assessment!; assessment.questions[this.formatedQuestionId()].editorValue = this.props.editorValue; this.setState({ assessment, hasUnsavedChanges: false }); storeLocalAssessment(assessment); // this.handleRefreshLibrary(); this.handleSaveXp(); }; private handleSaveXp = () => { const curXp = this.getMaxXp(); const changeXp = curXp - this.state.originalMaxXp; if (changeXp !== 0) { const overview = this.props.assessmentOverview; if (changeXp !== 0) { overview.maxXp = curXp; } this.setState({ originalMaxXp: curXp }); this.props.updateAssessmentOverview(overview); storeLocalAssessmentOverview(overview); } }; private getMaxXp = () => { let xp = 0; const questions = this.state.assessment!.questions; for (const question of questions) { xp += question.maxXp; } return xp as number; }; private updateEditAssessmentState = (assessmentVal: Assessment) => { this.setState({ assessment: assessmentVal, hasUnsavedChanges: true }); }; private updateAndSaveAssessment = (assessmentVal: Assessment) => { this.setState({ assessment: assessmentVal }); this.handleRefreshLibrary(); this.handleSave(); this.resetWorkspaceValues(); }; private handleActiveTabChange = (tab: SideContentType) => { this.setState({ activeTab: tab }); }; private toggleEditingMode = () => { const toggle = this.state.editingMode === 'question' ? 'global' : 'question'; this.setState({ editingMode: toggle }); }; /** Pre-condition: IAssessment has been loaded */ private sideContentProps: (p: EditingWorkspaceProps, q: number) => SideContentProps = ( props: EditingWorkspaceProps, questionId: number ) => { const assessment = this.state.assessment!; let tabs: SideContentTab[]; if (this.state.editingMode === 'question') { const qnType = this.state.assessment!.questions[this.props.questionId].type; const questionTemplateTab = qnType === 'mcq' ? ( <MCQQuestionTemplateTab assessment={assessment} questionId={questionId} updateAssessment={this.updateEditAssessmentState} /> ) : ( <ProgrammingQuestionTemplateTab assessment={assessment} questionId={questionId} updateAssessment={this.updateEditAssessmentState} editorValue={this.props.editorValue} handleEditorValueChange={this.props.handleEditorValueChange} handleUpdateWorkspace={this.props.handleUpdateWorkspace} /> ); tabs = [ { label: `Task ${questionId + 1}`, iconName: IconNames.NINJA, body: ( <TextAreaContent assessment={assessment} path={['questions', questionId, 'content']} updateAssessment={this.updateEditAssessmentState} /> ), id: SideContentType.editorQuestionOverview, toSpawn: () => true }, { label: `Question Template`, iconName: IconNames.DOCUMENT, body: questionTemplateTab, id: SideContentType.editorQuestionTemplate, toSpawn: () => true }, { label: `Manage Local Deployment`, iconName: IconNames.HOME, body: ( <DeploymentTab assessment={assessment} label={'Question Specific'} handleRefreshLibrary={this.handleRefreshLibrary} pathToLibrary={['questions', questionId, 'library']} updateAssessment={this.updateEditAssessmentState} isOptionalDeployment={true} /> ), id: SideContentType.editorLocalDeployment, toSpawn: () => true }, { label: `Manage Local Grader Deployment`, iconName: IconNames.CONFIRM, body: ( <DeploymentTab assessment={assessment} label={'Question Specific Grader'} handleRefreshLibrary={this.handleRefreshLibrary} pathToLibrary={['questions', questionId, 'graderLibrary']} pathToCopy={['questions', questionId, 'library']} updateAssessment={this.updateEditAssessmentState} isOptionalDeployment={true} /> ), id: SideContentType.editorLocalGraderDeployment, toSpawn: () => true }, { label: `Grading`, iconName: IconNames.TICK, body: ( <GradingTab assessment={assessment} path={['questions', questionId]} updateAssessment={this.updateEditAssessmentState} /> ), id: SideContentType.editorGrading, toSpawn: () => true } ]; if (qnType === 'programming') { tabs.push({ label: `Autograder`, iconName: IconNames.AIRPLANE, body: ( <AutograderTab assessment={assessment} questionId={questionId} handleTestcaseEval={this.handleTestcaseEval} updateAssessment={this.updateEditAssessmentState} /> ), id: SideContentType.editorAutograder, toSpawn: () => true }); } const functionsAttached = assessment!.globalDeployment!.external.symbols; if (functionsAttached.includes('get_matrix')) { tabs.push({ label: `Tone Matrix`, iconName: IconNames.GRID_VIEW, body: <SideContentToneMatrix />, id: SideContentType.toneMatrix, toSpawn: () => true }); } } else { tabs = [ { label: `${assessment!.type} Briefing`, iconName: IconNames.BRIEFCASE, body: ( <TextAreaContent assessment={assessment} path={['longSummary']} updateAssessment={this.updateEditAssessmentState} /> ), id: SideContentType.editorBriefing, toSpawn: () => true }, { label: `Manage Question`, iconName: IconNames.WRENCH, body: ( <ManageQuestionTab assessment={assessment} hasUnsavedChanges={this.state.hasUnsavedChanges} questionId={questionId} updateAssessment={this.updateAndSaveAssessment} /> ), id: SideContentType.editorManageQuestion, toSpawn: () => true }, { label: `Manage Global Deployment`, iconName: IconNames.GLOBE, body: ( <DeploymentTab assessment={assessment} label={'Global'} handleRefreshLibrary={this.handleRefreshLibrary} pathToLibrary={['globalDeployment']} updateAssessment={this.updateEditAssessmentState} isOptionalDeployment={false} /> ), id: SideContentType.editorGlobalDeployment, toSpawn: () => true }, { label: `Manage Global Grader Deployment`, iconName: IconNames.CONFIRM, body: ( <DeploymentTab assessment={assessment} label={'Global Grader'} handleRefreshLibrary={this.handleRefreshLibrary} pathToLibrary={['graderDeployment']} updateAssessment={this.updateEditAssessmentState} isOptionalDeployment={true} /> ), id: SideContentType.editorGlobalGraderDeployment, toSpawn: () => true } ]; } return { handleActiveTabChange: this.handleActiveTabChange, tabs }; }; /** Pre-condition: IAssessment has been loaded */ private controlBarProps: (q: number) => ControlBarProps = (questionId: number) => { const listingPath = '/mission-control'; const assessmentWorkspacePath = listingPath + `/${this.state.assessment!.id.toString()}`; const questionProgress: [number, number] = [ questionId + 1, this.state.assessment!.questions.length ]; const onClickPrevious = () => history.push(assessmentWorkspacePath + `/${(questionId - 1).toString()}`); const onClickNext = () => history.push(assessmentWorkspacePath + `/${(questionId + 1).toString()}`); const onClickReturn = () => history.push(listingPath); const onClickResetTemplate = () => { this.setState((currentState: State) => { return { ...currentState, showResetTemplateOverlay: currentState.hasUnsavedChanges }; }); }; const nextButton = ( <ControlBarNextButton onClickNext={onClickNext} onClickReturn={onClickReturn} questionProgress={questionProgress} key="next_question" /> ); const previousButton = ( <ControlBarPreviousButton onClick={onClickPrevious} questionProgress={questionProgress} key="previous_question" /> ); const questionView = ( <ControlBarQuestionViewButton questionProgress={questionProgress} key="question_view" /> ); const resetButton = ( <ControlBarResetButton onClick={onClickResetTemplate} key="reset_template" /> ); const runButton = ( <ControlBarRunButton handleEditorEval={this.props.handleEditorEval} key="run" /> ); const saveButton = ( <ControlButtonSaveButton hasUnsavedChanges={this.state.hasUnsavedChanges} onClickSave={this.handleSave} key="save" /> ); const toggleEditModeButton = ( <ControlBarToggleEditModeButton editingMode={this.state.editingMode} toggleEditMode={this.toggleEditingMode} key="toggle_edit_mode" /> ); return { editorButtons: [runButton, saveButton, resetButton], flowButtons: [previousButton, questionView, nextButton], editingWorkspaceButtons: [toggleEditModeButton] }; }; private replButtons() { const clearButton = ( <ControlBarClearButton handleReplOutputClear={this.props.handleReplOutputClear} key="clear_repl" /> ); const evalButton = ( <ControlBarEvalButton handleReplEval={this.props.handleReplEval} isRunning={this.props.isRunning} key="eval_repl" /> ); return [evalButton, clearButton]; } } function uniq(a: string[]) { const seen = {}; return a.filter(item => (seen.hasOwnProperty(item) ? false : (seen[item] = true))); } export default EditingWorkspace;
the_stack
import React from 'react' import classnames from 'classnames' import { vec2 } from 'gl-matrix' import { PhotoWork } from 'common/CommonTypes' import { CameraMetrics, getInvertedProjectionMatrix, createProjectionMatrix } from 'common/util/CameraMetrics' import { Point, Size, Rect, Side, Corner, corners, Insets, zeroInsets } from 'common/util/GeometryTypes' import { transformRect, oppositeCorner, cornerPointOfRect, centerOfRect, intersectLineWithPolygon, rectFromCenterAndSize, isPointInPolygon, nearestPointOnPolygon, Vec2Like, rectFromCornerPointAndSize, rectFromPoints, directionOfPoints, movePoint, ceilVec2, floorVec2, roundVec2, boundsOfPoints, boundsOfRects, scaleRectToFitBorders } from 'common/util/GeometryUtil' import { bindMany, isShallowEqual } from 'common/util/LangUtil' import CropOverlay from './CropOverlay' import CropModeToolbar from './CropModeToolbar' import { createDragRectFencePolygon } from './CropModeUtil' import { AspectRatioType } from './DetailTypes' const minCropRectSize = 32 export interface Props { topBarClassName: string bodyClassName: string photoWork: PhotoWork cameraMetrics: CameraMetrics onPhotoWorkEdited(photoWork: PhotoWork, boundsRect?: Rect | null): void onDone(): void } interface State { actionInfo: { type: 'tilt', centerInTextureCoords: vec2, maxCropRectSize: Size } | { type: 'drag-rect', startCropRect: Rect, fencePolygon: vec2[] } | { type: 'drag-side', dragStartMetrics: DragStartMetrics } | { type: 'drag-corner', dragStartMetrics: DragStartMetrics } | null aspectRatioType: AspectRatioType isAspectRatioLandscape: boolean } export default class CropModeLayer extends React.Component<Props, State> { constructor(props: Props) { super(props) bindMany(this, 'setAspectRatio', 'onRectDrag', 'onSideDrag', 'onCornerDrag', 'onTiltChange') this.state = { actionInfo: null, aspectRatioType: 'free', isAspectRatioLandscape: true } } private setAspectRatio(aspectRatioType: AspectRatioType, isLandscape: boolean | null) { const { props } = this const { cameraMetrics } = props if (isLandscape === null) { // Detect landscape/portrait const { width, height } = cameraMetrics.cropRect isLandscape = (width === height) ? this.state.isAspectRatioLandscape : width > height } let nextCropRect: Rect | null = null const aspectRatio = getAspectRatio(aspectRatioType, isLandscape, cameraMetrics.textureSize) if (aspectRatio !== null) { const { cropRect: prevCropRect, textureSize } = cameraMetrics const texturePolygon = createTexturePolygon(cameraMetrics) let wantedCropRectSize: Size if (prevCropRect.width === textureSize.width || prevCropRect.height === textureSize.height) { // The last crop rect was full size -> Make the next crop rect full size again const maxSize = Math.max(textureSize.width, textureSize.height) wantedCropRectSize = aspectRatio > 1 ? { width: maxSize, height: maxSize / aspectRatio } : { width: maxSize * aspectRatio, height: maxSize } } else { // The new crop rect's area should have the same size as the previous one const width = Math.sqrt(prevCropRect.width * prevCropRect.height * aspectRatio) wantedCropRectSize = { width, height: width / aspectRatio } } nextCropRect = scaleRectToFitBorders(centerOfRect(prevCropRect), wantedCropRectSize, texturePolygon) } // Apply changes this.setState({ aspectRatioType, isAspectRatioLandscape: isLandscape }) if (nextCropRect) { this.onPhotoWorkEdited({ ...props.photoWork, cropRect: nextCropRect }) } } private onRectDrag(deltaX: number, deltaY: number, isFinished: boolean) { const { props } = this const { cameraMetrics } = props const { actionInfo } = this.state let nextState: Partial<State> | null = null let startCropRect: Rect let fencePolygon: vec2[] if (actionInfo && actionInfo.type === 'drag-rect') { startCropRect = actionInfo.startCropRect fencePolygon = actionInfo.fencePolygon } else { startCropRect = cameraMetrics.cropRect fencePolygon = createDragRectFencePolygon(startCropRect, createTexturePolygon(cameraMetrics)) nextState = { actionInfo: { type: 'drag-rect', startCropRect, fencePolygon } } } // Limit the crop rect to the texture const zoom = cameraMetrics.photoPosition.zoom let nextRectLeftTop: Vec2Like = [ startCropRect.x - deltaX / cameraMetrics.displayScaling / zoom, startCropRect.y - deltaY / cameraMetrics.displayScaling / zoom ] if (!isPointInPolygon(nextRectLeftTop, fencePolygon)) { nextRectLeftTop = nearestPointOnPolygon(nextRectLeftTop, fencePolygon) } const cropRect = rectFromCornerPointAndSize(roundVec2(nextRectLeftTop), startCropRect) // Apply changes if (isFinished) { nextState = { actionInfo: null } } if (nextState) { this.setState(nextState as any) } this.onPhotoWorkEdited({ ...props.photoWork, cropRect }) } private onSideDrag(side: Side, point: Point, isFinished: boolean) { const { props, state } = this const { cameraMetrics } = props const { actionInfo } = state const prevCropRect = cameraMetrics.cropRect let nextState: Partial<State> | null = null let dragStartMetrics: DragStartMetrics if (actionInfo && actionInfo.type === 'drag-side') { dragStartMetrics = actionInfo.dragStartMetrics } else { dragStartMetrics = getDragStartMetrics(cameraMetrics) nextState = { actionInfo: { type: 'drag-side', dragStartMetrics } } } const isHorizontal = (side === 'e' || side === 'w') const { projectedPoint, boundsRect } = getProjectedDragTarget(point, dragStartMetrics, isHorizontal ? 'x-only' : 'y-only') const nwCorner = cornerPointOfRect(prevCropRect, 'nw') const seCorner = cornerPointOfRect(prevCropRect, 'se') switch (side) { case 'w': nwCorner[0] = Math.min(seCorner[0] - minCropRectSize, projectedPoint[0]); break case 'n': nwCorner[1] = Math.min(seCorner[1] - minCropRectSize, projectedPoint[1]); break case 'e': seCorner[0] = Math.max(nwCorner[0] + minCropRectSize, projectedPoint[0]); break case 's': seCorner[1] = Math.max(nwCorner[1] + minCropRectSize, projectedPoint[1]); break } let wantedCropRect = rectFromPoints(nwCorner, seCorner) const aspectRatio = getAspectRatio(state.aspectRatioType, state.isAspectRatioLandscape, cameraMetrics.textureSize) if (aspectRatio) { const wantedCropRectCenter = centerOfRect(wantedCropRect) if (isHorizontal) { wantedCropRect = rectFromCenterAndSize(wantedCropRectCenter, { width: wantedCropRect.width, height: wantedCropRect.width / aspectRatio }) } else { wantedCropRect = rectFromCenterAndSize(wantedCropRectCenter, { width: wantedCropRect.height * aspectRatio, height: wantedCropRect.height }) } } const texturePolygon = createTexturePolygon(cameraMetrics) const cropRect = limitRectResizeToTexture(prevCropRect, wantedCropRect, texturePolygon) // Apply changes if (isFinished) { nextState = { actionInfo: null } } if (nextState) { this.setState(nextState as any) } this.onPhotoWorkEdited({ ...props.photoWork, cropRect }, isFinished ? null : boundsOfRects(boundsRect, cropRect)) } private onCornerDrag(corner: Corner, point: Point, isFinished: boolean) { const { props, state } = this const { cameraMetrics } = props const { actionInfo } = state const prevCropRect = cameraMetrics.cropRect let nextState: Partial<State> | null = null let dragStartMetrics: DragStartMetrics if (actionInfo && actionInfo.type === 'drag-corner') { dragStartMetrics = actionInfo.dragStartMetrics } else { dragStartMetrics = getDragStartMetrics(cameraMetrics) nextState = { actionInfo: { type: 'drag-corner', dragStartMetrics } } } const { projectedPoint, boundsRect } = getProjectedDragTarget(point, dragStartMetrics, 'both') const oppositePoint = cornerPointOfRect(prevCropRect, oppositeCorner[corner]) // Limit the crop rect to the texture // The oppositePoint stays fixed, find width/height that fits into the texture const texturePolygon = createTexturePolygon(cameraMetrics) const cornerDirection = [ corner === 'ne' || corner === 'se' ? 1 : -1, corner === 'sw' || corner === 'se' ? 1 : -1 ] let wantedCornerPoint: Vec2Like const aspectRatio = getAspectRatio(state.aspectRatioType, state.isAspectRatioLandscape, cameraMetrics.textureSize) if (aspectRatio) { let rawWidth = Math.abs(projectedPoint[0] - oppositePoint[0]) let rawHeight = Math.abs(projectedPoint[1] - oppositePoint[1]) if (rawWidth / rawHeight < aspectRatio) { rawWidth = rawHeight * aspectRatio } else { rawHeight = rawWidth / aspectRatio } wantedCornerPoint = [ oppositePoint[0] + cornerDirection[0] * rawWidth, oppositePoint[1] + cornerDirection[1] * rawHeight ] } else { wantedCornerPoint = isPointInPolygon(projectedPoint, texturePolygon) ? projectedPoint : nearestPointOnPolygon(projectedPoint, texturePolygon) } const nextCropRectSize = { width: wantedCornerPoint[0] - oppositePoint[0], height: wantedCornerPoint[1] - oppositePoint[1] } let xCutFactor = maxCutFactor(oppositePoint, [nextCropRectSize.width, 0], texturePolygon) || 1 let yCutFactor = maxCutFactor(oppositePoint, [0, nextCropRectSize.height], texturePolygon) || 1 if (aspectRatio) { xCutFactor = yCutFactor = Math.min(xCutFactor, yCutFactor) } if (xCutFactor < 1) { nextCropRectSize.width *= xCutFactor } if (yCutFactor < 1) { nextCropRectSize.height *= yCutFactor } nextCropRectSize.width = cornerDirection[0] * Math.max(minCropRectSize, Math.floor(cornerDirection[0] * nextCropRectSize.width)) nextCropRectSize.height = cornerDirection[1] * Math.max(minCropRectSize, Math.floor(cornerDirection[1] * nextCropRectSize.height)) const cropRect = rectFromCornerPointAndSize(oppositePoint, nextCropRectSize) // Apply changes if (isFinished) { nextState = { actionInfo: null } } if (nextState) { this.setState(nextState as any) } this.onPhotoWorkEdited({ ...props.photoWork, cropRect }, isFinished ? null : boundsOfRects(boundsRect, cropRect)) } private onTiltChange(tilt: number) { const { props } = this const { cameraMetrics } = props const { actionInfo } = this.state let nextState: Partial<State> | null = null const prevCropRect = cameraMetrics.cropRect // Apply tilt const photoWork = { ...props.photoWork } if (tilt === 0) { delete photoWork.tilt } else { photoWork.tilt = tilt } // Get center and maximum size of crop rect let centerInTextureCoords: vec2 let maxCropRectSize: Size if (actionInfo && actionInfo.type === 'tilt') { centerInTextureCoords = actionInfo.centerInTextureCoords maxCropRectSize = actionInfo.maxCropRectSize } else { const center = centerOfRect(prevCropRect) vec2.transformMat4(center, center, getInvertedProjectionMatrix(cameraMetrics)) centerInTextureCoords = center maxCropRectSize = { width: prevCropRect.width, height: prevCropRect.height } nextState = { actionInfo: { type: 'tilt', centerInTextureCoords, maxCropRectSize } } } // Adjust crop rect const texturePolygon = createTexturePolygon(cameraMetrics) const nextProjectionMatrix = createProjectionMatrix(cameraMetrics.textureSize, photoWork) const nextCropRectCenter = vec2.transformMat4(vec2.create(), centerInTextureCoords, nextProjectionMatrix) photoWork.cropRect = scaleRectToFitBorders(nextCropRectCenter, maxCropRectSize, texturePolygon) // Apply changes if (nextState) { this.setState(nextState as any) } this.onPhotoWorkEdited(photoWork) } private onPhotoWorkEdited(photoWork: PhotoWork, boundsRect?: Rect | null) { const { cropRect } = photoWork if (cropRect) { if (isShallowEqual(cropRect, this.props.cameraMetrics.neutralCropRect)) { delete photoWork.cropRect } else { photoWork.cropRect = cropRect } } this.props.onPhotoWorkEdited(photoWork, boundsRect) } render() { const { props, state } = this const { cameraMetrics } = props if (!cameraMetrics) { return null } const cropRectInDisplayCoords = transformRect(cameraMetrics.cropRect, cameraMetrics.displayMatrix) return ( <> <CropModeToolbar className={classnames(props.topBarClassName, 'CropModeLayer-toolbar')} aspectRatioType={state.aspectRatioType} isAspectRatioLandscape={state.isAspectRatioLandscape} photoWork={props.photoWork} setAspectRatio={this.setAspectRatio} onPhotoWorkEdited={props.onPhotoWorkEdited} onDone={props.onDone} /> <CropOverlay className={classnames(props.bodyClassName, 'CropModeLayer-body')} width={cameraMetrics.displaySize.width} height={cameraMetrics.displaySize.height} rect={cropRectInDisplayCoords} tilt={props.photoWork.tilt || 0} onRectDrag={this.onRectDrag} onSideDrag={this.onSideDrag} onCornerDrag={this.onCornerDrag} onTiltChange={this.onTiltChange} /> </> ) } } function getAspectRatio(aspectRatioType: AspectRatioType, isLandscape: boolean, textureSize: Size): number | null { let value: number switch (aspectRatioType) { case 'free': return null case 'original': value = Math.max(1, textureSize.width, textureSize.height) / Math.max(1, Math.min(textureSize.width, textureSize.height)); break case '1:1': value = 1; break case '16:9': value = 16 / 9; break case '4:3': value = 4 / 3; break case '3:2': value = 3 / 2; break default: throw new Error('Unsupported aspectRatioType: ' + aspectRatioType) } return isLandscape ? value : 1 / value } /** * Creates a polygon of the texture's outline (in projected coordinates). */ function createTexturePolygon(cameraMetrics: CameraMetrics): vec2[] { const { textureSize, projectionMatrix } = cameraMetrics // Create the polygon in texture coordinates const polygon = [ vec2.fromValues(0, 0), vec2.fromValues(textureSize.width, 0), vec2.fromValues(textureSize.width, textureSize.height), vec2.fromValues(0, textureSize.height), ] // Transform the polygon to projected coordinates for (let i = 0, il = polygon.length; i < il; i++) { vec2.transformMat4(polygon[i], polygon[i], projectionMatrix) } return polygon } function limitRectResizeToTexture(prevRect: Rect, wantedRect: Rect, texturePolygon: Vec2Like[]): Rect { let minFactor = 1 if (wantedRect.width < minCropRectSize) { const minFactorX = (prevRect.width - minCropRectSize) / (wantedRect.width - minCropRectSize) if (minFactorX < minFactor) { minFactor = minFactorX } } if (wantedRect.height < minCropRectSize) { const minFactorY = (prevRect.height - minCropRectSize) / (wantedRect.height - minCropRectSize) if (minFactorY < minFactor) { minFactor = minFactorY } } let nwStart: vec2 | null = null let nwDirection: vec2 | null = null let seStart: vec2 | null = null let seDirection: vec2 | null = null for (const corner of corners) { const start = cornerPointOfRect(prevRect, corner) const end = cornerPointOfRect(wantedRect, corner) const direction = directionOfPoints(start, end) const cutFactor = maxCutFactor(start, direction, texturePolygon) if (cutFactor && cutFactor < minFactor) { minFactor = cutFactor } if (corner === 'nw') { nwStart = start nwDirection = cutFactor ? direction : null } else if (corner === 'se') { seStart = start seDirection = cutFactor ? direction : null } } const nextNwPoint = ceilVec2(nwDirection ? movePoint(nwStart!, nwDirection, minFactor) : nwStart!) const nextSePoint = floorVec2(seDirection ? movePoint(seStart!, seDirection, minFactor) : seStart!) return rectFromPoints(nextNwPoint, nextSePoint) } function maxCutFactor(lineStart: Vec2Like, lineDirection: Vec2Like, polygonPoints: Vec2Like[]): number | null { const factors = intersectLineWithPolygon(lineStart, lineDirection, polygonPoints) if (factors.length) { return factors[factors.length - 1] } else { return null } } interface DragStartMetrics { displaySize: Size displayScaling: number insets: Insets startZoom: number startBoundsNwScreen: vec2 startBoundsSeScreen: vec2 startBoundsNwProjected: vec2 startBoundsSeProjected: vec2 textureBounds: Rect } function getDragStartMetrics(startCameraMetrics: CameraMetrics): DragStartMetrics { const startBoundsNwProjected = cornerPointOfRect(startCameraMetrics.boundsRect, 'nw') const startBoundsSeProjected = cornerPointOfRect(startCameraMetrics.boundsRect, 'se') const startBoundsNwScreen = vec2.transformMat4(vec2.create(), startBoundsNwProjected, startCameraMetrics.displayMatrix) const startBoundsSeScreen = vec2.transformMat4(vec2.create(), startBoundsSeProjected, startCameraMetrics.displayMatrix) const texturePolygon = createTexturePolygon(startCameraMetrics) const textureBounds = boundsOfPoints(texturePolygon) return { displaySize: startCameraMetrics.displaySize, displayScaling: startCameraMetrics.displayScaling, insets: startCameraMetrics.insets || zeroInsets, startZoom: startCameraMetrics.photoPosition.zoom, startBoundsNwScreen, startBoundsSeScreen, startBoundsNwProjected, startBoundsSeProjected, textureBounds, } } /** * Translates a screen point (in display coordinates) into a projected point (in projected coordinates). * See: doc/geometry-concept.md * * While the user drags a point/line within the original bounds, zoom and center stays the same. Once he draggs * outside the original bounds, the bounds will be adjusted (which will change center and zoom) so the user can drag to * the full borders of the image without having to drop in between. */ function getProjectedDragTarget(screenPoint: Point, dragStartMetrics: DragStartMetrics, adjust: 'x-only' | 'y-only' | 'both'): { projectedPoint: vec2, boundsRect: Rect } { const { displaySize, displayScaling, insets, startZoom, startBoundsNwScreen, startBoundsSeScreen, startBoundsNwProjected, startBoundsSeProjected, textureBounds } = dragStartMetrics const canvasPadding = 10 const startProjectedPixPerDevicePix = 1 / displayScaling / startZoom const startBoundsWidthScreen = startBoundsSeScreen[0] - startBoundsNwScreen[0] const startBoundsHeightScreen = startBoundsSeScreen[1] - startBoundsNwScreen[1] const insetsRightX = displaySize.width - insets.right const insetsBottomY = displaySize.height - insets.bottom const mainAreaWidth = insetsRightX - insets.left const mainAreaHeight = insetsBottomY - insets.top const boundsNwProjected = vec2.clone(startBoundsNwProjected) const boundsSeProjected = vec2.clone(startBoundsSeProjected) if (screenPoint.x < startBoundsNwScreen[0] && adjust !== 'y-only') { if (screenPoint.x < insets.left) { const borderX = insets.left - screenPoint.x const borderWidth = insets.left - canvasPadding const borderInsideProjected = boundsNwProjected[0] - (mainAreaWidth - startBoundsWidthScreen) * startProjectedPixPerDevicePix const borderOutsideProjected = Math.min(borderInsideProjected - borderWidth * startProjectedPixPerDevicePix, textureBounds.x) boundsNwProjected[0] = Math.max(textureBounds.x, borderInsideProjected - (borderX / borderWidth) * (borderInsideProjected - borderOutsideProjected)) } else { boundsNwProjected[0] = Math.max(textureBounds.x, startBoundsNwProjected[0] - (startBoundsNwScreen[0] - screenPoint.x) * 2 * startProjectedPixPerDevicePix) } } else if (screenPoint.x > startBoundsSeScreen[0] && adjust !== 'y-only') { const textureBoundsRight = textureBounds.x + textureBounds.width if (screenPoint.x > insetsRightX) { const borderX = insetsRightX - screenPoint.x const borderWidth = insets.right - canvasPadding const borderInsideProjected = boundsSeProjected[0] + (mainAreaWidth - startBoundsWidthScreen) * startProjectedPixPerDevicePix const borderOutsideProjected = Math.max(borderInsideProjected + borderWidth * startProjectedPixPerDevicePix, textureBoundsRight) boundsSeProjected[0] = Math.min(textureBoundsRight, borderInsideProjected + (borderX / borderWidth) * (borderInsideProjected - borderOutsideProjected)) } else { boundsSeProjected[0] = Math.min(textureBoundsRight, startBoundsSeProjected[0] + (screenPoint.x - startBoundsSeScreen[0]) * 2 * startProjectedPixPerDevicePix) } } if (screenPoint.y < startBoundsNwScreen[1] && adjust !== 'x-only') { if (screenPoint.y < insets.top) { const borderY = insets.top - screenPoint.y const borderHeight = insets.top - canvasPadding const borderInsideProjected = boundsNwProjected[1] - (mainAreaHeight - startBoundsHeightScreen) * startProjectedPixPerDevicePix const borderOutsideProjected = Math.min(borderInsideProjected - borderHeight * startProjectedPixPerDevicePix, textureBounds.y) boundsNwProjected[1] = Math.max(textureBounds.y, borderInsideProjected - (borderY / borderHeight) * (borderInsideProjected - borderOutsideProjected)) } else { boundsNwProjected[1] = Math.max(textureBounds.y, startBoundsNwProjected[1] - (startBoundsNwScreen[1] - screenPoint.y) * 2 * startProjectedPixPerDevicePix) } } else if (screenPoint.y > startBoundsSeScreen[1] && adjust !== 'x-only') { const textureBoundsRight = textureBounds.y + textureBounds.height if (screenPoint.y > insetsBottomY) { const borderY = insetsBottomY - screenPoint.y const borderHeight = insets.bottom - canvasPadding const borderInsideProjected = boundsSeProjected[1] + (mainAreaHeight - startBoundsHeightScreen) * startProjectedPixPerDevicePix const borderOutsideProjected = Math.max(borderInsideProjected + borderHeight * startProjectedPixPerDevicePix, textureBoundsRight) boundsSeProjected[1] = Math.min(textureBoundsRight, borderInsideProjected + (borderY / borderHeight) * (borderInsideProjected - borderOutsideProjected)) } else { boundsSeProjected[1] = Math.min(textureBoundsRight, startBoundsSeProjected[1] + (screenPoint.y - startBoundsSeScreen[1]) * 2 * startProjectedPixPerDevicePix) } } const zoom = Math.min( startZoom, (mainAreaWidth / displayScaling) / (boundsSeProjected[0] - boundsNwProjected[0]), (mainAreaHeight / displayScaling) / (boundsSeProjected[1] - boundsNwProjected[1])) const mainAreaCenterX = insets.left + mainAreaWidth / 2 const mainAreaCenterY = insets.top + mainAreaHeight / 2 const boundsCenterXProjected = (boundsNwProjected[0] + boundsSeProjected[0]) / 2 const boundsCenterYProjected = (boundsNwProjected[1] + boundsSeProjected[1]) / 2 const projectedX = boundsCenterXProjected + (Math.max(insets.left, Math.min(insetsRightX, screenPoint.x)) - mainAreaCenterX) / displayScaling / zoom const projectedY = boundsCenterYProjected + (Math.max(insets.top, Math.min(insetsBottomY, screenPoint.y)) - mainAreaCenterY) / displayScaling / zoom const result = { projectedPoint: vec2.fromValues(projectedX, projectedY), boundsRect: boundsOfPoints([boundsNwProjected, boundsSeProjected]) } return result }
the_stack
import {authenticate, UserProfileFactory} from '@loopback/authentication'; import {inject} from '@loopback/core'; import { MockTestOauth2SocialApp, MyUser, userRepository, } from '@loopback/mock-oauth2-provider'; import {get, Response, RestApplication, RestBindings} from '@loopback/rest'; import {SecurityBindings, securityId, UserProfile} from '@loopback/security'; import { Client, createClientForHandler, expect, supertest, } from '@loopback/testlab'; import axios from 'axios'; import {AddressInfo} from 'net'; import { Strategy as Oauth2Strategy, StrategyOptions, VerifyCallback, VerifyFunction, } from 'passport-oauth2'; import qs from 'qs'; import * as url from 'url'; import {StrategyAdapter} from '../../strategy-adapter'; import { configureApplication, simpleRestApplication, } from './fixtures/simple-rest-app'; /** * This test consists of three main components -> the supertest client, the LoopBack app (simple-rest-app.ts) * and the Mock Authorization Server (mock-oauth2-social-app.ts) * * PLEASE LOOK AT fixtures/README.md file before going thru the below * * Mock Authorization Server (mock-oauth2-social-app.ts) : * mocks the authorization flow login with a social app like facebook, google, etc * LoopBack app (simple-rest-app.ts) : * has a simple app with no controller, Oauth2Controller is added in this test */ /** * options to pass to the Passport Strategy */ const oauth2Options: StrategyOptions = { clientID: '1111', clientSecret: '1917e2b73a87fd0c9a92afab64f6c8d4', // `redirect_uri`: // 'passport-oauth2' takes care of sending the configured `callBackURL` setting as `redirect_uri` // to the authorization server. This behaviour is inherited by all other oauth2 modules like facebook, google, etc callbackURL: 'http://localhost:8080/auth/thirdparty/callback', // 'authorizationURL' is used by 'passport-oauth2' to begin the authorization grant flow authorizationURL: 'http://localhost:9000/oauth/dialog', // `tokenURL` is used by 'passport-oauth2' to exchange the access code for an access token // this exchange is taken care internally by 'passport-oauth2' // when the `callbackURL` is invoked by the authorization server tokenURL: 'http://localhost:9000/oauth/token', }; /** * verify function for the oauth2 strategy * This function mocks a lookup against a user profile datastore * * @param accessToken * @param refreshToken * @param profile * @param done */ const verify: VerifyFunction = function ( accessToken: string, refreshToken: string, userProfile: MyUser, done: VerifyCallback, ) { userProfile.token = accessToken; if (!userRepository.findById(userProfile.id)) { userRepository.createExternalUser(userProfile); } return done(null, userProfile); }; /** * convert user info to user profile * @param user */ const myUserProfileFactory: UserProfileFactory<MyUser> = function ( user: MyUser, ): UserProfile { const userProfile = {[securityId]: user.id, ...user}; return userProfile; }; /** * Login controller for third party oauth provider * * This creates an authentication endpoint for the third party oauth provider * * Two methods are expected * * 1. loginToThirdParty * i. an endpoint for api clients to login via a third party app * ii. the passport strategy identifies this call as a redirection to third party * iii. this endpoint redirects to the third party authorization url * * 2. thirdPartyCallBack * i. this is the callback for the thirdparty app * ii. on successful user login the third party calls this endpoint with an access code * iii. the passport oauth2 strategy exchanges the code for an access token * iv. the passport oauth2 strategy then calls the provided `verify()` function with the access token */ export class Oauth2Controller { constructor() {} // this configures the oauth2 strategy @authenticate('oauth2') // we have modeled this as a GET endpoint @get('/auth/thirdparty') // loginToThirdParty() is the handler for '/auth/thirdparty' // this method is injected with redirect url and status // the value for 'authentication.redirect.url' is set by the authentication action provider loginToThirdParty( @inject('authentication.redirect.url') redirectUrl: string, @inject('authentication.redirect.status') status: number, @inject(RestBindings.Http.RESPONSE) response: Response, ) { // controller handles redirect // and returns response object to indicate response is already handled response.statusCode = status || 302; response.setHeader('Location', redirectUrl); response.end(); return response; } // we configure the callback url also with the same oauth2 strategy @authenticate('oauth2') // this SHOULD be a GET call so that the third party can ask the browser to redirect @get('/auth/thirdparty/callback') // thirdPartyCallBack() is the handler for '/auth/thirdparty/callback' // the oauth2 strategy identifies this as a callback with the request.query.code sent by the third party app // the oauth2 strategy exchanges the access code for a access token and then calls the provided verify() function // the verify function creates a user profile after verifying the access token thirdPartyCallBack(@inject(SecurityBindings.USER) user: UserProfile) { // eslint-disable-next-line @typescript-eslint/naming-convention return {access_token: user.token}; } } describe('Oauth2 authorization flow', () => { let app: RestApplication; let oauth2Strategy: StrategyAdapter<MyUser>; let client: Client; let oauth2Client: Client; before(() => { const server = MockTestOauth2SocialApp.startMock(); const port = (server.address() as AddressInfo).port; oauth2Client = supertest(`http://localhost:${port}`); }); after(MockTestOauth2SocialApp.stopMock); before(givenLoopBackApp); before(givenOauth2Strategy); before(setupAuthentication); before(givenControllerInApp); before(givenClient); let oauthProviderUrl: string; let providerLoginUrl: string; let callbackToLbApp: string; let loginPageParams: string; context('Stage 1 - Authorization code grant', () => { describe('when client invokes oauth flow', () => { it('call is redirected to third party authorization url', async () => { // HTTP status code 303 means see other, // on seeing which the browser would redirect to the other location const response = await client.get('/auth/thirdparty').expect(303); oauthProviderUrl = response.get('Location'); expect(url.parse(response.get('Location')).pathname).to.equal( url.parse(oauth2Options.authorizationURL).pathname, ); }); it('call to authorization url is redirected to oauth providers login page', async () => { // HTTP status code 302 means redirect to new uri, // on seeing which the browser would redirect to the new uri const response = await supertest('').get(oauthProviderUrl).expect(302); providerLoginUrl = response.get('Location'); loginPageParams = url.parse(providerLoginUrl).query ?? ''; expect(url.parse(response.get('Location')).pathname).to.equal('/login'); }); it('login page redirects to authorization app callback endpoint', async () => { const loginPageHiddenParams = qs.parse(loginPageParams); const params = { username: 'user1', password: 'abc', // eslint-disable-next-line @typescript-eslint/naming-convention client_id: loginPageHiddenParams.client_id, // eslint-disable-next-line @typescript-eslint/naming-convention redirect_uri: loginPageHiddenParams.redirect_uri, scope: loginPageHiddenParams.scope, }; // On successful login, the authorizing app redirects to the callback url // HTTP status code 302 is returned to the browser const response = await oauth2Client .post('/login_submit') .send(qs.stringify(params)) .expect(302); callbackToLbApp = response.get('Location'); expect(url.parse(callbackToLbApp).pathname).to.equal( '/auth/thirdparty/callback', ); }); it('callback url contains access code', async () => { expect(url.parse(callbackToLbApp).query).to.containEql('code'); }); }); }); context('Stage 2: Authentication', () => { describe('Invoking call back url returns access token', () => { it('access code can be exchanged for token', async () => { expect(url.parse(callbackToLbApp).path).to.containEql( '/auth/thirdparty/callback', ); const path: string = url.parse(callbackToLbApp).path ?? ''; const response = await client.get(path).expect(200); expect(response.body).property('access_token'); }); }); }); function givenLoopBackApp() { app = simpleRestApplication(); } function givenOauth2Strategy() { const passport = new Oauth2Strategy(oauth2Options, verify); // passport-oauth2 base class leaves user profile creation to subclass implementations passport.userProfile = (accessToken, done) => { // call the profile url in the mock authorization app with the accessToken axios .get('http://localhost:9000/verify?access_token=' + accessToken, { headers: {Authorization: accessToken}, }) .then(response => { done(null, response.data); }) .catch(err => { done(err); }); }; // use strategy adapter to fit passport strategy to LoopBack app oauth2Strategy = new StrategyAdapter( passport, 'oauth2', myUserProfileFactory, ); } async function setupAuthentication() { await configureApplication(oauth2Strategy, 'oauth2'); } function givenControllerInApp() { return app.controller(Oauth2Controller); } function givenClient() { client = createClientForHandler(app.requestHandler); } });
the_stack
namespace ts.projectSystem { describe("unittests:: tsserver:: Project Errors", () => { function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: readonly string[]): void { assert.isTrue(projectFiles !== undefined, "missing project files"); checkProjectErrorsWorker(projectFiles.projectErrors, expectedErrors); } function checkProjectErrorsWorker(errors: readonly Diagnostic[], expectedErrors: readonly string[]): void { assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); if (expectedErrors.length) { for (let i = 0; i < errors.length; i++) { const actualMessage = flattenDiagnosticMessageText(errors[i].messageText, "\n"); const expectedMessage = expectedErrors[i]; assert.isTrue(actualMessage.indexOf(expectedMessage) === 0, `error message does not match, expected ${actualMessage} to start with ${expectedMessage}`); } } } function checkDiagnosticsWithLinePos(errors: server.protocol.DiagnosticWithLinePosition[], expectedErrors: string[]) { assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); if (expectedErrors.length) { zipWith(errors, expectedErrors, ({ message: actualMessage }, expectedMessage) => { assert.isTrue(startsWith(actualMessage, actualMessage), `error message does not match, expected ${actualMessage} to start with ${expectedMessage}`); }); } } it("external project - diagnostics for missing files", () => { const file1 = { path: "/a/b/app.ts", content: "" }; const file2 = { path: "/a/b/applib.ts", content: "" }; const host = createServerHost([file1, libFile]); const session = createSession(host); const projectService = session.getProjectService(); const projectFileName = "/a/b/test.csproj"; const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = { type: "request", command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName } }; { projectService.openExternalProject({ projectFileName, options: {}, rootFiles: toExternalFiles([file1.path, file2.path]) }); checkNumberOfProjects(projectService, { externalProjects: 1 }); const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; // only file1 exists - expect error checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]); } host.renameFile(file1.path, file2.path); { // only file2 exists - expect error checkNumberOfProjects(projectService, { externalProjects: 1 }); const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; checkDiagnosticsWithLinePos(diags, ["File '/a/b/app.ts' not found."]); } host.writeFile(file1.path, file1.content); { // both files exist - expect no errors checkNumberOfProjects(projectService, { externalProjects: 1 }); const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; checkDiagnosticsWithLinePos(diags, []); } }); it("configured projects - diagnostics for missing files", () => { const file1 = { path: "/a/b/app.ts", content: "" }; const file2 = { path: "/a/b/applib.ts", content: "" }; const config = { path: "/a/b/tsconfig.json", content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) }; const host = createServerHost([file1, config, libFile]); const session = createSession(host); const projectService = session.getProjectService(); openFilesForSession([file1], session); checkNumberOfProjects(projectService, { configuredProjects: 1 }); const project = configuredProjectAt(projectService, 0); const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = { type: "request", command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName: project.getProjectName() } }; let diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]); host.writeFile(file2.path, file2.content); checkNumberOfProjects(projectService, { configuredProjects: 1 }); diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[]; checkDiagnosticsWithLinePos(diags, []); }); it("configured projects - diagnostics for corrupted config 1", () => { const file1 = { path: "/a/b/app.ts", content: "" }; const file2 = { path: "/a/b/lib.ts", content: "" }; const correctConfig = { path: "/a/b/tsconfig.json", content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) }; const corruptedConfig = { path: correctConfig.path, content: correctConfig.content.substr(1) }; const host = createServerHost([file1, file2, corruptedConfig]); const projectService = createProjectService(host); projectService.openClientFile(file1.path); { projectService.checkNumberOfProjects({ configuredProjects: 1 }); const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; assert.isTrue(configuredProject !== undefined, "should find configured project"); checkProjectErrors(configuredProject, []); const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); checkProjectErrorsWorker(projectErrors, [ "'{' expected." ]); assert.isNotNull(projectErrors[0].file); assert.equal(projectErrors[0].file!.fileName, corruptedConfig.path); } // fix config and trigger watcher host.writeFile(correctConfig.path, correctConfig.content); { projectService.checkNumberOfProjects({ configuredProjects: 1 }); const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; assert.isTrue(configuredProject !== undefined, "should find configured project"); checkProjectErrors(configuredProject, []); const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); checkProjectErrorsWorker(projectErrors, []); } }); it("configured projects - diagnostics for corrupted config 2", () => { const file1 = { path: "/a/b/app.ts", content: "" }; const file2 = { path: "/a/b/lib.ts", content: "" }; const correctConfig = { path: "/a/b/tsconfig.json", content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) }) }; const corruptedConfig = { path: correctConfig.path, content: correctConfig.content.substr(1) }; const host = createServerHost([file1, file2, correctConfig]); const projectService = createProjectService(host); projectService.openClientFile(file1.path); { projectService.checkNumberOfProjects({ configuredProjects: 1 }); const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; assert.isTrue(configuredProject !== undefined, "should find configured project"); checkProjectErrors(configuredProject, []); const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); checkProjectErrorsWorker(projectErrors, []); } // break config and trigger watcher host.writeFile(corruptedConfig.path, corruptedConfig.content); { projectService.checkNumberOfProjects({ configuredProjects: 1 }); const configuredProject = find(projectService.synchronizeProjectList([]), f => f.info!.projectName === corruptedConfig.path)!; assert.isTrue(configuredProject !== undefined, "should find configured project"); checkProjectErrors(configuredProject, []); const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors(); checkProjectErrorsWorker(projectErrors, [ "'{' expected." ]); assert.isNotNull(projectErrors[0].file); assert.equal(projectErrors[0].file!.fileName, corruptedConfig.path); } }); }); describe("unittests:: tsserver:: Project Errors are reported as appropriate", () => { it("document is not contained in project", () => { const file1 = { path: "/a/b/app.ts", content: "" }; const corruptedConfig = { path: "/a/b/tsconfig.json", content: "{" }; const host = createServerHost([file1, corruptedConfig]); const projectService = createProjectService(host); projectService.openClientFile(file1.path); projectService.checkNumberOfProjects({ configuredProjects: 1 }); const project = projectService.findProject(corruptedConfig.path)!; checkProjectRootFiles(project, [file1.path]); }); describe("when opening new file that doesnt exist on disk yet", () => { function verifyNonExistentFile(useProjectRoot: boolean) { const folderPath = "/user/someuser/projects/someFolder"; const fileInRoot: File = { path: `/src/somefile.d.ts`, content: "class c { }" }; const fileInProjectRoot: File = { path: `${folderPath}/src/somefile.d.ts`, content: "class c { }" }; const host = createServerHost([libFile, fileInRoot, fileInProjectRoot]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(), useInferredProjectPerProjectRoot: true }); const untitledFile = "untitled:Untitled-1"; const refPathNotFound1 = "../../../../../../typings/@epic/Core.d.ts"; const refPathNotFound2 = "./src/somefile.d.ts"; const fileContent = `/// <reference path="${refPathNotFound1}" /> /// <reference path="${refPathNotFound2}" />`; session.executeCommandSeq<protocol.OpenRequest>({ command: server.CommandNames.Open, arguments: { file: untitledFile, fileContent, scriptKindName: "TS", projectRootPath: useProjectRoot ? folderPath : undefined } }); appendAllScriptInfos(session.getProjectService(), session.logger.logs); // Since this is not js project so no typings are queued host.checkTimeoutQueueLength(0); verifyGetErrRequest({ session, host, files: [untitledFile] }); baselineTsserverLogs("projectErrors", `when opening new file that doesnt exist on disk yet ${useProjectRoot ? "with projectRoot" : "without projectRoot"}`, session); } it("has projectRoot", () => { verifyNonExistentFile(/*useProjectRoot*/ true); }); it("does not have projectRoot", () => { verifyNonExistentFile(/*useProjectRoot*/ false); }); }); it("folder rename updates project structure and reports no errors", () => { const projectDir = "/a/b/projects/myproject"; const app: File = { path: `${projectDir}/bar/app.ts`, content: "class Bar implements foo.Foo { getFoo() { return ''; } get2() { return 1; } }" }; const foo: File = { path: `${projectDir}/foo/foo.ts`, content: "declare namespace foo { interface Foo { get2(): number; getFoo(): string; } }" }; const configFile: File = { path: `${projectDir}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "none", targer: "es5" }, exclude: ["node_modules"] }) }; const host = createServerHost([app, foo, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); session.executeCommandSeq<protocol.OpenRequest>({ command: server.CommandNames.Open, arguments: { file: app.path, } }); verifyGetErrRequest({ session, host, files: [app] }); host.renameFolder(`${projectDir}/foo`, `${projectDir}/foo2`); host.runQueuedTimeoutCallbacks(); host.runQueuedTimeoutCallbacks(); verifyGetErrRequest({ session, host, files: [app] }); baselineTsserverLogs("projectErrors", `folder rename updates project structure and reports no errors`, session); }); it("Getting errors before opening file", () => { const file: File = { path: "/a/b/project/file.ts", content: "let x: number = false;" }; const host = createServerHost([file, libFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); session.executeCommandSeq<protocol.GeterrRequest>({ command: server.CommandNames.Geterr, arguments: { delay: 0, files: [file.path] } }); host.checkTimeoutQueueLengthAndRun(1); baselineTsserverLogs("projectErrors", "getting errors before opening file", session); }); it("Reports errors correctly when file referenced by inferred project root, is opened right after closing the root file", () => { const app: File = { path: `${tscWatch.projectRoot}/src/client/app.js`, content: "" }; const serverUtilities: File = { path: `${tscWatch.projectRoot}/src/server/utilities.js`, content: `function getHostName() { return "hello"; } export { getHostName };` }; const backendTest: File = { path: `${tscWatch.projectRoot}/test/backend/index.js`, content: `import { getHostName } from '../../src/server/utilities';export default getHostName;` }; const files = [libFile, app, serverUtilities, backendTest]; const host = createServerHost(files); const session = createSession(host, { useInferredProjectPerProjectRoot: true, canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([{ file: app, projectRootPath: tscWatch.projectRoot }], session); openFilesForSession([{ file: backendTest, projectRootPath: tscWatch.projectRoot }], session); verifyGetErrRequest({ session, host, files: [backendTest.path, app.path] }); closeFilesForSession([backendTest], session); openFilesForSession([{ file: serverUtilities.path, projectRootPath: tscWatch.projectRoot }], session); verifyGetErrRequest({ session, host, files: [serverUtilities.path, app.path] }); baselineTsserverLogs("projectErrors", `reports errors correctly when file referenced by inferred project root, is opened right after closing the root file`, session); }); it("Correct errors when resolution resolves to file that has same ambient module and is also module", () => { const projectRootPath = "/users/username/projects/myproject"; const aFile: File = { path: `${projectRootPath}/src/a.ts`, content: `import * as myModule from "@custom/plugin"; function foo() { // hello }` }; const config: File = { path: `${projectRootPath}/tsconfig.json`, content: JSON.stringify({ include: ["src"] }) }; const plugin: File = { path: `${projectRootPath}/node_modules/@custom/plugin/index.d.ts`, content: `import './proposed'; declare module '@custom/plugin' { export const version: string; }` }; const pluginProposed: File = { path: `${projectRootPath}/node_modules/@custom/plugin/proposed.d.ts`, content: `declare module '@custom/plugin' { export const bar = 10; }` }; const files = [libFile, aFile, config, plugin, pluginProposed]; const host = createServerHost(files); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([aFile], session); checkErrors(); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: aFile.path, line: 3, offset: 8, endLine: 3, endOffset: 8, insertString: "o" } }); checkErrors(); baselineTsserverLogs("projectErrors", `correct errors when resolution resolves to file that has same ambient module and is also module`, session); function checkErrors() { host.checkTimeoutQueueLength(0); verifyGetErrRequest({ session, host, files: [aFile] }); } }); describe("when semantic error returns includes global error", () => { const file: File = { path: `${tscWatch.projectRoot}/ui.ts`, content: `const x = async (_action: string) => { };` }; const config: File = { path: `${tscWatch.projectRoot}/tsconfig.json`, content: "{}" }; verifyGetErrScenario({ scenario: "projectErrors", subScenario: "when semantic error returns includes global error", allFiles: () => [libFile, file, config], openFiles: () => [file], getErrRequest: () => [file], getErrForProjectRequest: () => [{ project: file, files: [file] }], syncDiagnostics: () => [{ file, project: config }], }); }); }); describe("unittests:: tsserver:: Project Errors for Configure file diagnostics events", () => { it("are generated when the config file has errors", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": { "foo": "bar", "allowJS": true } }` }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file], session); baselineTsserverLogs("projectErrors", "configFileDiagnostic events are generated when the config file has errors", session); }); it("are generated when the config file doesn't have errors", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": {} }` }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file], session); baselineTsserverLogs("projectErrors", "configFileDiagnostic events are generated when the config file doesnt have errors", session); }); it("are generated when the config file changes", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const configFile = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": {} }` }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file], session); configFile.content = `{ "compilerOptions": { "haha": 123 } }`; host.writeFile(configFile.path, configFile.content); host.runQueuedTimeoutCallbacks(); configFile.content = `{ "compilerOptions": {} }`; host.writeFile(configFile.path, configFile.content); host.runQueuedTimeoutCallbacks(); baselineTsserverLogs("projectErrors", "configFileDiagnostic events are generated when the config file changes", session); }); it("are not generated when the config file does not include file opened and config file has errors", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const file2: File = { path: "/a/b/test.ts", content: "let x = 10" }; const file3: File = { path: "/a/b/test2.ts", content: "let xy = 10" }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": { "foo": "bar", "allowJS": true }, "files": ["app.ts"] }` }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file2], session); openFilesForSession([file], session); // We generate only if project is created when opening file from the project openFilesForSession([file3], session); baselineTsserverLogs("projectErrors", "configFileDiagnostic events are not generated when the config file does not include file opened and config file has errors", session); }); it("are not generated when the config file has errors but suppressDiagnosticEvents is true", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": { "foo": "bar", "allowJS": true } }` }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, suppressDiagnosticEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file], session); baselineTsserverLogs("projectErrors", "configFileDiagnostic events are not generated when the config file has errors but suppressDiagnosticEvents is true", session); }); it("are not generated when the config file does not include file opened and doesnt contain any errors", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const file2: File = { path: "/a/b/test.ts", content: "let x = 10" }; const file3: File = { path: "/a/b/test2.ts", content: "let xy = 10" }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "files": ["app.ts"] }` }; const host = createServerHost([file, file2, file3, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file2], session); openFilesForSession([file], session); // We generate only if project is created when opening file from the project openFilesForSession([file3], session); baselineTsserverLogs("projectErrors", "configFileDiagnostic events are not generated when the config file does not include file opened and doesnt contain any errors", session); }); it("contains the project reference errors", () => { const file: File = { path: "/a/b/app.ts", content: "let x = 10" }; const noSuchTsconfig = "no-such-tsconfig.json"; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "files": ["app.ts"], "references": [{"path":"./${noSuchTsconfig}"}] }` }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([file], session); baselineTsserverLogs("projectErrors", "configFileDiagnostic events contains the project reference errors", session); }); }); describe("unittests:: tsserver:: Project Errors dont include overwrite emit error", () => { it("for inferred project", () => { const f1 = { path: "/a/b/f1.js", content: "function test1() { }" }; const host = createServerHost([f1, libFile]); const session = createSession(host); openFilesForSession([f1], session); const projectService = session.getProjectService(); checkNumberOfProjects(projectService, { inferredProjects: 1 }); const projectName = projectService.inferredProjects[0].getProjectName(); const diags = session.executeCommand({ type: "request", command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName: projectName } } as server.protocol.CompilerOptionsDiagnosticsRequest).response as readonly protocol.DiagnosticWithLinePosition[]; assert.isTrue(diags.length === 0); session.executeCommand({ type: "request", command: server.CommandNames.CompilerOptionsForInferredProjects, seq: 3, arguments: { options: { module: ModuleKind.CommonJS } } } as server.protocol.SetCompilerOptionsForInferredProjectsRequest); const diagsAfterUpdate = session.executeCommand({ type: "request", command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 4, arguments: { projectFileName: projectName } } as server.protocol.CompilerOptionsDiagnosticsRequest).response as readonly protocol.DiagnosticWithLinePosition[]; assert.isTrue(diagsAfterUpdate.length === 0); }); it("for external project", () => { const f1 = { path: "/a/b/f1.js", content: "function test1() { }" }; const host = createServerHost([f1, libFile]); const session = createSession(host); const projectService = session.getProjectService(); const projectFileName = "/a/b/project.csproj"; const externalFiles = toExternalFiles([f1.path]); projectService.openExternalProject({ projectFileName, rootFiles: externalFiles, options: {} } as protocol.ExternalProject); checkNumberOfProjects(projectService, { externalProjects: 1 }); const diags = session.executeCommand({ type: "request", command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName } } as server.protocol.CompilerOptionsDiagnosticsRequest).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diags.length === 0); session.executeCommand({ type: "request", command: server.CommandNames.OpenExternalProject, seq: 3, arguments: { projectFileName, rootFiles: externalFiles, options: { module: ModuleKind.CommonJS } } } as server.protocol.OpenExternalProjectRequest); const diagsAfterUpdate = session.executeCommand({ type: "request", command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 4, arguments: { projectFileName } } as server.protocol.CompilerOptionsDiagnosticsRequest).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diagsAfterUpdate.length === 0); }); }); describe("unittests:: tsserver:: Project Errors reports Options Diagnostic locations correctly with changes in configFile contents", () => { it("when options change", () => { const file = { path: "/a/b/app.ts", content: "let x = 10" }; const configFileContentBeforeComment = `{`; const configFileContentComment = ` // comment`; const configFileContentAfterComment = ` "compilerOptions": { "inlineSourceMap": true, "mapRoot": "./" } }`; const configFileContentWithComment = configFileContentBeforeComment + configFileContentComment + configFileContentAfterComment; const configFileContentWithoutCommentLine = configFileContentBeforeComment + configFileContentAfterComment; const configFile = { path: "/a/b/tsconfig.json", content: configFileContentWithComment }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host); openFilesForSession([file], session); const projectService = session.getProjectService(); checkNumberOfProjects(projectService, { configuredProjects: 1 }); const projectName = configuredProjectAt(projectService, 0).getProjectName(); const diags = session.executeCommand({ type: "request", command: server.CommandNames.SemanticDiagnosticsSync, seq: 2, arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true } } as server.protocol.SemanticDiagnosticsSyncRequest).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diags.length === 3); configFile.content = configFileContentWithoutCommentLine; host.writeFile(configFile.path, configFile.content); const diagsAfterEdit = session.executeCommand({ type: "request", command: server.CommandNames.SemanticDiagnosticsSync, seq: 2, arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true } } as server.protocol.SemanticDiagnosticsSyncRequest).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diagsAfterEdit.length === 3); verifyDiagnostic(diags[0], diagsAfterEdit[0]); verifyDiagnostic(diags[1], diagsAfterEdit[1]); verifyDiagnostic(diags[2], diagsAfterEdit[2]); function verifyDiagnostic(beforeEditDiag: server.protocol.DiagnosticWithLinePosition, afterEditDiag: server.protocol.DiagnosticWithLinePosition) { assert.equal(beforeEditDiag.message, afterEditDiag.message); assert.equal(beforeEditDiag.code, afterEditDiag.code); assert.equal(beforeEditDiag.category, afterEditDiag.category); assert.equal(beforeEditDiag.startLocation.line, afterEditDiag.startLocation.line + 1); assert.equal(beforeEditDiag.startLocation.offset, afterEditDiag.startLocation.offset); assert.equal(beforeEditDiag.endLocation.line, afterEditDiag.endLocation.line + 1); assert.equal(beforeEditDiag.endLocation.offset, afterEditDiag.endLocation.offset); } }); }); describe("unittests:: tsserver:: Project Errors with config file change", () => { it("Updates diagnostics when '--noUnusedLabels' changes", () => { const aTs: File = { path: "/a.ts", content: "label: while (1) {}" }; const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`; const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) }; const host = createServerHost([aTs, tsconfig]); const session = createSession(host); openFilesForSession([aTs], session); host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false)); host.runQueuedTimeoutCallbacks(); const response = executeSessionRequest<protocol.SemanticDiagnosticsSyncRequest, protocol.SemanticDiagnosticsSyncResponse>(session, protocol.CommandTypes.SemanticDiagnosticsSync, { file: aTs.path }) as protocol.Diagnostic[] | undefined; assert.deepEqual<protocol.Diagnostic[] | undefined>(response, [ { start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 + "label".length }, text: "Unused label.", category: "error", code: Diagnostics.Unused_label.code, relatedInformation: undefined, reportsUnnecessary: true, reportsDeprecated: undefined, source: undefined, }, ]); }); }); describe("unittests:: tsserver:: Project Errors with resolveJsonModule", () => { function createSessionForTest({ include }: { include: readonly string[]; }) { const test: File = { path: `${tscWatch.projectRoot}/src/test.ts`, content: `import * as blabla from "./blabla.json"; declare var console: any; console.log(blabla);` }; const blabla: File = { path: `${tscWatch.projectRoot}/src/blabla.json`, content: "{}" }; const tsconfig: File = { path: `${tscWatch.projectRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { resolveJsonModule: true, composite: true }, include }) }; const host = createServerHost([test, blabla, libFile, tsconfig]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([test], session); return { host, session, test, blabla, tsconfig }; } it("should not report incorrect error when json is root file found by tsconfig", () => { const { host, session, test } = createSessionForTest({ include: ["./src/*.ts", "./src/*.json"] }); verifyGetErrRequest({ session, host, files: [test] }); baselineTsserverLogs("projectErrors", `should not report incorrect error when json is root file found by tsconfig`, session); }); it("should report error when json is not root file found by tsconfig", () => { const { host, session, test } = createSessionForTest({ include: ["./src/*.ts"] }); verifyGetErrRequest({ session, host, files: [test] }); baselineTsserverLogs("projectErrors", `should report error when json is not root file found by tsconfig`, session); }); }); describe("unittests:: tsserver:: Project Errors with npm install when", () => { function verifyNpmInstall(timeoutDuringPartialInstallation: boolean) { const main: File = { path: `${tscWatch.projectRoot}/src/main.ts`, content: "import * as _a from '@angular/core';" }; const config: File = { path: `${tscWatch.projectRoot}/tsconfig.json`, content: "{}" }; // Move things from staging to node_modules without triggering watch const moduleFile: File = { path: `${tscWatch.projectRoot}/node_modules/@angular/core/index.d.ts`, content: `export const y = 10;` }; const projectFiles = [main, libFile, config]; const host = createServerHost(projectFiles); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs() }); openFilesForSession([{ file: main, projectRootPath: tscWatch.projectRoot }], session); verifyGetErrRequest({ session, host, files: [main] }); let npmInstallComplete = false; // Simulate npm install let filesAndFoldersToAdd: (File | Folder)[] = [ { path: `${tscWatch.projectRoot}/node_modules` }, // This should queue update { path: `${tscWatch.projectRoot}/node_modules/.staging` }, { path: `${tscWatch.projectRoot}/node_modules/.staging/@babel` }, { path: `${tscWatch.projectRoot}/node_modules/.staging/@babel/helper-plugin-utils-a06c629f` }, { path: `${tscWatch.projectRoot}/node_modules/.staging/core-js-db53158d` }, ]; verifyWhileNpmInstall(3); filesAndFoldersToAdd = [ { path: `${tscWatch.projectRoot}/node_modules/.staging/@angular/platform-browser-dynamic-5efaaa1a` }, { path: `${tscWatch.projectRoot}/node_modules/.staging/@angular/cli-c1e44b05/models/analytics.d.ts`, content: `export const x = 10;` }, { path: `${tscWatch.projectRoot}/node_modules/.staging/@angular/core-0963aebf/index.d.ts`, content: `export const y = 10;` }, ]; // Since we added/removed in .staging no timeout verifyWhileNpmInstall(0); filesAndFoldersToAdd = []; host.ensureFileOrFolder(moduleFile, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true, /*ignoreParentWatch*/ true); // Since we added/removed in .staging no timeout verifyWhileNpmInstall(0); // Remove staging folder to remove errors host.deleteFolder(`${tscWatch.projectRoot}/node_modules/.staging`, /*recursive*/ true); npmInstallComplete = true; projectFiles.push(moduleFile); // Additional watch for watching script infos from node_modules verifyWhileNpmInstall(3); baselineTsserverLogs("projectErrors", `npm install when timeout occurs ${timeoutDuringPartialInstallation ? "inbetween" : "after"} installation`, session); function verifyWhileNpmInstall(timeouts: number) { filesAndFoldersToAdd.forEach(f => host.ensureFileOrFolder(f)); if (npmInstallComplete || timeoutDuringPartialInstallation) { host.checkTimeoutQueueLengthAndRun(timeouts); // Invalidation of failed lookups if (timeouts) { host.checkTimeoutQueueLengthAndRun(timeouts - 1); // Actual update } } else { host.checkTimeoutQueueLength(timeouts ? 3 : 2); } verifyGetErrRequest({ session, host, files: [main], existingTimeouts: !npmInstallComplete && !timeoutDuringPartialInstallation ? timeouts ? 3 : 2 : undefined }); } } it("timeouts occur inbetween installation", () => { verifyNpmInstall(/*timeoutDuringPartialInstallation*/ true); }); it("timeout occurs after installation", () => { verifyNpmInstall(/*timeoutDuringPartialInstallation*/ false); }); }); }
the_stack
import { ValueCell } from '../../../mol-util'; import { Mat4, Vec3, Vec4 } from '../../../mol-math/linear-algebra'; import { transformPositionArray, GroupMapping, createGroupMapping } from '../../util'; import { GeometryUtils } from '../geometry'; import { createColors } from '../color-data'; import { createMarkers } from '../marker-data'; import { createSizes } from '../size-data'; import { TransformData } from '../transform-data'; import { LocationIterator, PositionLocation } from '../../util/location-iterator'; import { ParamDefinition as PD } from '../../../mol-util/param-definition'; import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } from '../../../mol-gl/renderable/util'; import { Sphere3D } from '../../../mol-math/geometry'; import { Theme } from '../../../mol-theme/theme'; import { PointsValues } from '../../../mol-gl/renderable/points'; import { RenderableState } from '../../../mol-gl/renderable'; import { Color } from '../../../mol-util/color'; import { BaseGeometry } from '../base'; import { createEmptyOverpaint } from '../overpaint-data'; import { createEmptyTransparency } from '../transparency-data'; import { hashFnv32a } from '../../../mol-data/util'; import { createEmptyClipping } from '../clipping-data'; /** Point cloud */ export interface Points { readonly kind: 'points', /** Number of vertices in the point cloud */ pointCount: number, /** Center buffer as array of xyz values wrapped in a value cell */ readonly centerBuffer: ValueCell<Float32Array>, /** Group buffer as array of group ids for each vertex wrapped in a value cell */ readonly groupBuffer: ValueCell<Float32Array>, /** Bounding sphere of the points */ readonly boundingSphere: Sphere3D /** Maps group ids to point indices */ readonly groupMapping: GroupMapping setBoundingSphere(boundingSphere: Sphere3D): void } export namespace Points { export function create(centers: Float32Array, groups: Float32Array, pointCount: number, points?: Points): Points { return points ? update(centers, groups, pointCount, points) : fromArrays(centers, groups, pointCount); } export function createEmpty(points?: Points): Points { const cb = points ? points.centerBuffer.ref.value : new Float32Array(0); const gb = points ? points.groupBuffer.ref.value : new Float32Array(0); return create(cb, gb, 0, points); } function hashCode(points: Points) { return hashFnv32a([ points.pointCount, points.centerBuffer.ref.version, points.groupBuffer.ref.version, ]); } function fromArrays(centers: Float32Array, groups: Float32Array, pointCount: number): Points { const boundingSphere = Sphere3D(); let groupMapping: GroupMapping; let currentHash = -1; let currentGroup = -1; const points = { kind: 'points' as const, pointCount, centerBuffer: ValueCell.create(centers), groupBuffer: ValueCell.create(groups), get boundingSphere() { const newHash = hashCode(points); if (newHash !== currentHash) { const b = calculateInvariantBoundingSphere(points.centerBuffer.ref.value, points.pointCount, 1); Sphere3D.copy(boundingSphere, b); currentHash = newHash; } return boundingSphere; }, get groupMapping() { if (points.groupBuffer.ref.version !== currentGroup) { groupMapping = createGroupMapping(points.groupBuffer.ref.value, points.pointCount); currentGroup = points.groupBuffer.ref.version; } return groupMapping; }, setBoundingSphere(sphere: Sphere3D) { Sphere3D.copy(boundingSphere, sphere); currentHash = hashCode(points); } }; return points; } function update(centers: Float32Array, groups: Float32Array, pointCount: number, points: Points) { points.pointCount = pointCount; ValueCell.update(points.centerBuffer, centers); ValueCell.update(points.groupBuffer, groups); return points; } export function transform(points: Points, t: Mat4) { const c = points.centerBuffer.ref.value; transformPositionArray(t, c, 0, points.pointCount); ValueCell.update(points.centerBuffer, c); } // export const StyleTypes = { 'square': 'Square', 'circle': 'Circle', 'fuzzy': 'Fuzzy', }; export type StyleTypes = keyof typeof StyleTypes; export const StyleTypeNames = Object.keys(StyleTypes) as StyleTypes[]; export const Params = { ...BaseGeometry.Params, sizeFactor: PD.Numeric(3, { min: 0, max: 10, step: 0.1 }), pointSizeAttenuation: PD.Boolean(false), pointStyle: PD.Select('square', PD.objectToOptions(StyleTypes)), }; export type Params = typeof Params export const Utils: GeometryUtils<Points, Params> = { Params, createEmpty, createValues, createValuesSimple, updateValues, updateBoundingSphere, createRenderableState, updateRenderableState, createPositionIterator }; function createPositionIterator(points: Points, transform: TransformData): LocationIterator { const groupCount = points.pointCount; const instanceCount = transform.instanceCount.ref.value; const location = PositionLocation(); const p = location.position; const v = points.centerBuffer.ref.value; const m = transform.aTransform.ref.value; const getLocation = (groupIndex: number, instanceIndex: number) => { if (instanceIndex < 0) { Vec3.fromArray(p, v, groupIndex * 3); } else { Vec3.transformMat4Offset(p, v, m, 0, groupIndex * 3, instanceIndex * 16); } return location; }; return LocationIterator(groupCount, instanceCount, 1, getLocation); } function createValues(points: Points, transform: TransformData, locationIt: LocationIterator, theme: Theme, props: PD.Values<Params>): PointsValues { const { instanceCount, groupCount } = locationIt; const positionIt = createPositionIterator(points, transform); const color = createColors(locationIt, positionIt, theme.color); const size = createSizes(locationIt, theme.size); const marker = createMarkers(instanceCount * groupCount); const overpaint = createEmptyOverpaint(); const transparency = createEmptyTransparency(); const clipping = createEmptyClipping(); const counts = { drawCount: points.pointCount, vertexCount: points.pointCount, groupCount, instanceCount }; const invariantBoundingSphere = Sphere3D.clone(points.boundingSphere); const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount); return { aPosition: points.centerBuffer, aGroup: points.groupBuffer, boundingSphere: ValueCell.create(boundingSphere), invariantBoundingSphere: ValueCell.create(invariantBoundingSphere), uInvariantBoundingSphere: ValueCell.create(Vec4.ofSphere(invariantBoundingSphere)), ...color, ...size, ...marker, ...overpaint, ...transparency, ...clipping, ...transform, ...BaseGeometry.createValues(props, counts), uSizeFactor: ValueCell.create(props.sizeFactor), dPointSizeAttenuation: ValueCell.create(props.pointSizeAttenuation), dPointStyle: ValueCell.create(props.pointStyle), }; } function createValuesSimple(points: Points, props: Partial<PD.Values<Params>>, colorValue: Color, sizeValue: number, transform?: TransformData) { const s = BaseGeometry.createSimple(colorValue, sizeValue, transform); const p = { ...PD.getDefaultValues(Params), ...props }; return createValues(points, s.transform, s.locationIterator, s.theme, p); } function updateValues(values: PointsValues, props: PD.Values<Params>) { BaseGeometry.updateValues(values, props); ValueCell.updateIfChanged(values.uSizeFactor, props.sizeFactor); ValueCell.updateIfChanged(values.dPointSizeAttenuation, props.pointSizeAttenuation); ValueCell.updateIfChanged(values.dPointStyle, props.pointStyle); } function updateBoundingSphere(values: PointsValues, points: Points) { const invariantBoundingSphere = Sphere3D.clone(points.boundingSphere); const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value); if (!Sphere3D.equals(boundingSphere, values.boundingSphere.ref.value)) { ValueCell.update(values.boundingSphere, boundingSphere); } if (!Sphere3D.equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) { ValueCell.update(values.invariantBoundingSphere, invariantBoundingSphere); ValueCell.update(values.uInvariantBoundingSphere, Vec4.fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere)); } } function createRenderableState(props: PD.Values<Params>): RenderableState { const state = BaseGeometry.createRenderableState(props); updateRenderableState(state, props); return state; } function updateRenderableState(state: RenderableState, props: PD.Values<Params>) { BaseGeometry.updateRenderableState(state, props); state.opaque = state.opaque && props.pointStyle !== 'fuzzy'; state.writeDepth = state.opaque; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/deploymentOperationsMappers"; import * as Parameters from "../models/parameters"; import { ResourceManagementClientContext } from "../resourceManagementClientContext"; /** Class representing a DeploymentOperations. */ export class DeploymentOperations { private readonly client: ResourceManagementClientContext; /** * Create a DeploymentOperations. * @param {ResourceManagementClientContext} client Reference to the service client. */ constructor(client: ResourceManagementClientContext) { this.client = client; } /** * Gets a deployments operation. * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsGetAtScopeResponse> */ getAtScope(scope: string, deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsGetAtScopeResponse>; /** * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param callback The callback */ getAtScope(scope: string, deploymentName: string, operationId: string, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; /** * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The optional parameters * @param callback The callback */ getAtScope(scope: string, deploymentName: string, operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; getAtScope(scope: string, deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperation>, callback?: msRest.ServiceCallback<Models.DeploymentOperation>): Promise<Models.DeploymentOperationsGetAtScopeResponse> { return this.client.sendOperationRequest( { scope, deploymentName, operationId, options }, getAtScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsGetAtScopeResponse>; } /** * Gets all deployments operations for a deployment. * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtScopeResponse> */ listAtScope(scope: string, deploymentName: string, options?: Models.DeploymentOperationsListAtScopeOptionalParams): Promise<Models.DeploymentOperationsListAtScopeResponse>; /** * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param callback The callback */ listAtScope(scope: string, deploymentName: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param scope The resource scope. * @param deploymentName The name of the deployment. * @param options The optional parameters * @param callback The callback */ listAtScope(scope: string, deploymentName: string, options: Models.DeploymentOperationsListAtScopeOptionalParams, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtScope(scope: string, deploymentName: string, options?: Models.DeploymentOperationsListAtScopeOptionalParams | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtScopeResponse> { return this.client.sendOperationRequest( { scope, deploymentName, options }, listAtScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtScopeResponse>; } /** * Gets a deployments operation. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsGetAtTenantScopeResponse> */ getAtTenantScope(deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsGetAtTenantScopeResponse>; /** * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param callback The callback */ getAtTenantScope(deploymentName: string, operationId: string, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; /** * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The optional parameters * @param callback The callback */ getAtTenantScope(deploymentName: string, operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; getAtTenantScope(deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperation>, callback?: msRest.ServiceCallback<Models.DeploymentOperation>): Promise<Models.DeploymentOperationsGetAtTenantScopeResponse> { return this.client.sendOperationRequest( { deploymentName, operationId, options }, getAtTenantScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsGetAtTenantScopeResponse>; } /** * Gets all deployments operations for a deployment. * @param deploymentName The name of the deployment. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtTenantScopeResponse> */ listAtTenantScope(deploymentName: string, options?: Models.DeploymentOperationsListAtTenantScopeOptionalParams): Promise<Models.DeploymentOperationsListAtTenantScopeResponse>; /** * @param deploymentName The name of the deployment. * @param callback The callback */ listAtTenantScope(deploymentName: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param deploymentName The name of the deployment. * @param options The optional parameters * @param callback The callback */ listAtTenantScope(deploymentName: string, options: Models.DeploymentOperationsListAtTenantScopeOptionalParams, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtTenantScope(deploymentName: string, options?: Models.DeploymentOperationsListAtTenantScopeOptionalParams | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtTenantScopeResponse> { return this.client.sendOperationRequest( { deploymentName, options }, listAtTenantScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtTenantScopeResponse>; } /** * Gets a deployments operation. * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsGetAtManagementGroupScopeResponse> */ getAtManagementGroupScope(groupId: string, deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsGetAtManagementGroupScopeResponse>; /** * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param callback The callback */ getAtManagementGroupScope(groupId: string, deploymentName: string, operationId: string, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; /** * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The optional parameters * @param callback The callback */ getAtManagementGroupScope(groupId: string, deploymentName: string, operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; getAtManagementGroupScope(groupId: string, deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperation>, callback?: msRest.ServiceCallback<Models.DeploymentOperation>): Promise<Models.DeploymentOperationsGetAtManagementGroupScopeResponse> { return this.client.sendOperationRequest( { groupId, deploymentName, operationId, options }, getAtManagementGroupScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsGetAtManagementGroupScopeResponse>; } /** * Gets all deployments operations for a deployment. * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtManagementGroupScopeResponse> */ listAtManagementGroupScope(groupId: string, deploymentName: string, options?: Models.DeploymentOperationsListAtManagementGroupScopeOptionalParams): Promise<Models.DeploymentOperationsListAtManagementGroupScopeResponse>; /** * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param callback The callback */ listAtManagementGroupScope(groupId: string, deploymentName: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param groupId The management group ID. * @param deploymentName The name of the deployment. * @param options The optional parameters * @param callback The callback */ listAtManagementGroupScope(groupId: string, deploymentName: string, options: Models.DeploymentOperationsListAtManagementGroupScopeOptionalParams, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtManagementGroupScope(groupId: string, deploymentName: string, options?: Models.DeploymentOperationsListAtManagementGroupScopeOptionalParams | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtManagementGroupScopeResponse> { return this.client.sendOperationRequest( { groupId, deploymentName, options }, listAtManagementGroupScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtManagementGroupScopeResponse>; } /** * Gets a deployments operation. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsGetAtSubscriptionScopeResponse> */ getAtSubscriptionScope(deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsGetAtSubscriptionScopeResponse>; /** * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param callback The callback */ getAtSubscriptionScope(deploymentName: string, operationId: string, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; /** * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The optional parameters * @param callback The callback */ getAtSubscriptionScope(deploymentName: string, operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; getAtSubscriptionScope(deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperation>, callback?: msRest.ServiceCallback<Models.DeploymentOperation>): Promise<Models.DeploymentOperationsGetAtSubscriptionScopeResponse> { return this.client.sendOperationRequest( { deploymentName, operationId, options }, getAtSubscriptionScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsGetAtSubscriptionScopeResponse>; } /** * Gets all deployments operations for a deployment. * @param deploymentName The name of the deployment. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtSubscriptionScopeResponse> */ listAtSubscriptionScope(deploymentName: string, options?: Models.DeploymentOperationsListAtSubscriptionScopeOptionalParams): Promise<Models.DeploymentOperationsListAtSubscriptionScopeResponse>; /** * @param deploymentName The name of the deployment. * @param callback The callback */ listAtSubscriptionScope(deploymentName: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param deploymentName The name of the deployment. * @param options The optional parameters * @param callback The callback */ listAtSubscriptionScope(deploymentName: string, options: Models.DeploymentOperationsListAtSubscriptionScopeOptionalParams, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtSubscriptionScope(deploymentName: string, options?: Models.DeploymentOperationsListAtSubscriptionScopeOptionalParams | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtSubscriptionScopeResponse> { return this.client.sendOperationRequest( { deploymentName, options }, listAtSubscriptionScopeOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtSubscriptionScopeResponse>; } /** * Gets a deployments operation. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsGetResponse> */ get(resourceGroupName: string, deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param callback The callback */ get(resourceGroupName: string, deploymentName: string, operationId: string, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param operationId The ID of the operation to get. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, deploymentName: string, operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperation>): void; get(resourceGroupName: string, deploymentName: string, operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperation>, callback?: msRest.ServiceCallback<Models.DeploymentOperation>): Promise<Models.DeploymentOperationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, deploymentName, operationId, options }, getOperationSpec, callback) as Promise<Models.DeploymentOperationsGetResponse>; } /** * Gets all deployments operations for a deployment. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListResponse> */ list(resourceGroupName: string, deploymentName: string, options?: Models.DeploymentOperationsListOptionalParams): Promise<Models.DeploymentOperationsListResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param callback The callback */ list(resourceGroupName: string, deploymentName: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param deploymentName The name of the deployment. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, deploymentName: string, options: Models.DeploymentOperationsListOptionalParams, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; list(resourceGroupName: string, deploymentName: string, options?: Models.DeploymentOperationsListOptionalParams | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, deploymentName, options }, listOperationSpec, callback) as Promise<Models.DeploymentOperationsListResponse>; } /** * Gets all deployments operations for a deployment. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtScopeNextResponse> */ listAtScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsListAtScopeNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listAtScopeNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listAtScopeNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtScopeNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listAtScopeNextOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtScopeNextResponse>; } /** * Gets all deployments operations for a deployment. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtTenantScopeNextResponse> */ listAtTenantScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsListAtTenantScopeNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listAtTenantScopeNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listAtTenantScopeNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtTenantScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtTenantScopeNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listAtTenantScopeNextOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtTenantScopeNextResponse>; } /** * Gets all deployments operations for a deployment. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtManagementGroupScopeNextResponse> */ listAtManagementGroupScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsListAtManagementGroupScopeNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listAtManagementGroupScopeNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listAtManagementGroupScopeNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtManagementGroupScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtManagementGroupScopeNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listAtManagementGroupScopeNextOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtManagementGroupScopeNextResponse>; } /** * Gets all deployments operations for a deployment. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListAtSubscriptionScopeNextResponse> */ listAtSubscriptionScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsListAtSubscriptionScopeNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listAtSubscriptionScopeNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listAtSubscriptionScopeNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listAtSubscriptionScopeNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListAtSubscriptionScopeNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listAtSubscriptionScopeNextOperationSpec, callback) as Promise<Models.DeploymentOperationsListAtSubscriptionScopeNextResponse>; } /** * Gets all deployments operations for a deployment. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DeploymentOperationsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DeploymentOperationsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeploymentOperationsListResult>, callback?: msRest.ServiceCallback<Models.DeploymentOperationsListResult>): Promise<Models.DeploymentOperationsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.DeploymentOperationsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getAtScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "{scope}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", urlParameters: [ Parameters.scope, Parameters.deploymentName, Parameters.operationId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "{scope}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", urlParameters: [ Parameters.scope, Parameters.deploymentName ], queryParameters: [ Parameters.top, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getAtTenantScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", urlParameters: [ Parameters.deploymentName, Parameters.operationId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtTenantScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Resources/deployments/{deploymentName}/operations", urlParameters: [ Parameters.deploymentName ], queryParameters: [ Parameters.top, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getAtManagementGroupScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", urlParameters: [ Parameters.groupId, Parameters.deploymentName, Parameters.operationId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtManagementGroupScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Management/managementGroups/{groupId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", urlParameters: [ Parameters.groupId, Parameters.deploymentName ], queryParameters: [ Parameters.top, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getAtSubscriptionScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", urlParameters: [ Parameters.deploymentName, Parameters.operationId, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtSubscriptionScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", urlParameters: [ Parameters.deploymentName, Parameters.subscriptionId ], queryParameters: [ Parameters.top, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}", urlParameters: [ Parameters.resourceGroupName, Parameters.deploymentName, Parameters.operationId, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperation }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations", urlParameters: [ Parameters.resourceGroupName, Parameters.deploymentName, Parameters.subscriptionId ], queryParameters: [ Parameters.top, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtScopeNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtTenantScopeNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtManagementGroupScopeNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAtSubscriptionScopeNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeploymentOperationsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
/// <reference path="../../definitions/Q.d.ts" /> /// <reference path="../../definitions/shelljs.d.ts" /> import path = require('path'); import fs = require('fs'); import zlib = require('zlib'); import stream = require('stream'); import Q = require("q"); import shelljs = require("shelljs"); import ctxm = require('../../context'); import cm = require('../../common'); import util = require('../../utilities'); import agentifm = require('vso-node-api/interfaces/TaskAgentInterfaces'); import buildifm = require('vso-node-api/interfaces/BuildInterfaces'); import ifm = require('../../interfaces'); import webapim = require("vso-node-api/WebApi"); import tm = require('../../tracing'); import dropm = require('./lib/dropUploader'); import plugins = require('../../plugins'); var stagingOptionId: string = "82f9a3e8-3930-482e-ac62-ae3276f284d5"; var dropOptionId: string = "e8b30f6f-039d-4d34-969c-449bbe9c3b9e"; var _trace: tm.Tracing; function _ensureTracing(ctx: cm.IExecutionContext, area: string) { _trace = new tm.Tracing(__filename, ctx.traceWriter); _trace.enter(area); } exports.pluginName = function () { return "buildDrop"; } exports.pluginTitle = function () { return "Build Drop" } exports.afterJobPlugins = function (executionContext: cm.IExecutionContext) { /** * this plugin handles both the "copy to staging folder" and "create drop" build options * this way we can ensure that they happen in the correct order */ var afterJobPlugins: plugins.IPlugin[] = []; var options = executionContext.jobInfo.jobMessage.environment.options; if (options) { var stagingOption: agentifm.JobOption = options[stagingOptionId]; if (stagingOption) { afterJobPlugins.push(new CopyToStagingFolder(stagingOption)); } var dropOption: agentifm.JobOption = options[dropOptionId]; if (dropOption) { afterJobPlugins.push(new CreateDrop(stagingOption, dropOption)); } } return afterJobPlugins; }; class CopyToStagingFolder implements plugins.IPlugin { private _stagingOption: agentifm.JobOption; public afterId: string; constructor(stagingOption: agentifm.JobOption) { this._stagingOption = stagingOption; } public pluginName(): string { return "copyToStagingFolder"; } public pluginTitle(): string { return "Copy to staging folder"; } public shouldRun(jobSuccess: boolean, executionContext: cm.IExecutionContext) { _ensureTracing(executionContext, 'shouldRun'); _trace.write('shouldRun: ' + jobSuccess); return jobSuccess; } public afterJob(pluginContext: cm.IExecutionContext, callback: (err?: any) => void) { _ensureTracing(pluginContext, 'afterJob'); this._copyToStagingFolder(pluginContext) .then(() => callback()) .fail((err: any) => { callback(err); }); } private _copyToStagingFolder(ctx: cm.IExecutionContext): Q.Promise<any> { // determine root: $(build.sourcesdirectory) _ensureTracing(ctx, 'copyToStagingFolder'); ctx.info("looking for source in " + ctxm.WellKnownVariables.sourceFolder); var environment = ctx.jobInfo.jobMessage.environment; var sourcesRoot: string = environment.variables[ctxm.WellKnownVariables.sourceFolder].replaceVars(environment.variables); _trace.state('sourcesRoot', sourcesRoot); var stagingFolder = getStagingFolder(ctx, this._stagingOption); var searchPattern = this._stagingOption.data["pattern"]; if (searchPattern) { // root the search pattern searchPattern = searchPattern.replaceVars(environment.variables); // fix semicolons searchPattern = searchPattern.replace(";;", "\0"); // promises containing lists of files to copy var filesPromises: Q.IPromise<string[]>[] = []; var searchPatterns = searchPattern.split(";"); searchPatterns.forEach((pattern: string, index: number) => { pattern = pattern.replace('\0', ';'); if (!isPathRooted(pattern) && sourcesRoot) { pattern = path.join(sourcesRoot, pattern); } _trace.state('pattern', pattern); // get list of files to copy var filesPromise: Q.IPromise<string[]>; if (pattern.indexOf('*') > -1 || pattern.indexOf('?') > -1) { ctx.info("Wildcard found in pattern parameter."); filesPromise = findMatchingFiles(ctx, null, pattern, false, true); } else { filesPromise = Q([pattern]); } filesPromises.push(filesPromise); }); // TODO: staging folder should be created and defined outside of this plugin // so if user opts out of copy pattern, they can still run a script. ctx.info("Staging folder: " + stagingFolder); var createStagingFolderPromise = util.ensurePathExists(stagingFolder); var deferred = Q.defer(); Q.all([Q.all(filesPromises), createStagingFolderPromise]) .then((results: any[]) => { var filesArrays: string[][] = results[0]; var files: string[] = Array.prototype.concat.apply([], filesArrays); ctx.info("found " + files.length + " files or folders"); _trace.state('files', files); var commonRoot = getCommonLocalPath(files); var useCommonRoot = !!commonRoot; if (useCommonRoot) { ctx.info("There is a common root (" + commonRoot + ") for the files. Using the remaining path elements in staging folder."); } try { files.forEach((file: string) => { var targetPath = stagingFolder; if (useCommonRoot) { var relativePath = file.substring(commonRoot.length) .replace(/^\\/g, "") .replace(/^\//g, ""); targetPath = path.join(stagingFolder, relativePath); } _trace.state('targetPath', targetPath); ctx.info("Copying all files from " + file + " to " + targetPath); shelljs.cp("-Rf", path.join(file, "*"), targetPath); }); deferred.resolve(null); } catch (err) { deferred.reject(err); } }) .fail((err: any) => { deferred.reject(err); }); return deferred.promise; } else { ctx.warning("No pattern specified. Nothing to copy."); return Q(null); } } } class CreateDrop implements plugins.IPlugin { private _stagingOption: agentifm.JobOption; private _dropOption: agentifm.JobOption; public afterId: string; constructor(stagingOption: agentifm.JobOption, dropOption: agentifm.JobOption) { this._stagingOption = stagingOption; this._dropOption = dropOption; } public pluginName(): string { return "createDrop"; } public pluginTitle(): string { return "Create drop"; } public shouldRun(jobSuccess: boolean, ctx: cm.IExecutionContext) { _ensureTracing(ctx, 'shouldRun'); _trace.write('shouldRun: ' + jobSuccess); return jobSuccess; } public afterJob(pluginContext: cm.IExecutionContext, callback: (err?: any) => void) { _ensureTracing(pluginContext, 'afterJob'); this._createDrop(pluginContext) .then(() => callback()) .fail((err: any) => { callback(err); }); } private _createDrop(ctx: cm.IExecutionContext): Q.Promise<any> { _ensureTracing(ctx, 'createDrop'); var location = this._dropOption.data["location"]; var path = this._dropOption.data["path"]; var stagingFolder = getStagingFolder(ctx, this._stagingOption); var environment = ctx.jobInfo.jobMessage.environment; if (location) { location = location.replaceVars(environment.variables); } if (path) { path = path.replaceVars(environment.variables); } ctx.info("drop location = " + location); ctx.info("drop path = " + path); // determine drop provider var artifactType: string; var dropPromise: Q.Promise<string> = Q(<string>null); switch (location) { case "filecontainer": artifactType = "container"; dropPromise = this._copyToFileContainer(ctx, stagingFolder, path); break; case "uncpath": artifactType = "filepath"; dropPromise = this._copyToUncPath(ctx, stagingFolder, path); break; } return dropPromise.then((artifactLocation: string) => { if (artifactLocation) { var serverUrl = environment.systemConnection.url; var accessToken = environment.systemConnection.authorization.parameters['AccessToken']; var token = webapim.getBearerHandler(accessToken); var buildClient = new webapim.WebApi(serverUrl, webapim.getBearerHandler(accessToken)).getQBuildApi(); return ctx.service.postArtifact(ctx.variables[ctxm.WellKnownVariables.projectId], parseInt(ctx.variables[ctxm.WellKnownVariables.buildId]), <buildifm.BuildArtifact>{ name: "drop", resource: { data: artifactLocation, type: artifactType } }); } else { ctx.warning("Drop location/path is missing or not supported. Not creating a build drop artifact."); return Q(null); } }); } private _copyToFileContainer(ctx: cm.IExecutionContext, stagingFolder: string, fileContainerPath: string): Q.Promise<string> { _ensureTracing(ctx, 'copyToFileContainer'); var fileContainerRegExp = /^#\/(\d+)(\/.*)$/; var containerId: number; var containerPath: string = "/"; var match = fileContainerPath.match(fileContainerRegExp); if (match) { containerId = parseInt(match[1]); if (match.length > 2) { containerPath = match[2]; } } else { ctx.error("invalid file container path '" + fileContainerPath + "'"); return Q(<string>null); } var containerRoot = containerPath; if (containerRoot.charAt(containerPath.length) !== '/') { containerRoot += '/'; } if (containerRoot.charAt(0) === '/') { containerRoot = containerRoot.substr(1); } _trace.state('containerRoot', containerRoot); var contentMap: { [path: string]: ifm.FileContainerItemInfo; } = {} return readDirectory(ctx, stagingFolder, true, false) .then((files: string[]) => { _trace.state('files', files); return dropm.uploadFiles(ctx, stagingFolder, containerId, containerRoot, files); /* return Q.all(files.map((fullPath: string) => { return Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { _trace.state('fullPath', fullPath); _trace.state('size', stat.size); return ctx.feedback.uploadFileToContainer(containerId, { fullPath: fullPath, containerItem: { containerId: containerId, itemType: ifm.ContainerItemType.File, path: containerRoot + fullPath.substring(stagingFolder.length + 1) }, uncompressedLength: stat.size, isGzipped: false }); }); })) */ }) .then(() => { ctx.info("container items uploaded"); _trace.state('fileContainerPath', fileContainerPath); return fileContainerPath; }); } private _copyToUncPath(ctx: cm.IExecutionContext, stagingFolder: string, uncPath: string): Q.Promise<string> { ctx.info("Copying all files from " + stagingFolder + " to " + uncPath); shelljs.cp("-Rf", path.join(stagingFolder, "*"), uncPath); return Q(uncPath); } } function getStagingFolder(ctx: cm.IExecutionContext, stagingOption: agentifm.JobOption): string { // determine staging folder: $(build.stagingdirectory)[/{stagingfolder}] var environment = ctx.jobInfo.jobMessage.environment; ctx.info("looking for staging folder in " + ctxm.WellKnownVariables.stagingFolder); var stagingFolder = environment.variables[ctxm.WellKnownVariables.stagingFolder].replaceVars(environment.variables) if (stagingOption) { var relativeStagingPath = stagingOption.data["stagingfolder"]; if (relativeStagingPath) { stagingFolder = path.join(stagingFolder, relativeStagingPath.replaceVars(environment.variables)); } } return stagingFolder; } var PagesPerBlock = 32; var BytesPerPage = 64 * 1024; var BlockSize = PagesPerBlock * BytesPerPage; function getCommonLocalPath(files: string[]): string { if (!files || files.length === 0) { return ""; } else { var root: string = files[0]; for (var index = 1; index < files.length; index++) { root = _getCommonLocalPath(root, files[index]); if (!root) { break; } } return root; } } function _getCommonLocalPath(path1: string, path2: string): string { var path1Depth = getFolderDepth(path1); var path2Depth = getFolderDepth(path2); var shortPath: string; var longPath: string; if (path1Depth >= path2Depth) { shortPath = path2; longPath = path1; } else { shortPath = path1; longPath = path2; } while (!isSubItem(longPath, shortPath)) { var parentPath = path.dirname(shortPath); if (path.normalize(parentPath) === path.normalize(shortPath)) { break; } shortPath = parentPath; } return shortPath; } function isSubItem(item: string, parent: string): boolean { item = path.normalize(item); parent = path.normalize(parent); return item.substring(0, parent.length) == parent && (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep)); } function getFolderDepth(fullPath: string): number { if (!fullPath) { return 0; } var current = path.normalize(fullPath); var parentPath = path.dirname(current); var count = 0; while (parentPath !== current) { ++count; current = parentPath; parentPath = path.dirname(current); } return count; } function findMatchingFiles(ctx: cm.IExecutionContext, rootFolder: string, pattern: string, includeFiles: boolean, includeFolders: boolean): Q.IPromise<string[]> { pattern = pattern.replace(';;', '\0'); var patterns = pattern.split(';'); var includePatterns: string[] = []; var excludePatterns: RegExp[] = []; patterns.forEach((p: string, index: number) => { p = p.replace('\0', ';'); var isIncludePattern: boolean = true; if (p.substring(0, 2) === "+:") { p = p.substring(2); } else if (p.substring(0, 2) === "-:") { isIncludePattern = false; p = p.substring(2); } if (!isPathRooted(p) && rootFolder) { p = path.join(rootFolder, p); } if (!isValidPattern(p)) { // TODO: report error ctx.error("invalid pattern " + p); } if (isIncludePattern) { includePatterns.push(p); } else { excludePatterns.push(convertPatternToRegExp(p)); } }); return getMatchingItems(ctx, includePatterns, excludePatterns, includeFiles, includeFolders); } function getMatchingItems(ctx: cm.IExecutionContext, includePatterns: string[], excludePatterns: RegExp[], includeFiles: boolean, includeFolders: boolean): Q.IPromise<string[]> { var fileMap: any = {}; var funcs = includePatterns.map((includePattern: string, index: number) => { return (files: string[]) => { var pathPrefix = getPathPrefix(includePattern); var patternRegex = convertPatternToRegExp(includePattern); return readDirectory(ctx, pathPrefix, includeFiles, includeFolders) .then((paths: string[]) => { paths.forEach((path: string, index: number) => { var normalizedPath = path.replace(/\\/g, '/'); var alternatePath = normalizedPath + "//"; var isMatch = false; if (patternRegex.test(normalizedPath) || (includeFolders && patternRegex.test(alternatePath))) { isMatch = true; for (var i = 0; i < excludePatterns.length; i++) { var excludePattern = excludePatterns[i]; if (excludePattern.test(normalizedPath) || (includeFolders && excludePattern.test(alternatePath))) { isMatch = false; break; } } } if (isMatch && !fileMap[path]) { fileMap[path] = true; files.push(path); } }); return files; }); } }); return funcs.reduce(Q.when, Q([])); } function readDirectory(ctx: cm.IExecutionContext, directory: string, includeFiles: boolean, includeFolders: boolean): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, directory) .then((files: string[]) => { var count = files.length; if (count > 0) { files.forEach((file: string, index: number) => { var fullPath = path.join(directory, file); Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { if (stat && stat.isDirectory()) { readDirectory(ctx, fullPath, includeFiles, includeFolders) .then((moreFiles: string[]) => { results = results.concat(moreFiles); if (--count === 0) { deferred.resolve(results); } }, (error) => { ctx.error(error.toString()); }); } else { if (includeFiles) { results.push(fullPath); } if (--count === 0) { deferred.resolve(results); } } }); }); } else { deferred.resolve(results); } }, (error) => { ctx.error(error.toString()); deferred.reject(error); }); return deferred.promise; } function getPathPrefix(pattern: string): string { var starIndex = pattern.indexOf('*'); var questionIndex = pattern.indexOf('?'); var index: number; if (starIndex > -1 && questionIndex > -1) { index = Math.min(starIndex, questionIndex); } else { index = Math.max(starIndex, questionIndex); } if (index < 0) { return path.dirname(pattern); } else { return pattern.substring(0, index); } } function isPathRooted(filePath: string): boolean { if (filePath.substring(0, 2) === "\\\\") { return true; } else if (filePath.charAt(0) === "/") { return true; } else { var regex = /^[a-zA-Z]:/; return regex.test(filePath); } } function isValidPattern(pattern: string): boolean { if (pattern.length > 0 && pattern.charAt(pattern.length - 1) === "\\" || pattern.charAt(pattern.length - 1) === "/") { return false; } else { return true; } } function convertPatternToRegExp(pattern: string): RegExp { pattern = pattern.replace(/\\/g, '/') .replace(/([.?*+^$[\]\\(){}|-])/g, "$1") .replace(/\/\*\*\//g, "((/.+/)|(/))") .replace(/\*\*/g, ".*") .replace("*", "[^/]*") .replace(/\?/g, "."); return new RegExp('^' + pattern + '$', "i"); }
the_stack
import * as os from 'os'; import * as fs from 'fs'; import * as path from 'path'; import * as tl from 'azure-pipelines-task-lib/task'; import * as trm from 'azure-pipelines-task-lib/toolrunner'; import httpClient = require("typed-rest-client/HttpClient"); import httpInterfaces = require("typed-rest-client/Interfaces"); import { VersionInfo, Channel, VersionFilesData, VersionParts } from "./models" import * as utils from "./versionutilities"; export class DotNetCoreVersionFetcher { constructor() { let proxyUrl: string = tl.getVariable("agent.proxyurl"); var requestOptions: httpInterfaces.IRequestOptions = proxyUrl ? { proxy: { proxyUrl: proxyUrl, proxyUsername: tl.getVariable("agent.proxyusername"), proxyPassword: tl.getVariable("agent.proxypassword"), proxyBypassHosts: tl.getVariable("agent.proxybypasslist") ? JSON.parse(tl.getVariable("agent.proxybypasslist")) : null } } : {}; this.httpCallbackClient = new httpClient.HttpClient(tl.getVariable("AZURE_HTTP_USER_AGENT"), null, requestOptions); this.channels = []; } public async getVersionInfo(versionSpec: string, packageType: string, includePreviewVersions: boolean): Promise<VersionInfo> { var requiredVersionInfo: VersionInfo = null; if (!this.channels || this.channels.length < 1) { await this.setReleasesIndex(); } let channelInformation = this.getVersionChannel(versionSpec); if (channelInformation) { requiredVersionInfo = await this.getVersionFromChannel(channelInformation, versionSpec, packageType, includePreviewVersions); } if (!requiredVersionInfo && !versionSpec.endsWith("x")) { console.log(tl.loc("FallingBackToAdjacentChannels", versionSpec)); requiredVersionInfo = await this.getVersionFromOtherChannels(versionSpec, packageType, includePreviewVersions); } if (!requiredVersionInfo) { throw tl.loc("VersionNotFound", packageType, versionSpec); } let dotNetSdkVersionTelemetry = `{"userVersion":"${versionSpec}", "resolvedVersion":"${requiredVersionInfo.getVersion()}"}`; console.log("##vso[telemetry.publish area=TaskDeploymentMethod;feature=DotNetCoreInstallerV1]" + dotNetSdkVersionTelemetry); return requiredVersionInfo; } public getDownloadUrl(versionInfo: VersionInfo): string { console.log(tl.loc("GettingDownloadUrl", versionInfo.getPackageType(), versionInfo.getVersion())); let osSuffixes = this.detectMachineOS(); let downloadPackageInfoObject: VersionFilesData = null; osSuffixes.find((osSuffix) => { downloadPackageInfoObject = versionInfo.getFiles().find((downloadPackageInfo: VersionFilesData) => { if (downloadPackageInfo.rid && osSuffix && downloadPackageInfo.rid.toLowerCase() == osSuffix.toLowerCase()) { if ((osSuffix.split("-")[0] == "win" && downloadPackageInfo.name.endsWith(".zip")) || (osSuffix.split("-")[0] != "win" && downloadPackageInfo.name.endsWith("tar.gz"))) { return true; } } return false; }); return !!downloadPackageInfoObject; }); if (!!downloadPackageInfoObject && downloadPackageInfoObject.url) { tl.debug("Got download URL for platform with rid: " + downloadPackageInfoObject.rid); return downloadPackageInfoObject.url; } throw tl.loc("DownloadUrlForMatchingOsNotFound", versionInfo.getPackageType(), versionInfo.getVersion(), osSuffixes.toString()); } private setReleasesIndex(): Promise<void> { return this.httpCallbackClient.get(DotNetCoreReleasesIndexUrl) .then((response: httpClient.HttpClientResponse) => { return response.readBody(); }) .then((body: string) => { let parsedReleasesIndexBody = JSON.parse(body); if (!parsedReleasesIndexBody || !parsedReleasesIndexBody["releases-index"] || parsedReleasesIndexBody["releases-index"].length < 1) { throw tl.loc("ReleasesIndexBodyIncorrect") } parsedReleasesIndexBody["releases-index"].forEach(channelRelease => { if (channelRelease) { try { this.channels.push(new Channel(channelRelease)); } catch (ex) { tl.debug("Channel information in releases-index.json was not proper. Error: " + JSON.stringify(ex)); // do not fail, try to find version in the available channels. } } }); }) .catch((ex) => { throw tl.loc("ExceptionWhileDownloadOrReadReleasesIndex", JSON.stringify(ex)); }); } private getVersionChannel(versionSpec: string): Channel { let versionParts = new VersionParts(versionSpec); let requiredChannelVersion = `${versionParts.majorVersion}.${versionParts.minorVersion}`; if (versionParts.minorVersion == "x") { var latestChannelVersion: string = `${versionParts.majorVersion}.0`; this.channels.forEach(channel => { // todo: should also check if the channel is in preview state, if so then only select the channel if includePreviewVersion should be true. // As a channel with state in preview will only have preview releases. // example: versionSpec: 3.x Channels: 3.0 (current), 3.1 (preview). // if (includePreviewVersion == true) select 3.1 // else select 3.0 if (utils.compareChannelVersion(channel.channelVersion, latestChannelVersion) > 0 && channel.channelVersion.startsWith(versionParts.majorVersion)) { latestChannelVersion = channel.channelVersion; } }); requiredChannelVersion = latestChannelVersion; } tl.debug(tl.loc("RequiredChannelVersionForSpec", requiredChannelVersion, versionSpec)); return this.channels.find(channel => { if (channel.channelVersion == requiredChannelVersion) { return true } }); } private getVersionFromChannel(channelInformation: Channel, versionSpec: string, packageType: string, includePreviewVersions: boolean): Promise<VersionInfo> { var releasesJsonUrl: string = channelInformation.releasesJsonUrl; if (releasesJsonUrl) { return this.httpCallbackClient.get(releasesJsonUrl) .then((response: httpClient.HttpClientResponse) => { return response.readBody(); }) .then((body: string) => { var channelReleases = JSON.parse(body).releases; let versionInfoList: VersionInfo[] = []; channelReleases.forEach((release) => { if (release && release[packageType] && release[packageType].version) { try { let versionInfo: VersionInfo = new VersionInfo(release[packageType], packageType); versionInfoList.push(versionInfo); } catch (err) { tl.debug(tl.loc("VersionInformationNotComplete", release[packageType].version, err)); } } }); let matchedVersionInfo = utils.getMatchingVersionFromList(versionInfoList, versionSpec, includePreviewVersions); if (!matchedVersionInfo) { console.log(tl.loc("MatchingVersionNotFound", packageType, versionSpec)); return null; } console.log(tl.loc("MatchingVersionForUserInputVersion", matchedVersionInfo.getVersion(), channelInformation.channelVersion, versionSpec)) return matchedVersionInfo; }) .catch((ex) => { tl.error(tl.loc("ErrorWhileGettingVersionFromChannel", versionSpec, channelInformation.channelVersion, JSON.stringify(ex))); return null; }); } else { tl.error(tl.loc("UrlForReleaseChannelNotFound", channelInformation.channelVersion)); } } private async getVersionFromOtherChannels(version: string, packageType: string, includePreviewVersions: boolean): Promise<VersionInfo> { let fallbackChannels = this.getChannelsForMajorVersion(version); if (!fallbackChannels && fallbackChannels.length < 1) { throw tl.loc("NoSuitableChannelWereFound", version); } var versionInfo: VersionInfo = null; for (var i = 0; i < fallbackChannels.length; i++) { console.log(tl.loc("LookingForVersionInChannel", (fallbackChannels[i]).channelVersion)); versionInfo = await this.getVersionFromChannel(fallbackChannels[i], version, packageType, includePreviewVersions); if (versionInfo) { break; } } return versionInfo; } private getChannelsForMajorVersion(version: string): Channel[] { var versionParts = new VersionParts(version); let adjacentChannels: Channel[] = []; this.channels.forEach(channel => { if (channel.channelVersion.startsWith(`${versionParts.majorVersion}`)) { adjacentChannels.push(channel); } }); return adjacentChannels; } private detectMachineOS(): string[] { let osSuffix = []; let scriptRunner: trm.ToolRunner; try { console.log(tl.loc("DetectingPlatform")); if (tl.osType().match(/^Win/)) { let escapedScript = path.join(this.getCurrentDir(), 'externals', 'get-os-platform.ps1').replace(/'/g, "''"); let command = `& '${escapedScript}'` let powershellPath = tl.which('powershell', true); scriptRunner = tl.tool(powershellPath) .line('-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command') .arg(command); } else { let scriptPath = path.join(this.getCurrentDir(), 'externals', 'get-os-distro.sh'); this.setFileAttribute(scriptPath, "777"); scriptRunner = tl.tool(tl.which(scriptPath, true)); } let result: trm.IExecSyncResult = scriptRunner.execSync(); if (result.code != 0) { throw tl.loc("getMachinePlatformFailed", result.error ? result.error.message : result.stderr); } let output: string = result.stdout; let index; if ((index = output.indexOf("Primary:")) >= 0) { let primary = output.substr(index + "Primary:".length).split(os.EOL)[0]; osSuffix.push(primary); console.log(tl.loc("PrimaryPlatform", primary)); } if ((index = output.indexOf("Legacy:")) >= 0) { let legacy = output.substr(index + "Legacy:".length).split(os.EOL)[0]; osSuffix.push(legacy); console.log(tl.loc("LegacyPlatform", legacy)); } if (osSuffix.length == 0) { throw tl.loc("CouldNotDetectPlatform"); } } catch (ex) { throw tl.loc("FailedInDetectingMachineArch", JSON.stringify(ex)); } return osSuffix; } private setFileAttribute(file: string, mode: string): void { fs.chmodSync(file, mode); } private getCurrentDir(): string { return __dirname; } private channels: Channel[]; private httpCallbackClient: httpClient.HttpClient; } const DotNetCoreReleasesIndexUrl: string = "https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases-index.json";
the_stack
import { Display, screen } from 'electron' import { ipcMain as ipc } from 'electron-better-ipc' import electronLog from 'electron-log' import { maxBy } from 'lodash' import moment from 'moment' import { ImageSource, SatelliteView } from '../shared/config_types' import { VIEW_DOWNLOAD_PROGRESS } from '../shared/IpcDefinitions' import { AppConfigStore } from './app_config_store' import { DownloadedImage } from './downloaded_image' import { LockInvalidatedError, MonitorConfigChangedError, RequestCancelledError, RequestError, ViewConfigAccessError, ViewNotSetError } from './errors' import { downloadImage } from './image_downloader' import { OSWallpaperInterface } from './os_wallpaper_interface' import { MacOSWallpaperInterface } from './os_wallpaper_interface/macos' import { WindowsWallpaperInterface } from './os_wallpaper_interface/windows' import { SatelliteConfigStore } from './satellite_config_store' import { Initiator, UpdateLock } from './update_lock' const log = electronLog.scope('wallpaper-manager') let wallpaperInterface: OSWallpaperInterface if (process.platform === 'darwin') { wallpaperInterface = new MacOSWallpaperInterface() } else { wallpaperInterface = new WindowsWallpaperInterface() } export const latestViewDownloadTimes: { [key: number]: number | undefined } = {} export class WallpaperManager { private static instance?: WallpaperManager /** * Path to the current wallpaper image */ imagePath?: string public static get Instance(): WallpaperManager { if (this.instance === undefined) { this.instance = new this() } return this.instance } /** * Get all non-internal monitors. * * @returns All non-internal monitors */ private static getMonitors(): Display[] { const allMonitors = screen.getAllDisplays().filter(monitor => !monitor.internal) log.debug( 'All monitors:', allMonitors.map(monitor => monitor.id) ) return allMonitors } /** * Select the image source that best matches the monitor. * * @param monitor - Monitor in question * @param sources - Possible image sources * @returns Selected image */ private static selectImageSourceForMonitor( monitor: Display, sources: ImageSource[] ): ImageSource { for (const source of sources) { if ( source.dimensions[0] > monitor.scaleFactor * monitor.size.width && source.dimensions[1] > monitor.scaleFactor * monitor.size.height ) { return source } } return sources[sources.length - 1] } /** * Given a view, determine the optimal image needed. * * Image is selected based on the resolution of available screens. * * @param view - Satellite view * @param monitors - Computer monitors currently available * @returns Selected image */ private static getOptimalImageFromView(view: SatelliteView, monitors: Display[]): ImageSource { // Get the best image size for each monitor const possibleImages = monitors.map(monitor => WallpaperManager.selectImageSourceForMonitor(monitor, view.imageSources) ) // Pick the biggest one const bestImage = maxBy(possibleImages, image => image.dimensions[0] * image.dimensions[1])! log.debug(`Optimal image for view "${view.id}": ${bestImage.id}`) return bestImage } /** * Check if the monitor configuration has changed. * * @param oldMonitors - Old configuration of monitors * @param newMonitors - New configuration of monitors * @returns Whether the config has changed */ private static haveMonitorsChanged(oldMonitors: Display[], newMonitors: Display[]): boolean { // TODO: Check monitor sizes too return oldMonitors.length !== newMonitors.length } /** * Non-error catching pipeline to update the wallpaper. * * @param lock - Acquired update pipeline lock * @param force - Whether to force re-download the image * @throws {ViewNotSetError} if view not set in config when running * @throws {ViewConfigAccessError} if there's an issue while obtaining the * current view config * @throws {LockInvalidatedError} if lock is invalidated while updating * @throws {RequestCancelledError} if download request was cancelled * @throws {FileDoesNotExistError} if image not downloaded properly * @throws {MonitorConfigChangedError} if the monitor config changed while * running update tasks * @throws {Error} Unknown errors */ public static async updatePipeline(lock: UpdateLock, force: boolean): Promise<void> { log.debug('Entering update pipeline') const viewId = AppConfigStore.currentViewId // If no view ID set, nothing to update if (viewId === undefined) { log.debug('No view set to update') throw new ViewNotSetError() } // Fetch the view config let viewConfig: SatelliteView | undefined try { viewConfig = await SatelliteConfigStore.Instance.getViewById(viewId) } catch (error) { log.debug('Error while fetching view config for update pipeline') if (error instanceof RequestError) { throw new ViewConfigAccessError( `Error while downloading view config for ID "${viewId}"` ) } throw error } // Make sure we still have the lock if (!lock.isStillHeld()) { log.debug('Lost update lock after getting view config') throw new LockInvalidatedError() } // If no config for ID, we can't proceed if (viewConfig === undefined) { log.debug('No view config for ID:', viewId) throw new ViewConfigAccessError(`No view config matching ID "${viewId}"`) } // Determine which image we need log.debug('Determining which image is needed to update') const monitors = WallpaperManager.getMonitors() const imageConfig = WallpaperManager.getOptimalImageFromView(viewConfig, monitors) // Get the newest downloaded image for the config let imageToSet = await DownloadedImage.getNewestDownloadedImage(imageConfig.id) // Make sure we still have the lock if (!lock.isStillHeld()) { log.debug('Lost update lock after checking for newest downloaded image') throw new LockInvalidatedError() } const oldImageToSet = imageToSet // If there isn't a downloaded image, it's too old, or we are forced, download a new one if ( imageToSet === undefined || moment.utc().diff(imageToSet.timestamp, 'seconds') > imageConfig.updateInterval || force === true ) { log.info('New image must be downloaded') imageToSet = await downloadImage( imageConfig, lock.generateCancelToken(), lock, percentage => { if (mb.window !== undefined) { // Skip if percentage is a number not divisible by 5 // This prevents IPC from being overwhelmed if (percentage !== undefined && percentage !== -1 && percentage % 5 !== 0) { return } ipc.callRenderer<number | undefined>( mb.window, `${VIEW_DOWNLOAD_PROGRESS}_${viewConfig!.id}`, percentage ) } } ) // Make sure we still have the lock if (!lock.isStillHeld()) { log.debug('Lost update lock while downloading image') throw new LockInvalidatedError() } } latestViewDownloadTimes[viewId] = imageToSet.timestamp.valueOf() // Make sure the monitor config hasn't changed const newMonitors = WallpaperManager.getMonitors() if (WallpaperManager.haveMonitorsChanged(monitors, newMonitors)) { log.debug('Monitors changed during update process') throw new MonitorConfigChangedError() } // Get monitors that don't already have the image set const monitorsToSet = monitors.filter( (monitor, i) => wallpaperInterface.getWallpaper(monitor, i) !== imageToSet!.getPath() ) // Set the wallpaper on monitors that don't have it set yet monitorsToSet.forEach((monitor, i) => wallpaperInterface.setWallpaper( monitor, i, imageToSet!.getPath(), imageConfig.defaultScaling ) ) // If there was an old image and we were forced to update, delete it // Prevents images from piling up when many force updates are called if (force === true && oldImageToSet !== undefined) { log.debug( 'Deleting image superseded by forced update:', oldImageToSet.getDownloadPath() ) await oldImageToSet.delete() } } /** * Update the wallpaper according to the config. * * @param initiator - Who is initiating the update * @param force - Whether to force a re-download of the image * @returns Whether the update completed successfully */ public static async update(initiator: Initiator, force = false): Promise<boolean> { const lock = UpdateLock.acquire(initiator) // If we couldn't get the lock, we can't proceed if (lock === undefined) { log.info(`Update triggered by ${initiator}, lock acquisition failed`) return false } log.info(`Update triggered by ${initiator}, lock acquisition succeeded`) try { // Try to run the pipeline and release the lock when done await WallpaperManager.updatePipeline(lock, force) lock.release() // Delete old images await DownloadedImage.cleanupOldImages() return true } catch (error) { if (error instanceof RequestCancelledError) { log.info('Image download request cancelled') return false } log.error('Error while updating. Invalidating lock.', error) lock.invalidate() // If there was an error, we couldn't complete successfully // TODO: Log the error and let the user know if it is worth // knowing return false } } }
the_stack
import { ChildProcess, spawn } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import stream from 'stream'; import { app, App, BrowserWindow, ipcMain } from 'electron'; import { Task, tasklist } from 'tasklist'; import { BackendCode } from '@/electron-main/backend-code'; import { BackendOptions } from '@/electron-main/ipc'; import { DEFAULT_PORT, selectPort } from '@/electron-main/port-utils'; import { assert } from '@/utils/assertions'; import { wait } from '@/utils/backoff'; async function streamToString(givenStream: stream.Readable): Promise<string> { const bufferChunks: Buffer[] = []; const stringChunks: string[] = []; return new Promise((resolve, reject) => { givenStream.on('data', chunk => { if (typeof chunk === 'string') { stringChunks.push(chunk); } else { bufferChunks.push(chunk); } }); givenStream.on('error', reject); givenStream.on('end', () => { if (bufferChunks.length > 0) { try { stringChunks.push(Buffer.concat(bufferChunks).toString('utf8')); } catch (e: any) { stringChunks.push(e.message); } } resolve(stringChunks.join('\n')); }); }); } function getBackendArguments(options: Partial<BackendOptions>): string[] { const args: string[] = []; if (options.loglevel) { args.push('--loglevel', options.loglevel); } if (options.logFromOtherModules) { args.push('--logfromothermodules'); } if (options.dataDirectory) { args.push('--data-dir', options.dataDirectory); } if (options.sleepSeconds) { args.push('--sleep-secs', options.sleepSeconds.toString()); } if (options.maxLogfilesNum) { args.push('--max-logfiles-num', options.maxLogfilesNum.toString()); } if (options.maxSizeInMbAllLogs) { args.push( '--max-size-in-mb-all-logs', options.maxSizeInMbAllLogs.toString() ); } return args; } const PY_DIST_FOLDER = 'rotkehlchen_py_dist'; export default class PyHandler { readonly defaultLogDirectory: string; private rpcFailureNotifier?: any; private childProcess?: ChildProcess; private _websocketPort?: number; private executable?: string; private _corsURL?: string; private backendOutput: string = ''; private onChildError?: (err: Error) => void; private onChildExit?: (code: number, signal: any) => void; private logDirectory?: string; constructor(private app: App) { app.setAppLogsPath(path.join(app.getPath('appData'), 'rotki', 'logs')); this.defaultLogDirectory = app.getPath('logs'); this._serverUrl = ''; this._websocketUrl = ''; this.logToFile('\nStarting rotki\n'); } private _port?: number; get port(): number { assert(this._port); return this._port; } private _serverUrl: string; get serverUrl(): string { return this._serverUrl; } private _websocketUrl: string; get websocketUrl(): string { return this._websocketUrl; } get logDir(): string { if (process.env.VITE_DEV_LOGS) { return path.join('..', 'logs'); } return this.logDirectory ?? this.defaultLogDirectory; } get electronLogFile(): string { return path.join(this.logDir, 'rotki_electron.log'); } get backendLogFile(): string { return path.join(this.logDir, 'rotkehlchen.log'); } private static packagedBackendPath() { const resources = process.resourcesPath ? process.resourcesPath : __dirname; if (os.platform() === 'darwin') { return path.join(resources, PY_DIST_FOLDER, 'rotkehlchen'); } return path.join(resources, PY_DIST_FOLDER); } logToFile(msg: string | Error) { if (!msg) { return; } const message = `${new Date(Date.now()).toISOString()}: ${msg}`; console.log(message); if (!fs.existsSync(this.logDir)) { fs.mkdirSync(this.logDir); } fs.appendFileSync(this.electronLogFile, `${message}\n`); } setCorsURL(url: string) { if (url.endsWith('/')) { this._corsURL = url.substring(0, url.length - 1); } else { this._corsURL = url; } } listenForMessages() { // Listen for ack messages from renderer process ipcMain.on('ack', (event, ...args) => { if (args[0] === 1) { clearInterval(this.rpcFailureNotifier); } else { this.logToFile(`Warning: unknown ack code ${args[0]}`); } }); } logAndQuit(msg: string) { console.log(msg); this.app.quit(); } async createPyProc(window: BrowserWindow, options: Partial<BackendOptions>) { if (options.logDirectory && !fs.existsSync(options.logDirectory)) { fs.mkdirSync(options.logDirectory); } this.logDirectory = options.logDirectory; if (process.env.SKIP_PYTHON_BACKEND) { this.logToFile('Skipped starting python sub-process'); return; } if (os.platform() === 'darwin') { const release = os.release().split('.'); if (release.length > 0 && parseInt(release[0]) < 18) { this.setFailureNotification( window, 'rotki requires at least macOS Mojave', BackendCode.MACOS_VERSION ); return; } } const port = await selectPort(); const backendUrl = process.env.VITE_BACKEND_URL; assert(backendUrl); const regExp = /(.*):\/\/(.*):(.*)/; const match = backendUrl.match(regExp); assert(match && match.length === 4); const [, scheme, host, oldPort] = match; assert(host); if (port !== DEFAULT_PORT) { if (parseInt(oldPort) !== port) { this._serverUrl = `${scheme}://${host}:${port}`; this.logToFile( `Default port ${oldPort} was in use. Starting backend at ${port}` ); } } this._port = port; this._websocketPort = await selectPort(port + 1); this._websocketUrl = `${host}:${this._websocketPort}`; const args: string[] = getBackendArguments(options); if (this.guessPackaged()) { this.startProcessPackaged(port, this._websocketPort, args, window); } else { this.startProcess(port, this._websocketPort, args); } const childProcess = this.childProcess; if (!childProcess) { return; } if (childProcess.stdout) { streamToString(childProcess.stdout).then(value => this.logBackendOutput(value) ); } if (childProcess.stderr) { streamToString(childProcess.stderr).then(value => this.logBackendOutput(value) ); } const handler = this; this.onChildError = (err: Error) => { this.logToFile( `Encountered an error while trying to start the python sub-process\n\n${err}` ); // Notify the main window every 2 seconds until it acks the notification handler.setFailureNotification(window, err, BackendCode.TERMINATED); }; this.onChildExit = (code: number, signal: any) => { this.logToFile( `The Python sub-process exited with signal: ${signal} (Code: ${code})` ); if (code !== 0) { // Notify the main window every 2 seconds until it acks the notification handler.setFailureNotification( window, this.backendOutput, BackendCode.TERMINATED ); } }; childProcess.on('error', this.onChildError); childProcess.on('exit', this.onChildExit); if (childProcess) { this.logToFile( `The Python sub-process started on port: ${port} (PID: ${childProcess.pid})` ); return; } this.logToFile('The Python sub-process was not successfully started'); } async exitPyProc(restart: boolean = false) { const client = this.childProcess; this.logToFile( restart ? 'Restarting the backend' : 'Terminating the backend' ); if (this.rpcFailureNotifier) { clearInterval(this.rpcFailureNotifier); } if (restart && client) { if (this.onChildExit) { client.off('exit', this.onChildExit); } if (this.onChildError) { client.off('error', this.onChildError); } } if (process.platform === 'win32') { return this.terminateWindowsProcesses(restart); } if (client) { return this.terminateBackend(client); } } private logBackendOutput(msg: string | Error) { this.logToFile(msg); this.backendOutput += msg; } private terminateBackend = (client: ChildProcess) => new Promise<void>((resolve, reject) => { client.on('exit', () => { this.logToFile( `The Python sub-process was terminated successfully (${client.killed})` ); resolve(); this.childProcess = undefined; this._port = undefined; }); client.on('error', e => { reject(e); }); client.kill(); }); private guessPackaged() { const path = PyHandler.packagedBackendPath(); this.logToFile( `Determining if we are packaged by seeing if ${path} exists` ); return fs.existsSync(path); } private setFailureNotification( window: Electron.BrowserWindow | null, backendOutput: string | Error, code: BackendCode ) { if (this.rpcFailureNotifier) { clearInterval(this.rpcFailureNotifier); } this.rpcFailureNotifier = setInterval(function () { window?.webContents.send('failed', backendOutput, code); }, 2000); } private startProcess(port: number, websocketPort: number, args: string[]) { const defaultArgs: string[] = [ '-m', 'rotkehlchen', '--rest-api-port', port.toString(), '--websockets-api-port', websocketPort.toString() ]; if (this._corsURL) { defaultArgs.push('--api-cors', this._corsURL); } defaultArgs.push('--logfile', this.backendLogFile); if (process.env.ROTKEHLCHEN_ENVIRONMENT === 'test') { const tempPath = path.join(this.app.getPath('temp'), 'rotkehlchen'); if (!fs.existsSync(tempPath)) { fs.mkdirSync(tempPath); } defaultArgs.push('--data-dir', tempPath); } if (!process.env.VIRTUAL_ENV) { this.logAndQuit( 'ERROR: Running in development mode and not inside a python virtual environment' ); return; } const allArgs = defaultArgs.concat(args); this.logToFile( `Starting non-packaged python subprocess: python ${allArgs.join(' ')}` ); this.childProcess = spawn('python', allArgs); } private startProcessPackaged( port: number, websocketPort: number, args: string[], window: BrowserWindow ) { const distDir = PyHandler.packagedBackendPath(); const files = fs.readdirSync(distDir); if (files.length === 0) { this.logAndQuit('ERROR: No files found in the dist directory'); return; } const binaries = files.filter(file => file.startsWith('rotkehlchen-')); if (binaries.length > 1) { const names = files.join(', '); const error = `Expected only one backend binary but found multiple ones in directory: ${names}.\nThis might indicate a problematic upgrade.\n\n Please make sure only one binary file exists that matches the app version`; this.logToFile(`ERROR: ${error}`); this.setFailureNotification(window, error, BackendCode.TERMINATED); return; } const exe = files.find(file => file.startsWith('rotkehlchen-')); if (!exe) { this.logAndQuit(`ERROR: Executable was not found`); return; } this.executable = exe; const executable = path.join(distDir, exe); if (this._corsURL) { args.push('--api-cors', this._corsURL); } args.push('--logfile', this.backendLogFile); args = [ '--rest-api-port', port.toString(), '--websockets-api-port', websocketPort.toString() ].concat(args); this.logToFile( `Starting packaged python subprocess: ${executable} ${args.join(' ')}` ); this.childProcess = spawn(executable, args); } private async terminateWindowsProcesses(restart: boolean) { // For win32 we got two problems: // 1. pyProc.kill() does not work due to SIGTERM not really being a signal // in Windows // 2. the onefile pyinstaller packaging creates two executables. // https://github.com/pyinstaller/pyinstaller/issues/2483 // // So the solution is to not let the application close, get all // pids and kill them before we close the app this.logToFile('Starting windows process termination'); const executable = this.executable; if (!executable) { this.logToFile('No python sub-process executable detected'); return; } const tasks: Task[] = await tasklist(); this.logToFile(`Currently running: ${tasks.length} tasks`); const pids = tasks .filter(task => task.imageName === executable) .map(task => task.pid); this.logToFile( `Detected the following running python sub-processes: ${pids.join(', ')}` ); const args = ['/f', '/t']; for (let i = 0; i < pids.length; i++) { args.push('/PID'); args.push(pids[i].toString()); } this.logToFile( `Preparing to call "taskill ${args.join( ' ' )}" on the python sub-processes` ); const taskKill = spawn('taskkill', args); return new Promise<void>(resolve => { taskKill.on('exit', () => { this.logToFile('Call to taskkill exited'); if (!restart) { app.exit(); } this.waitForTermination(tasks, pids).then(resolve); }); taskKill.on('error', err => { this.logToFile(`Call to taskkill failed:\n\n ${err}`); if (!restart) { app.exit(); } resolve(); }); setTimeout(() => resolve, 15000); }); } private async waitForTermination(tasks: Task[], processes: number[]) { function stillRunning() { return tasks.filter(({ pid }) => processes.includes(pid)).length; } let running = stillRunning(); if (running === 0) { return; } for (let i = 0; i < 10; i++) { this.logToFile( `The ${running} processes are still running. Waiting for 2 seconds` ); await wait(2000); running = stillRunning(); if (stillRunning.length === 0) { break; } } } }
the_stack
import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; import { ParserOptions } from "@babel/parser"; export { ParserOptions, GeneratorOptions, t as types, template, traverse, NodePath, Visitor }; export type Node = t.Node; export type ParseResult = t.File | t.Program; export const version: string; export const DEFAULT_EXTENSIONS: ['.js', '.jsx', '.es6', '.es', '.mjs']; export interface TransformOptions { /** * Include the AST in the returned object * * Default: `false` */ ast?: boolean | null; /** * Attach a comment after all non-user injected code * * Default: `null` */ auxiliaryCommentAfter?: string | null; /** * Attach a comment before all non-user injected code * * Default: `null` */ auxiliaryCommentBefore?: string | null; /** * Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of. * * Default: `"."` */ root?: string | null; /** * This option, combined with the "root" value, defines how Babel chooses its project root. * The different modes define different ways that Babel can process the "root" value to get * the final project root. * * @see https://babeljs.io/docs/en/next/options#rootmode */ rootMode?: 'root' | 'upward' | 'upward-optional'; /** * The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files. * * Default: `undefined` */ configFile?: string | boolean | null; /** * Specify whether or not to use .babelrc and * .babelignore files. * * Default: `true` */ babelrc?: boolean | null; /** * Specify which packages should be search for .babelrc files when they are being compiled. `true` to always search, or a path string or an array of paths to packages to search * inside of. Defaults to only searching the "root" package. * * Default: `(root)` */ babelrcRoots?: boolean | MatchPattern | MatchPattern[] | null; /** * Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"` * * Default: env vars */ envName?: string; /** * If any of patterns match, the current configuration object is considered inactive and is ignored during config processing. */ exclude?: MatchPattern | MatchPattern[]; /** * Enable code generation * * Default: `true` */ code?: boolean | null; /** * Output comments in generated output * * Default: `true` */ comments?: boolean | null; /** * Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB * * Default: `"auto"` */ compact?: boolean | "auto" | null; /** * The working directory that Babel's programmatic options are loaded relative to. * * Default: `"."` */ cwd?: string | null; /** * Utilities may pass a caller object to identify themselves to Babel and * pass capability-related flags for use by configs, presets and plugins. * * @see https://babeljs.io/docs/en/next/options#caller */ caller?: TransformCaller; /** * This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }` * which will use those options when the `envName` is `production` * * Default: `{}` */ env?: { [index: string]: TransformOptions | null | undefined; } | null; /** * A path to a `.babelrc` file to extend * * Default: `null` */ extends?: string | null; /** * Filename for use in errors etc * * Default: `"unknown"` */ filename?: string | null; /** * Filename relative to `sourceRoot` * * Default: `(filename)` */ filenameRelative?: string | null; /** * An object containing the options to be passed down to the babel code generator, @babel/generator * * Default: `{}` */ generatorOpts?: GeneratorOptions | null; /** * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used * * Default: `null` */ getModuleId?: ((moduleName: string) => string | null | undefined) | null; /** * ANSI highlight syntax error code frames * * Default: `true` */ highlightCode?: boolean | null; /** * Opposite to the `only` option. `ignore` is disregarded if `only` is specified * * Default: `null` */ ignore?: MatchPattern[] | null; /** * This option is a synonym for "test" */ include?: MatchPattern | MatchPattern[]; /** * A source map object that the output source map will be based on * * Default: `null` */ inputSourceMap?: object | null; /** * Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) * * Default: `false` */ minified?: boolean | null; /** * Specify a custom name for module ids * * Default: `null` */ moduleId?: string | null; /** * If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) * * Default: `false` */ moduleIds?: boolean | null; /** * Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions * * Default: `(sourceRoot)` */ moduleRoot?: string | null; /** * A glob, regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile * a non-matching file it's returned verbatim * * Default: `null` */ only?: MatchPattern[] | null; /** * Allows users to provide an array of options that will be merged into the current configuration one at a time. * This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply */ overrides?: TransformOptions[]; /** * An object containing the options to be passed down to the babel parser, @babel/parser * * Default: `{}` */ parserOpts?: ParserOptions | null; /** * List of plugins to load and use * * Default: `[]` */ plugins?: PluginItem[] | null; /** * List of presets (a set of plugins) to load and use * * Default: `[]` */ presets?: PluginItem[] | null; /** * Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE**: This will not retain the columns) * * Default: `false` */ retainLines?: boolean | null; /** * An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comment` option when used * * Default: `null` */ shouldPrintComment?: ((commentContents: string) => boolean) | null; /** * Set `sources[0]` on returned source map * * Default: `(filenameRelative)` */ sourceFileName?: string | null; /** * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` * then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** * * Default: `false` */ sourceMaps?: boolean | "inline" | "both" | null; /** * The root from which all sources are relative * * Default: `(moduleRoot)` */ sourceRoot?: string | null; /** * Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to guess, based on the presence of ES6 * `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`. * * Default: `("module")` */ sourceType?: "script" | "module" | "unambiguous" | null; /** * If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing. */ test?: MatchPattern | MatchPattern[]; /** * An optional callback that can be used to wrap visitor methods. **NOTE**: This is useful for things like introspection, and not really needed for implementing anything. Called as * `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`. */ wrapPluginVisitorMethod?: ((pluginAlias: string, visitorType: "enter" | "exit", callback: (path: NodePath, state: any) => void) => (path: NodePath, state: any) => void) | null; } export interface TransformCaller { // the only required property name: string; // e.g. set to true by `babel-loader` and false by `babel-jest` supportsStaticESM?: boolean; supportsDynamicImport?: boolean; // augment this with a "declare module '@babel/core' { ... }" if you need more keys } export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any; export interface MatchPatternContext { envName: string; dirname: string; caller: TransformCaller | undefined; } export type MatchPattern = string | RegExp | ((filename: string | undefined, context: MatchPatternContext) => boolean); /** * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST. */ export function transform(code: string, callback: FileResultCallback): void; /** * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST. */ export function transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback): void; /** * Here for backward-compatibility. Ideally use `transformSync` if you want a synchronous API. */ export function transform(code: string, opts?: TransformOptions): BabelFileResult | null; /** * Transforms the passed in code. Returning an object with the generated code, source map, and AST. */ export function transformSync(code: string, opts?: TransformOptions): BabelFileResult | null; /** * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST. */ export function transformAsync(code: string, opts?: TransformOptions): Promise<BabelFileResult | null>; /** * Asynchronously transforms the entire contents of a file. */ export function transformFile(filename: string, callback: FileResultCallback): void; /** * Asynchronously transforms the entire contents of a file. */ export function transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback): void; /** * Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`. */ export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult | null; /** * Asynchronously transforms the entire contents of a file. */ export function transformFileAsync(filename: string, opts?: TransformOptions): Promise<BabelFileResult | null>; /** * Given an AST, transform it. */ export function transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback): void; /** * Given an AST, transform it. */ export function transformFromAst(ast: Node, code: string | undefined, opts: TransformOptions | undefined, callback: FileResultCallback): void; /** * Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API. */ export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult | null; /** * Given an AST, transform it. */ export function transformFromAstAsync(ast: Node, code?: string, opts?: TransformOptions): Promise<BabelFileResult | null>; // A babel plugin is a simple function which must return an object matching // the following interface. Babel will throw if it finds unknown properties. // The list of allowed plugin keys is here: // https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71 export interface PluginObj<S = {}> { name?: string; manipulateOptions?(opts: any, parserOpts: any): void; pre?(this: S, state: any): void; visitor: Visitor<S>; post?(this: S, state: any): void; inherits?: any; } export interface BabelFileResult { ast?: t.File | null; code?: string | null; ignored?: boolean; map?: { version: number; sources: string[]; names: string[]; sourceRoot?: string; sourcesContent?: string[]; mappings: string; file: string; } | null; metadata?: BabelFileMetadata; } export interface BabelFileMetadata { usedHelpers: string[]; marked: Array<{ type: string; message: string; loc: object; }>; modules: BabelFileModulesMetadata; } export interface BabelFileModulesMetadata { imports: object[]; exports: { exported: object[]; specifiers: object[]; }; } export type FileParseCallback = (err: Error | null, result: ParseResult | null) => any; /** * Given some code, parse it using Babel's standard behavior. * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. */ export function parse(code: string, callback: FileParseCallback): void; /** * Given some code, parse it using Babel's standard behavior. * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. */ export function parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback): void; /** * Given some code, parse it using Babel's standard behavior. * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. */ export function parse(code: string, options?: TransformOptions): ParseResult | null; /** * Given some code, parse it using Babel's standard behavior. * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. */ export function parseSync(code: string, options?: TransformOptions): ParseResult | null; /** * Given some code, parse it using Babel's standard behavior. * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. */ export function parseAsync(code: string, options?: TransformOptions): Promise<ParseResult | null>; /** * Resolve Babel's options fully, resulting in an options object where: * * * opts.plugins is a full list of Plugin instances. * * opts.presets is empty and all presets are flattened into opts. * * It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel * will not make a second attempt to load config files. * * Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to * use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to * invalidate properly, but it is the best we have at the moment. */ export function loadOptions(options?: TransformOptions): object | null; /** * To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and * presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it * as then see fit and pass it back to Babel again. * * * `babelrc: string | void` - The path of the `.babelrc` file, if there was one. * * `babelignore: string | void` - The path of the `.babelignore` file, if there was one. * * `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back * to Babel again. * * `plugins: Array<ConfigItem>` - See below. * * `presets: Array<ConfigItem>` - See below. * * It can be safely passed back to Babel. Fields like `babelrc` have been set to false so that later calls to * Babel will not make a second attempt to load config files. * * `ConfigItem` instances expose properties to introspect the values, but each item should be treated as * immutable. If changes are desired, the item should be removed from the list and replaced with either a normal * Babel config value, or with a replacement item created by `babel.createConfigItem`. See that function for * information about `ConfigItem` fields. */ export function loadPartialConfig(options?: TransformOptions): Readonly<PartialConfig> | null; export interface PartialConfig { options: TransformOptions; babelrc?: string; babelignore?: string; config?: string; } export interface ConfigItem { /** * The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]` */ name?: string; /** * The resolved value of the plugin. */ value: object | ((...args: any[]) => any); /** * The options object passed to the plugin. */ options?: object | false; /** * The path that the options are relative to. */ dirname: string; /** * Information about the plugin's file, if Babel knows it. * * */ file?: { /** * The file that the user requested, e.g. `"@babel/env"` */ request: string; /** * The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"` */ resolved: string; } | null; } export type PluginOptions = object | undefined | false; export type PluginTarget = string | object | ((...args: any[]) => any); export type PluginItem = ConfigItem | PluginObj<any> | PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined]; export function resolvePlugin(name: string, dirname: string): string | null; export function resolvePreset(name: string, dirname: string): string | null; export interface CreateConfigItemOptions { dirname?: string; type?: "preset" | "plugin"; } /** * Allows build tooling to create and cache config items up front. If this function is called multiple times for a * given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected * plugins and presets to inject, pre-constructing the config items would be recommended. */ export function createConfigItem(value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined], options?: CreateConfigItemOptions): ConfigItem; // NOTE: the documentation says the ConfigAPI also exposes @babel/core's exports, but it actually doesn't /** * @see https://babeljs.io/docs/en/next/config-files#config-function-api */ export interface ConfigAPI { /** * The version string for the Babel version that is loading the config file. * * @see https://babeljs.io/docs/en/next/config-files#apiversion */ version: string; /** * @see https://babeljs.io/docs/en/next/config-files#apicache */ cache: SimpleCacheConfigurator; /** * @see https://babeljs.io/docs/en/next/config-files#apienv */ env: EnvFunction; // undocumented; currently hardcoded to return 'false' // async(): boolean /** * This API is used as a way to access the `caller` data that has been passed to Babel. * Since many instances of Babel may be running in the same process with different `caller` values, * this API is designed to automatically configure `api.cache`, the same way `api.env()` does. * * The `caller` value is available as the first parameter of the callback function. * It is best used with something like this to toggle configuration behavior * based on a specific environment: * * @example * function isBabelRegister(caller?: { name: string }) { * return !!(caller && caller.name === "@babel/register") * } * api.caller(isBabelRegister) * * @see https://babeljs.io/docs/en/next/config-files#apicallercb */ caller<T extends SimpleCacheKey>(callerCallback: (caller: TransformOptions['caller']) => T): T; /** * While `api.version` can be useful in general, it's sometimes nice to just declare your version. * This API exposes a simple way to do that with: * * @example * api.assertVersion(7) // major version only * api.assertVersion("^7.2") * * @see https://babeljs.io/docs/en/next/config-files#apiassertversionrange */ assertVersion(versionRange: number | string): boolean; // NOTE: this is an undocumented reexport from "@babel/parser" but it's missing from its types // tokTypes: typeof tokTypes } /** * JS configs are great because they can compute a config on the fly, * but the downside there is that it makes caching harder. * Babel wants to avoid re-executing the config function every time a file is compiled, * because then it would also need to re-execute any plugin and preset functions * referenced in that config. * * To avoid this, Babel expects users of config functions to tell it how to manage caching * within a config file. * * @see https://babeljs.io/docs/en/next/config-files#apicache */ export interface SimpleCacheConfigurator { // there is an undocumented call signature that is a shorthand for forever()/never()/using(). // (ever: boolean): void // <T extends SimpleCacheKey>(callback: CacheCallback<T>): T /** * Permacache the computed config and never call the function again. */ forever(): void; /** * Do not cache this config, and re-execute the function every time. */ never(): void; /** * Any time the using callback returns a value other than the one that was expected, * the overall config function will be called again and a new entry will be added to the cache. * * @example * api.cache.using(() => process.env.NODE_ENV) */ using<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T; /** * Any time the using callback returns a value other than the one that was expected, * the overall config function will be called again and all entries in the cache will * be replaced with the result. * * @example * api.cache.invalidate(() => process.env.NODE_ENV) */ invalidate<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T; } // https://github.com/babel/babel/blob/v7.3.3/packages/babel-core/src/config/caching.js#L231 export type SimpleCacheKey = string | boolean | number | null | undefined; export type SimpleCacheCallback<T extends SimpleCacheKey> = () => T; /** * Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function * meant specifically for that. This API is used as a quick way to check the `"envName"` that Babel * was loaded with, which takes `NODE_ENV` into account if no other overriding environment is set. * * @see https://babeljs.io/docs/en/next/config-files#apienv */ export interface EnvFunction { /** * @returns the current `envName` string */ (): string; /** * @returns `true` if the `envName` is `===` any of the given strings */ (envName: string | ReadonlyArray<string>): boolean; // the official documentation is misleading for this one... // this just passes the callback to `cache.using` but with an additional argument. // it returns its result instead of necessarily returning a boolean. <T extends SimpleCacheKey>(envCallback: (envName: NonNullable<TransformOptions['envName']>) => T): T; } export type ConfigFunction = (api: ConfigAPI) => TransformOptions; export as namespace babel;
the_stack
import { TokenReader, IRenderSettings, defaultRenderSettings } from "../helpers"; import { CSSToken, stringToTokens } from "./css"; import { CSSValue, parseValue, renderValue } from "./value"; /* CSS Selectors: */ interface IFullSelector { tagName: string, classes: string[], id: string, child: ISelector, // e.g. div > h1 descendant: ISelector, // e.g. div h1 generalSibling: ISelector, adjacent: ISelector, pseudoClasses: Array<{ name: string, args?: CSSValue | Array<ISelector> }>, pseudoElements: Array<{ name: string, args?: CSSValue }> attributes: Array<{ attribute: string, matcher: AttributeMatcher value?: string, }> } export type ISelector = Partial<IFullSelector>; export enum AttributeMatcher { KeyExists, ExactEqual, SomeWord, BeginsWith, Prefixed, Suffixed, Occurrence } const tokenToAttributeMatcher: Map<CSSToken, AttributeMatcher> = new Map([ [CSSToken.Equal, AttributeMatcher.ExactEqual], [CSSToken.SomeWordEqual, AttributeMatcher.SomeWord], [CSSToken.BeginsWithEqual, AttributeMatcher.BeginsWith], [CSSToken.PrefixedEqual, AttributeMatcher.Prefixed], [CSSToken.SuffixedEqual, AttributeMatcher.Suffixed], [CSSToken.OccurrenceEqual, AttributeMatcher.Occurrence] ]); export function parseSelectorsFromTokens(reader: TokenReader<CSSToken>): Array<ISelector> { const selectors: Array<ISelector> = [] while (reader.current) { selectors.push(parseSelectorFromTokens(reader)); if (reader.current.type !== CSSToken.Comma) break; else reader.expectNext(CSSToken.Comma); } return selectors; } // These tokens can appear around the selector. Whitespace in front of these tokens does not mean to go down parsing them as descendants const specialNonSpecificPositionalSelector = [CSSToken.OpenCurly, CSSToken.Child, CSSToken.Plus]; /** * Parses a SINGLE selector from tokens * @param reader * @param fromDescendant temp fix for descendants */ export function parseSelectorFromTokens(reader: TokenReader<CSSToken>): ISelector { if (reader.current.type as CSSToken === CSSToken.OpenCurly) { reader.throwExpect("Expected selector"); } // TODO "*" and "&" be handled differently. let selector: ISelector = {}; if (reader.current.type === CSSToken.Identifier) { selector.tagName = reader.current.value; reader.move(); } else if (reader.current.type === CSSToken.Star) { selector.tagName = "*"; reader.move(); } else if (reader.current.type === CSSToken.And) { selector.tagName = "&"; reader.move(); } while (![CSSToken.OpenCurly, CSSToken.CloseBracket, CSSToken.Comma].includes(reader.current.type)) { /* Deals with descendants by testing whether the token is not immediate. CSS has a annoying design where whitespace has an effect. e.g "h1.title" is different to "h1 .title" */ if ( reader.peek(-1) && Object.keys(selector).length > 0 && !specialNonSpecificPositionalSelector.includes(reader.current.type) && !specialNonSpecificPositionalSelector.includes(reader.peek(-1)!.type) && reader.peek(-1)?.line === reader.current.line && reader.current.column !== reader.peek(-1)!.column + (reader.peek(-1)?.value?.length ?? 1) ) { selector.descendant = parseSelectorFromTokens(reader); continue; } switch (reader.current.type) { case CSSToken.Hash: if (selector.id) reader.throwError("CSS selector can only contain one id matcher"); reader.move(); selector.id = reader.current.value; reader.expectNext(CSSToken.Identifier); break; case CSSToken.Dot: reader.move(); if (!selector.classes) selector.classes = []; selector.classes.push(reader.current.value!); reader.expectNext(CSSToken.Identifier); break; case CSSToken.Colon: reader.move(); if (!selector.pseudoClasses) selector.pseudoClasses = []; const pseudoClassName = reader.current.value!; reader.move(); if (reader.current.type as CSSToken === CSSToken.OpenBracket) { reader.move(); let args: CSSValue | Array<ISelector>; if (["is", "not"].includes(pseudoClassName)) { args = parseSelectorsFromTokens(reader); } else { args = parseValue(reader); // TODO parse selector for :is() and :has() ?? } reader.expectNext(CSSToken.CloseBracket); selector.pseudoClasses.push({ name: pseudoClassName, args }); } else { selector.pseudoClasses.push({ name: pseudoClassName }); } break; case CSSToken.DoubleColon: reader.move(); if (!selector.pseudoElements) selector.pseudoElements = []; const pseudoElementName = reader.current.value!; reader.move(); selector.pseudoElements.push({ name: pseudoElementName }); break; case CSSToken.OpenSquare: reader.move(); const attribute = reader.current.value!; reader.expectNext(CSSToken.Identifier); let matcher: AttributeMatcher = AttributeMatcher.KeyExists; let value: string | undefined; if (tokenToAttributeMatcher.has(reader.current.type)) { matcher = tokenToAttributeMatcher.get(reader.current.type)!; reader.move(); value = reader.current.value; reader.expectNext(CSSToken.StringLiteral); } selector.attributes = [{ attribute, matcher, value }]; reader.expectNext(CSSToken.CloseSquare); break; case CSSToken.Child: reader.move(); selector.child = parseSelectorFromTokens(reader); break; case CSSToken.Plus: reader.move(); selector.adjacent = parseSelectorFromTokens(reader); break; default: reader.throwExpect("Expected selector"); } } return selector; } /** * Returns single `ISelector` from a string * @param selector */ export function parseSelectorFromString(selector: string): ISelector { const reader = stringToTokens(selector); const selector_ = parseSelectorFromTokens(reader); reader.expect(CSSToken.EOF); return selector_; } /** * Renders a `ISelector` * @param selector * @param settings */ export function renderSelector(selector: ISelector, settings: IRenderSettings = defaultRenderSettings): string { let acc = ""; if (selector.tagName) { acc += selector.tagName; } if (selector.id) { acc += `#${selector.id}`; } if (selector.classes) { for (const cssClass of selector.classes) { acc += `.${cssClass}`; } } if (selector.pseudoClasses) { for (const pseudoClass of selector.pseudoClasses) { acc += `:${pseudoClass.name}`; if (pseudoClass.args) { acc += "("; // If array is an array of selectors if (["is", "not"].includes(pseudoClass.name)) { for (let i = 0; i < pseudoClass.args.length; i++) { acc += renderSelector(pseudoClass.args[i] as ISelector, settings); if (i + 1 < pseudoClass.args.length) acc += settings.minify ? "," : ", "; } } else { acc += renderValue(pseudoClass.args as CSSValue, settings) } acc += ")"; } } } if (selector.pseudoElements) { for (const pseudoElement of selector.pseudoElements) { acc += `::${pseudoElement.name}`; } } if (selector.attributes) { for (const { attribute, matcher, value } of selector.attributes) { acc += "["; acc += attribute; switch (matcher) { case AttributeMatcher.ExactEqual: acc += `="${value!}"`; break; case AttributeMatcher.SomeWord: acc += `~="${value!}"`; break; case AttributeMatcher.BeginsWith: acc += `|="${value!}"`; break; case AttributeMatcher.Prefixed: acc += `^="${value!}"`; break; case AttributeMatcher.Suffixed: acc += `$="${value!}"`; break; case AttributeMatcher.Occurrence: acc += `*="${value!}"`; break; } acc += "]"; } } if (selector.child) { acc += settings.minify ? ">" : " > "; acc += renderSelector(selector.child, settings); } else if (selector.descendant) { acc += " "; acc += renderSelector(selector.descendant, settings); } else if (selector.adjacent) { acc += settings.minify ? "+" : " + "; acc += renderSelector(selector.adjacent, settings); } return acc; } const childSelectorProperties: Array<keyof ISelector> = ["descendant", "child"]; /** * `selector` becomes the rightmost descendant of `parentSelector` * Handles cloning of parent selector to prevent mutation * @param selector the selector to rightmost * @param parentSelector the selector to place `selector` under */ export function prefixSelector(selector: ISelector, parentSelector: ISelector): ISelector { // Don't prefix :root if (selector.pseudoClasses?.length === 1 && selector.pseudoClasses[0].name === "root") { return selector; } // Allows for &, :non-scoped .user if (selector.pseudoClasses?.length === 1 && selector.pseudoClasses[0].name === "non-scoped") { return selector.descendant!; } let modifier: ISelector = { ...parentSelector }; let hook: ISelector = modifier; let aspect = Object .keys(hook) .filter(prop => childSelectorProperties.includes(prop as keyof ISelector))?.[0]; // Find the bottom most descendant while (aspect) { // Clone the descendant to prevent override Reflect.set(hook, aspect, { ...Reflect.get(hook, aspect) }); // Set hook to descendant hook = Reflect.get(hook, aspect); aspect = Object .keys(hook) .filter(prop => childSelectorProperties.includes(prop as keyof ISelector))?.[0]; } if (selector.tagName === "&") { // TODO concat selector.classes and parentSelector.classes and other stuff like that Object.assign(hook, { ...selector, tagName: hook.tagName }) } else { hook.descendant = selector; } return modifier; }
the_stack
import React, { PureComponent } from 'react' import styled, { css } from 'react-emotion' import Dialog from './dialog' import { DefaultButton, GreenButton } from './buttons' import { Destination, CustomCategories, CategoryPreferences, PreferenceDialogTemplate } from '../types' const hideOnMobile = css` @media (max-width: 600px) { display: none; } ` const TableScroll = styled('div')` overflow-x: auto; margin-top: 16px; ` const Table = styled('table')` border-collapse: collapse; font-size: 12px; ` const ColumnHeading = styled('th')` background: #f7f8fa; color: #1f4160; font-weight: 600; text-align: left; border-width: 2px; ` const RowHeading = styled('th')` font-weight: normal; text-align: left; ` const Row = styled('tr')` th, td { vertical-align: top; padding: 8px 12px; border: 1px solid rgba(67, 90, 111, 0.114); } td { border-top: none; } ` const InputCell = styled('td')` input { vertical-align: middle; } label { display: block; margin-bottom: 4px; white-space: nowrap; } ` interface PreferenceDialogProps { innerRef: (element: HTMLElement | null) => void onCancel: () => void onSave: () => void onChange: (name: string, value: boolean) => void marketingDestinations: Destination[] advertisingDestinations: Destination[] functionalDestinations: Destination[] marketingAndAnalytics?: boolean | null advertising?: boolean | null functional?: boolean | null customCategories?: CustomCategories destinations: Destination[] preferences: CategoryPreferences title: React.ReactNode content: React.ReactNode preferencesDialogTemplate?: PreferenceDialogTemplate } export default class PreferenceDialog extends PureComponent<PreferenceDialogProps, {}> { static displayName = 'PreferenceDialog' static defaultProps = { marketingAndAnalytics: null, advertising: null, functional: null } render() { const { innerRef, onCancel, marketingDestinations, advertisingDestinations, functionalDestinations, marketingAndAnalytics, advertising, functional, customCategories, destinations, title, content, preferences, preferencesDialogTemplate } = this.props const { headings, checkboxes, actionButtons } = preferencesDialogTemplate! const functionalInfo = preferencesDialogTemplate?.categories!.find(c => c.key === 'functional') const marketingInfo = preferencesDialogTemplate?.categories!.find(c => c.key === 'marketing') const advertisingInfo = preferencesDialogTemplate?.categories!.find( c => c.key === 'advertising' ) const essentialInfo = preferencesDialogTemplate?.categories!.find(c => c.key === 'essential') const buttons = ( <div> <DefaultButton type="button" onClick={onCancel}> {actionButtons!.cancelValue} </DefaultButton> <GreenButton type="submit">{actionButtons!.saveValue}</GreenButton> </div> ) return ( <Dialog innerRef={innerRef} title={title} buttons={buttons} onCancel={onCancel} onSubmit={this.handleSubmit} > {content} <TableScroll> <Table> <thead> <Row> <ColumnHeading scope="col">{headings!.allowValue}</ColumnHeading> <ColumnHeading scope="col">{headings!.categoryValue}</ColumnHeading> <ColumnHeading scope="col">{headings!.purposeValue}</ColumnHeading> <ColumnHeading scope="col" className={hideOnMobile}> {headings!.toolsValue} </ColumnHeading> </Row> </thead> <tbody> {!customCategories && ( <> <Row> <InputCell> <label> <input type="radio" name="functional" value="true" checked={functional === true} onChange={this.handleChange} aria-label="Allow functional tracking" required />{' '} {checkboxes!.yesValue} </label> <label> <input type="radio" name="functional" value="false" checked={functional === false} onChange={this.handleChange} aria-label="Disallow functional tracking" required />{' '} {checkboxes!.noValue} </label> </InputCell> <RowHeading scope="row">{functionalInfo?.name}</RowHeading> <td> <p>{functionalInfo?.description}</p> <p className={hideOnMobile}>{functionalInfo?.example}</p> </td> <td className={hideOnMobile}> {functionalDestinations.map(d => d.name).join(', ')} </td> </Row> <Row> <InputCell> <label> <input type="radio" name="marketingAndAnalytics" value="true" checked={marketingAndAnalytics === true} onChange={this.handleChange} aria-label="Allow marketing and analytics tracking" required />{' '} {checkboxes!.yesValue} </label> <label> <input type="radio" name="marketingAndAnalytics" value="false" checked={marketingAndAnalytics === false} onChange={this.handleChange} aria-label="Disallow marketing and analytics tracking" required />{' '} {checkboxes!.noValue} </label> </InputCell> <RowHeading scope="row">{marketingInfo?.name}</RowHeading> <td> <p>{marketingInfo?.description}</p> <p className={hideOnMobile}>{marketingInfo?.example}</p> </td> <td className={hideOnMobile}> {marketingDestinations.map(d => d.name).join(', ')} </td> </Row> <Row> <InputCell> <label> <input type="radio" name="advertising" value="true" checked={advertising === true} onChange={this.handleChange} aria-label="Allow advertising tracking" required />{' '} {checkboxes!.yesValue} </label> <label> <input type="radio" name="advertising" value="false" checked={advertising === false} onChange={this.handleChange} aria-label="Disallow advertising tracking" required />{' '} {checkboxes!.noValue} </label> </InputCell> <RowHeading scope="row">{advertisingInfo?.name}</RowHeading> <td> <p>{advertisingInfo?.description}</p> <p className={hideOnMobile}>{advertisingInfo?.example}</p> </td> <td className={hideOnMobile}> {advertisingDestinations.map(d => d.name).join(', ')} </td> </Row> </> )} {customCategories && Object.entries(customCategories).map( ([categoryName, { integrations, purpose }]) => ( <Row key={categoryName}> <InputCell> <label> <input type="radio" name={categoryName} value="true" checked={preferences[categoryName] === true} onChange={this.handleChange} aria-label={`Allow "${categoryName}" tracking`} required />{' '} {checkboxes!.yesValue} </label> <label> <input type="radio" name={categoryName} value="false" checked={preferences[categoryName] === false} onChange={this.handleChange} aria-label={`Disallow "${categoryName}" tracking`} required />{' '} {checkboxes!.noValue} </label> </InputCell> <RowHeading scope="row">{categoryName}</RowHeading> <td> <p>{purpose}</p> </td> <td className={hideOnMobile}> {destinations .filter(d => integrations.includes(d.id)) .map(d => d.name) .join(', ')} </td> </Row> ) )} <Row> <td>N/A</td> <RowHeading scope="row">{essentialInfo?.name}</RowHeading> <td> <p>{essentialInfo?.description}</p> <p>{essentialInfo?.example}</p> </td> <td className={hideOnMobile} /> </Row> </tbody> </Table> </TableScroll> </Dialog> ) } handleChange = e => { const { onChange } = this.props onChange(e.target.name, e.target.value === 'true') } handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { const { onSave, preferences, marketingAndAnalytics, advertising, functional, customCategories } = this.props e.preventDefault() // Safe guard against browsers that don't prevent the // submission of invalid forms (Safari < 10.1) if ( !customCategories && (marketingAndAnalytics === null || advertising === null || functional === null) ) { return } // Safe guard against custom categories being null if ( customCategories && Object.keys(customCategories).some(category => preferences[category] === null) ) { return } onSave() } }
the_stack
import { PLAYER, PLAYER_STATS_TABLES, RATINGS, PLAYER_SUMMARY, isSport, DEFAULT_JERSEY, } from "../../common"; import { player } from "../core"; import { idb } from "../db"; import { face, formatEventText, g, getTeamColors, getTeamInfoBySeason, helpers, processPlayersHallOfFame, random, } from "../util"; import type { MenuItemHeader, MenuItemLink, MinimalPlayerRatings, Player, UpdateEvents, ViewInput, } from "../../common/types"; import orderBy from "lodash-es/orderBy"; import findLast from "lodash-es/findLast"; const fixRatingsStatsAbbrevs = async (p: { ratings?: { abbrev: string; season: number; tid?: number; }[]; stats?: { abbrev: string; season: number; tid?: number; }[]; }) => { const keys = ["ratings", "stats"] as const; for (const key of keys) { const rows = p[key]; if (rows) { for (const row of rows) { if (row.tid !== undefined) { const info = await getTeamInfoBySeason(row.tid, row.season); if (info) { row.abbrev = info.abbrev; } } } } } }; export const getCommon = async (pid?: number, season?: number) => { if (pid === undefined) { // https://stackoverflow.com/a/59923262/786644 const returnValue = { type: "error" as const, errorMessage: "Player not found.", }; return returnValue; } const statSummary = Object.values(PLAYER_SUMMARY); const statTables = Object.values(PLAYER_STATS_TABLES); let stats = Array.from( new Set( statTables.reduce<string[]>((allStats, currentStats) => { return allStats.concat(currentStats.stats); }, []), ), ); // Needed because shot locations tables are "special" for now, unfortunately if (isSport("basketball")) { stats = stats.concat([ "fgAtRim", "fgaAtRim", "fgpAtRim", "fgLowPost", "fgaLowPost", "fgpLowPost", "fgMidRange", "fgaMidRange", "fgpMidRange", "tp", "tpa", "tpp", ]); } const pRaw = await idb.getCopy.players( { pid, }, "noCopyCache", ); if (!pRaw) { // https://stackoverflow.com/a/59923262/786644 const returnValue = { type: "error" as const, errorMessage: "Player not found.", }; return returnValue; } await face.upgrade(pRaw); type Stats = { season: number; tid: number; abbrev: string; age: number; playoffs: boolean; jerseyNumber: string; } & Record<string, number>; const p: | (Pick< Player, | "pid" | "tid" | "hgt" | "weight" | "born" | "contract" | "diedYear" | "face" | "imgURL" | "injury" | "injuries" | "college" | "relatives" | "awards" > & { age: number; ageAtDeath: number | null; draft: Player["draft"] & { age: number; abbrev: string; originalAbbrev: string; }; name: string; abbrev: string; mood: any; salaries: any[]; salariesTotal: any; untradable: any; untradableMsg?: string; ratings: (MinimalPlayerRatings & { abbrev: string; age: number; tid: number; })[]; stats: Stats[]; careerStats: Stats; careerStatsPlayoffs: Stats; jerseyNumber?: string; experience: number; note?: string; watch: boolean; }) | undefined = await idb.getCopy.playersPlus(pRaw, { attrs: [ "pid", "name", "tid", "abbrev", "age", "ageAtDeath", "hgt", "weight", "born", "diedYear", "contract", "draft", "face", "mood", "injury", "injuries", "salaries", "salariesTotal", "awards", "imgURL", "watch", "college", "relatives", "untradable", "jerseyNumber", "experience", "note", ], ratings: [ "season", "abbrev", "tid", "age", "ovr", "pot", ...RATINGS, "skills", "pos", "injuryIndex", ], stats: ["season", "tid", "abbrev", "age", "jerseyNumber", ...stats], playoffs: true, showRookies: true, fuzz: true, }); if (!p) { // https://stackoverflow.com/a/59923262/786644 const returnValue = { type: "error" as const, errorMessage: "Player not found.", }; return returnValue; } await fixRatingsStatsAbbrevs(p); // Filter out rows with no games played p.stats = p.stats.filter(row => row.gp > 0); const userTid = g.get("userTid"); if (p.tid !== PLAYER.RETIRED) { p.mood = await player.moodInfos(pRaw); // Account for extra free agent demands if (p.tid === PLAYER.FREE_AGENT) { p.contract.amount = p.mood.user.contractAmount / 1000; } } const willingToSign = !!(p.mood && p.mood.user && p.mood.user.willing); const retired = p.tid === PLAYER.RETIRED; let teamName = ""; if (p.tid >= 0) { teamName = `${g.get("teamInfoCache")[p.tid]?.region} ${ g.get("teamInfoCache")[p.tid]?.name }`; } else if (p.tid === PLAYER.FREE_AGENT) { teamName = "Free Agent"; } else if ( p.tid === PLAYER.UNDRAFTED || p.tid === PLAYER.UNDRAFTED_FANTASY_TEMP ) { teamName = "Draft Prospect"; } else if (p.tid === PLAYER.RETIRED) { teamName = "Retired"; } const teams = await idb.cache.teams.getAll(); const jerseyNumberInfos: { number: string; start: number; end: number; t?: { tid: number; colors: [string, string, string]; jersey?: string; name: string; region: string; }; retired: boolean; }[] = []; let prevKey: string = ""; for (const ps of p.stats) { const jerseyNumber = ps.jerseyNumber; if (jerseyNumber === undefined || ps.gp === 0) { continue; } const ts = await getTeamInfoBySeason(ps.tid, ps.season); let t; if (ts && ts.colors && ts.name !== undefined && ts.region !== undefined) { t = { tid: ps.tid, colors: ts.colors, jersey: ts.jersey, name: ts.name, region: ts.region, }; } // Don't include jersey in key, because it's not visible in the jersey number display const key = JSON.stringify([ jerseyNumber, t?.tid, t?.colors, t?.name, t?.region, ]); if (key === prevKey) { const prev = jerseyNumberInfos.at(-1); prev.end = ps.season; } else { let retired = false; const t2 = teams[ps.tid]; if (t2 && t2.retiredJerseyNumbers) { retired = t2.retiredJerseyNumbers.some( info => info.pid === pid && info.number === jerseyNumber, ); } jerseyNumberInfos.push({ number: jerseyNumber, start: ps.season, end: ps.season, t, retired, }); } prevKey = key; } let teamColors; let teamJersey; if (p.tid === PLAYER.RETIRED) { const { legacyTid } = processPlayersHallOfFame([p])[0]; // Randomly pick a season that he played on this team, and use that for colors const teamJerseyNumberInfos = jerseyNumberInfos.filter( info => info.t && info.t.tid === legacyTid, ); if (teamJerseyNumberInfos.length > 0) { const info = random.choice(teamJerseyNumberInfos); if (info.t) { teamColors = info.t.colors; teamJersey = info.t.jersey; } } } if (teamColors === undefined) { teamColors = await getTeamColors(p.tid); } if (teamJersey === undefined) { teamJersey = (await idb.cache.teams.get(p.tid))?.jersey ?? DEFAULT_JERSEY; } // Quick links to other players... let customMenu: MenuItemHeader | undefined; let customMenuInfo: | { title: string; players: Player[]; } | undefined; if (p.tid >= 0) { // ...on same team customMenuInfo = { title: "Roster", players: await idb.cache.players.indexGetAll("playersByTid", p.tid), }; } else if (p.tid === PLAYER.FREE_AGENT) { // ...also free agents customMenuInfo = { title: "Free Agents", players: await idb.cache.players.indexGetAll("playersByTid", p.tid), }; } else if (p.tid === PLAYER.UNDRAFTED) { // ...in same draft class customMenuInfo = { title: "Draft Class", players: ( await idb.cache.players.indexGetAll("playersByTid", p.tid) ).filter(p2 => p2.draft.year === p.draft.year), }; } if (customMenuInfo) { const children: MenuItemLink[] = orderBy( customMenuInfo.players, "value", "desc", ).map(p2 => { const ratings = p2.ratings.at(-1); const age = g.get("season") - p2.born.year; let description = `${age}yo`; if (!g.get("challengeNoRatings")) { const ovr = player.fuzzRating(ratings.ovr, ratings.fuzz); const pot = player.fuzzRating(ratings.pot, ratings.fuzz); description += `, ${ovr}/${pot}`; } return { type: "link", league: true, path: ["player", p2.pid], text: `${ratings.pos} ${p2.firstName} ${p2.lastName} (${description})`, }; }); customMenu = { type: "header", long: customMenuInfo.title, short: customMenuInfo.title, league: true, children, }; } let teamURL; if (p.tid >= 0) { teamURL = helpers.leagueUrl(["roster", `${p.abbrev}_${p.tid}`]); } else if (p.tid === PLAYER.FREE_AGENT) { teamURL = helpers.leagueUrl(["free_agents"]); } else if ( p.tid === PLAYER.UNDRAFTED || p.tid === PLAYER.UNDRAFTED_FANTASY_TEMP ) { teamURL = helpers.leagueUrl(["draft_scouting"]); } if (season !== undefined) { // Age/experience if (p.stats.length > 0) { const offset = season - g.get("season"); p.age = Math.max(0, p.age + offset); const offset2 = season - p.stats.at(-1).season; p.experience = Math.max(0, p.experience + offset2); // Jersey number const stats = findLast( p.stats, row => row.season === season && !row.playoffs, ); if (stats) { if (stats.jerseyNumber !== undefined) { p.jerseyNumber = stats.jerseyNumber; } const info = await getTeamInfoBySeason(stats.tid, stats.season); if (info) { teamName = `${info.region} ${info.name}`; teamColors = info.colors; teamJersey = info.jersey; } teamURL = helpers.leagueUrl([ "roster", `${stats.abbrev}_${stats.tid}`, season, ]); } } } return { type: "normal" as const, currentSeason: g.get("season"), customMenu, freeAgent: p.tid === PLAYER.FREE_AGENT, godMode: g.get("godMode"), injured: p.injury.gamesRemaining > 0, jerseyNumberInfos, phase: g.get("phase"), pid, // Needed for state.pid check player: p, retired, showContract: p.tid !== PLAYER.UNDRAFTED && p.tid !== PLAYER.UNDRAFTED_FANTASY_TEMP && p.tid !== PLAYER.RETIRED, showRatings: !g.get("challengeNoRatings") || retired, showTradeFor: p.tid !== userTid && p.tid >= 0, showTradingBlock: p.tid === userTid, spectator: g.get("spectator"), statSummary, statTables, teamColors, teamJersey, teamName, teamURL, willingToSign, }; }; const updatePlayer = async ( inputs: ViewInput<"player">, updateEvents: UpdateEvents, state: any, ) => { if ( updateEvents.includes("firstRun") || updateEvents.includes("playerMovement") || !state.retired || state.pid !== inputs.pid ) { const topStuff = await getCommon(inputs.pid); if (topStuff.type === "error") { // https://stackoverflow.com/a/59923262/786644 const returnValue = { errorMessage: topStuff.errorMessage, }; return returnValue; } const p = topStuff.player; const eventsAll = orderBy( [ ...(await idb.getCopies.events( { pid: topStuff.pid, }, "noCopyCache", )), ...(p.draft.dpid !== undefined ? await idb.getCopies.events( { dpid: p.draft.dpid, }, "noCopyCache", ) : []), ], "eid", "asc", ); const feats = eventsAll .filter(event => event.type === "playerFeat") .map(event => { return { eid: event.eid, season: event.season, text: helpers.correctLinkLid(g.get("lid"), event.text as any), }; }); const eventsFiltered = eventsAll.filter(event => { // undefined is a temporary workaround for bug from commit 999b9342d9a3dc0e8f337696e0e6e664e7b496a4 return !( event.type === "award" || event.type === "injured" || event.type === "healed" || event.type === "hallOfFame" || event.type === "playerFeat" || event.type === "tragedy" || event.type === undefined ); }); const events = []; for (const event of eventsFiltered) { events.push({ eid: event.eid, text: await formatEventText(event), season: event.season, }); } return { ...topStuff, events, feats, ratings: RATINGS, }; } }; export default updatePlayer;
the_stack
import { Injectable } from '@angular/core'; import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreWSExternalWarning } from '@services/ws'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; import { CoreUser } from '@features/user/services/user'; import { AddonMessages, AddonMessagesMarkMessageReadResult } from '@addons/messages/services/messages'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreLogger } from '@singletons/logger'; import { makeSingleton } from '@singletons'; const ROOT_CACHE_KEY = 'mmaNotifications:'; /** * Service to handle notifications. */ @Injectable({ providedIn: 'root' }) export class AddonNotificationsProvider { static readonly READ_CHANGED_EVENT = 'addon_notifications_read_changed_event'; static readonly READ_CRON_EVENT = 'addon_notifications_read_cron_event'; static readonly PUSH_SIMULATION_COMPONENT = 'AddonNotificationsPushSimulation'; static readonly LIST_LIMIT = 20; protected logger: CoreLogger; constructor() { this.logger = CoreLogger.getInstance('AddonNotificationsProvider'); } /** * Function to format notification data. * * @param notifications List of notifications. * @param read Whether the notifications are read or unread. * @return Promise resolved with notifications. */ protected async formatNotificationsData( notifications: AddonNotificationsGetMessagesMessage[], read?: boolean, ): Promise<AddonNotificationsGetMessagesMessageFormatted[]>; protected async formatNotificationsData( notifications: AddonNotificationsPopupNotification[], read?: boolean, ): Promise<AddonNotificationsPopupNotificationFormatted[]>; protected async formatNotificationsData( notifications: (AddonNotificationsGetMessagesMessage | AddonNotificationsPopupNotification)[], read?: boolean, ): Promise<AddonNotificationsAnyNotification[]> { const promises = notifications.map(async (notificationRaw) => { const notification = <AddonNotificationsAnyNotification> notificationRaw; // Set message to show. if (notification.component && notification.component == 'mod_forum') { notification.mobiletext = notification.smallmessage; } else { notification.mobiletext = notification.fullmessage; } notification.moodlecomponent = notification.component; notification.notification = 1; notification.notif = 1; if (typeof read != 'undefined') { notification.read = read; } if (typeof notification.customdata == 'string') { notification.customdata = CoreTextUtils.parseJSON<Record<string, unknown>>(notification.customdata, {}); } // Try to set courseid the notification belongs to. if (notification.customdata?.courseid) { notification.courseid = <number> notification.customdata.courseid; } else if (!notification.courseid) { const courseIdMatch = notification.fullmessagehtml.match(/course\/view\.php\?id=([^"]*)/); if (courseIdMatch?.[1]) { notification.courseid = parseInt(courseIdMatch[1], 10); } } if (notification.useridfrom > 0) { // Try to get the profile picture of the user. try { const user = await CoreUser.getProfile(notification.useridfrom, notification.courseid, true); notification.profileimageurlfrom = user.profileimageurl; notification.userfromfullname = user.fullname; } catch { // Error getting user. This can happen if device is offline or the user is deleted. } } return notification; }); return Promise.all(promises); } /** * Get the cache key for the get notification preferences call. * * @return Cache key. */ protected getNotificationPreferencesCacheKey(): string { return ROOT_CACHE_KEY + 'notificationPreferences'; } /** * Get notification preferences. * * @param siteId Site ID. If not defined, use current site. * @return Promise resolved with the notification preferences. */ async getNotificationPreferences(siteId?: string): Promise<AddonNotificationsPreferences> { this.logger.debug('Get notification preferences'); const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getNotificationPreferencesCacheKey(), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, }; const data = await site.read<AddonNotificationsGetUserNotificationPreferencesResult>( 'core_message_get_user_notification_preferences', {}, preSets, ); return data.preferences; } /** * Get cache key for notification list WS calls. * * @return Cache key. */ protected getNotificationsCacheKey(): string { return ROOT_CACHE_KEY + 'list'; } /** * Get notifications from site. * * @param read True if should get read notifications, false otherwise. * @param offset Position of the first notification to get. * @param options Other options. * @return Promise resolved with notifications. */ async getNotifications( read: boolean, offset: number, options?: AddonNotificationsGetNotificationsOptions, ): Promise<AddonNotificationsGetMessagesMessageFormatted[]> { options = options || {}; options.limit = options.limit || AddonNotificationsProvider.LIST_LIMIT; this.logger.debug(`Get ${(read ? 'read' : 'unread')} notifications from ${offset}. Limit: ${options.limit}`); const site = await CoreSites.getSite(options.siteId); const data: AddonNotificationsGetMessagesWSParams = { useridto: site.getUserId(), useridfrom: 0, type: 'notifications', read: !!read, newestfirst: true, limitfrom: offset, limitnum: options.limit, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getNotificationsCacheKey(), ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; // Get unread notifications. const response = await site.read<AddonNotificationsGetMessagesWSResponse>('core_message_get_messages', data, preSets); const notifications = response.messages; return this.formatNotificationsData(notifications, read); } /** * Get notifications from site using the new WebService. * * @param offset Position of the first notification to get. * @param options Other options. * @return Promise resolved with notifications and if can load more. * @since 3.2 */ async getPopupNotifications( offset: number, options?: AddonNotificationsGetNotificationsOptions, ): Promise<{notifications: AddonNotificationsPopupNotificationFormatted[]; canLoadMore: boolean}> { options = options || {}; options.limit = options.limit || AddonNotificationsProvider.LIST_LIMIT; this.logger.debug(`Get popup notifications from ${offset}. Limit: ${options.limit}`); const site = await CoreSites.getSite(options.siteId); const data: AddonNotificationsPopupGetPopupNotificationsWSParams = { useridto: site.getUserId(), newestfirst: true, offset, limit: options.limit + 1, // Get one more to calculate canLoadMore. }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getNotificationsCacheKey(), ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; // Get notifications. const response = await site.read<AddonNotificationsGetPopupNotificationsResult>( 'message_popup_get_popup_notifications', data, preSets, ); const notifications = await this.formatNotificationsData(response.notifications.slice(0, options.limit)); return { canLoadMore: response.notifications.length > options.limit, notifications, }; } /** * Get read notifications from site. * * @param offset Position of the first notification to get. * @param options Other options. * @return Promise resolved with notifications. */ getReadNotifications( offset: number, options?: AddonNotificationsGetNotificationsOptions, ): Promise<AddonNotificationsGetMessagesMessageFormatted[]> { return this.getNotifications(true, offset, options); } /** * Get unread notifications from site. * * @param offset Position of the first notification to get. * @param options Other options. * @return Promise resolved with notifications. */ getUnreadNotifications( offset: number, options?: AddonNotificationsGetNotificationsOptions, ): Promise<AddonNotificationsGetMessagesMessageFormatted[]> { return this.getNotifications(false, offset, options); } /** * Get unread notifications count. Do not cache calls. * * @param userId The user id who received the notification. If not defined, use current user. * @param siteId Site ID. If not defined, use current site. * @return Promise resolved with the message notifications count. */ async getUnreadNotificationsCount(userId?: number, siteId?: string): Promise<number> { const site = await CoreSites.getSite(siteId); // @since 3.2 if (site.wsAvailable('message_popup_get_unread_popup_notification_count')) { userId = userId || site.getUserId(); const params: AddonNotificationsPopupGetUnreadPopupNotificationCountWSParams = { useridto: userId, }; const preSets: CoreSiteWSPreSets = { getFromCache: false, emergencyCache: false, saveToCache: false, typeExpected: 'number', }; try { return await site.read<number>('message_popup_get_unread_popup_notification_count', params, preSets); } catch { // Return no messages if the call fails. return 0; } } // Fallback call try { const unread = await this.getUnreadNotifications(0, { limit: AddonNotificationsProvider.LIST_LIMIT, siteId }); // The app used to add a + sign if needed, but 3.1 will be dropped soon so it's easier to always return a number. return unread.length; } catch { // Return no messages if the call fails. return 0; } } /** * Returns whether or not popup WS is available for a certain site. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with true if available, resolved with false or rejected otherwise. * @since 3.2 */ async isPopupAvailable(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return site.wsAvailable('message_popup_get_popup_notifications'); } /** * Mark all message notification as read. * * @return Resolved when done. * @since 3.2 */ async markAllNotificationsAsRead(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); const params: CoreMessageMarkAllNotificationsAsReadWSParams = { useridto: CoreSites.getCurrentSiteUserId(), }; return site.write<boolean>('core_message_mark_all_notifications_as_read', params); } /** * Mark a single notification as read. * * @param notificationId ID of notification to mark as read * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. * @since 3.5 */ async markNotificationRead( notificationId: number, siteId?: string, ): Promise<CoreMessageMarkNotificationReadWSResponse | AddonMessagesMarkMessageReadResult> { const site = await CoreSites.getSite(siteId); if (site.wsAvailable('core_message_mark_notification_read')) { const params: CoreMessageMarkNotificationReadWSParams = { notificationid: notificationId, timeread: CoreTimeUtils.timestamp(), }; return site.write<CoreMessageMarkNotificationReadWSResponse>('core_message_mark_notification_read', params); } else { // Fallback for versions prior to 3.5. return AddonMessages.markMessageRead(notificationId, site.id); } } /** * Invalidate get notification preferences. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved when data is invalidated. */ async invalidateNotificationPreferences(siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getNotificationPreferencesCacheKey()); } /** * Invalidates notifications list WS calls. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the list is invalidated. */ async invalidateNotificationsList(siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getNotificationsCacheKey()); } /** * Returns whether or not we can mark all notifications as read. * * @return True if enabled, false otherwise. * @since 3.2 */ isMarkAllNotificationsAsReadEnabled(): boolean { return CoreSites.wsAvailableInCurrentSite('core_message_mark_all_notifications_as_read'); } /** * Returns whether or not we can count unread notifications precisely. * * @return True if enabled, false otherwise. * @since 3.2 */ isPreciseNotificationCountEnabled(): boolean { return CoreSites.wsAvailableInCurrentSite('message_popup_get_unread_popup_notification_count'); } /** * Returns whether or not the notification preferences are enabled for the current site. * * @return True if enabled, false otherwise. * @since 3.2 */ isNotificationPreferencesEnabled(): boolean { return CoreSites.wsAvailableInCurrentSite('core_message_get_user_notification_preferences'); } } export const AddonNotifications = makeSingleton(AddonNotificationsProvider); /** * Preferences returned by core_message_get_user_notification_preferences. */ export type AddonNotificationsPreferences = { userid: number; // User id. disableall: number | boolean; // Whether all the preferences are disabled. processors: AddonNotificationsPreferencesProcessor[]; // Config form values. components: AddonNotificationsPreferencesComponent[]; // Available components. enableall?: boolean; // Calculated in the app. Whether all the preferences are enabled. }; /** * Processor in notification preferences. */ export type AddonNotificationsPreferencesProcessor = { displayname: string; // Display name. name: string; // Processor name. hassettings: boolean; // Whether has settings. contextid: number; // Context id. userconfigured: number; // Whether is configured by the user. }; /** * Component in notification preferences. */ export type AddonNotificationsPreferencesComponent = { displayname: string; // Display name. notifications: AddonNotificationsPreferencesNotification[]; // List of notificaitons for the component. }; /** * Notification processor in notification preferences component. */ export type AddonNotificationsPreferencesNotification = { displayname: string; // Display name. preferencekey: string; // Preference key. processors: AddonNotificationsPreferencesNotificationProcessor[]; // Processors values for this notification. }; /** * Notification processor in notification preferences component. */ export type AddonNotificationsPreferencesNotificationProcessor = { displayname: string; // Display name. name: string; // Processor name. locked: boolean; // Is locked by admin?. lockedmessage?: string; // @since 3.6. Text to display if locked. userconfigured: number; // Is configured?. loggedin: AddonNotificationsPreferencesNotificationProcessorState; loggedoff: AddonNotificationsPreferencesNotificationProcessorState; }; /** * State in notification processor in notification preferences component. */ export type AddonNotificationsPreferencesNotificationProcessorState = { name: string; // Name. displayname: string; // Display name. checked: boolean; // Is checked?. }; /** * Params of core_message_get_messages WS. */ export type AddonNotificationsGetMessagesWSParams = { useridto: number; // The user id who received the message, 0 for any user. useridfrom?: number; // The user id who send the message, 0 for any user. -10 or -20 for no-reply or support user. type?: string; // Type of message to return, expected values are: notifications, conversations and both. read?: boolean; // True for getting read messages, false for unread. newestfirst?: boolean; // True for ordering by newest first, false for oldest first. limitfrom?: number; // Limit from. limitnum?: number; // Limit number. }; /** * Data returned by core_message_get_messages WS. */ export type AddonNotificationsGetMessagesWSResponse = { messages: AddonNotificationsGetMessagesMessage[]; warnings?: CoreWSExternalWarning[]; }; /** * Message data returned by core_message_get_messages. */ export type AddonNotificationsGetMessagesMessage = { id: number; // Message id. useridfrom: number; // User from id. useridto: number; // User to id. subject: string; // The message subject. text: string; // The message text formated. fullmessage: string; // The message. fullmessageformat: number; // Fullmessage format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). fullmessagehtml: string; // The message in html. smallmessage: string; // The shorten message. notification: number; // Is a notification?. contexturl: string; // Context URL. contexturlname: string; // Context URL link name. timecreated: number; // Time created. timeread: number; // Time read. usertofullname: string; // User to full name. userfromfullname: string; // User from full name. component?: string; // @since 3.7. The component that generated the notification. eventtype?: string; // @since 3.7. The type of notification. customdata?: string; // @since 3.7. Custom data to be passed to the message processor. }; /** * Message data returned by core_message_get_messages with some calculated data. */ export type AddonNotificationsGetMessagesMessageFormatted = Omit<AddonNotificationsGetMessagesMessage, 'customdata'> & AddonNotificationsNotificationCalculatedData; /** * Params of message_popup_get_popup_notifications WS. */ export type AddonNotificationsPopupGetPopupNotificationsWSParams = { useridto: number; // The user id who received the message, 0 for current user. newestfirst?: boolean; // True for ordering by newest first, false for oldest first. limit?: number; // The number of results to return. offset?: number; // Offset the result set by a given amount. }; /** * Result of WS message_popup_get_popup_notifications. */ export type AddonNotificationsGetPopupNotificationsResult = { notifications: AddonNotificationsPopupNotification[]; unreadcount: number; // The number of unread message for the given user. }; /** * Notification returned by message_popup_get_popup_notifications. */ export type AddonNotificationsPopupNotification = { id: number; // Notification id (this is not guaranteed to be unique within this result set). useridfrom: number; // User from id. useridto: number; // User to id. subject: string; // The notification subject. shortenedsubject: string; // The notification subject shortened with ellipsis. text: string; // The message text formated. fullmessage: string; // The message. fullmessageformat: number; // Fullmessage format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). fullmessagehtml: string; // The message in html. smallmessage: string; // The shorten message. contexturl: string; // Context URL. contexturlname: string; // Context URL link name. timecreated: number; // Time created. timecreatedpretty: string; // Time created in a pretty format. timeread: number; // Time read. read: boolean; // Notification read status. deleted: boolean; // Notification deletion status. iconurl: string; // URL for notification icon. component?: string; // The component that generated the notification. eventtype?: string; // The type of notification. customdata?: string; // @since 3.7. Custom data to be passed to the message processor. }; /** * Notification returned by message_popup_get_popup_notifications. */ export type AddonNotificationsPopupNotificationFormatted = Omit<AddonNotificationsPopupNotification, 'customdata'> & AddonNotificationsNotificationCalculatedData; /** * Any kind of notification that can be retrieved. */ export type AddonNotificationsAnyNotification = AddonNotificationsPopupNotificationFormatted | AddonNotificationsGetMessagesMessageFormatted; /** * Result of WS core_message_get_user_notification_preferences. */ export type AddonNotificationsGetUserNotificationPreferencesResult = { preferences: AddonNotificationsPreferences; warnings?: CoreWSExternalWarning[]; }; /** * Calculated data for messages returned by core_message_get_messages. */ export type AddonNotificationsNotificationCalculatedData = { mobiletext?: string; // Calculated in the app. Text to display for the notification. moodlecomponent?: string; // Calculated in the app. Moodle's component. notif?: number; // Calculated in the app. Whether it's a notification. notification?: number; // Calculated in the app in some cases. Whether it's a notification. read?: boolean; // Calculated in the app. Whether the notifications is read. courseid?: number; // Calculated in the app. Course the notification belongs to. profileimageurlfrom?: string; // Calculated in the app. Avatar of user that sent the notification. userfromfullname?: string; // Calculated in the app in some cases. User from full name. customdata?: Record<string, unknown>; // Parsed custom data. }; /** * Params of message_popup_get_unread_popup_notification_count WS. */ export type AddonNotificationsPopupGetUnreadPopupNotificationCountWSParams = { useridto: number; // The user id who received the message, 0 for any user. }; /** * Params of core_message_mark_all_notifications_as_read WS. */ export type CoreMessageMarkAllNotificationsAsReadWSParams = { useridto: number; // The user id who received the message, 0 for any user. useridfrom?: number; // The user id who send the message, 0 for any user. -10 or -20 for no-reply or support user. timecreatedto?: number; // Mark messages created before this time as read, 0 for all messages. }; /** * Params of core_message_mark_notification_read WS. */ export type CoreMessageMarkNotificationReadWSParams = { notificationid: number; // Id of the notification. timeread?: number; // Timestamp for when the notification should be marked read. }; /** * Data returned by core_message_mark_notification_read WS. */ export type CoreMessageMarkNotificationReadWSResponse = { notificationid: number; // Id of the notification. warnings?: CoreWSExternalWarning[]; }; /** * Options to pass to getNotifications and getPopupNotifications. */ export type AddonNotificationsGetNotificationsOptions = CoreSitesCommonWSOptions & { limit?: number; // Number of notifications to get. Defaults to LIST_LIMIT. };
the_stack
import { elementUpdated, expect, fixture, oneEvent } from '@open-wc/testing'; import { mock, spy, stub, useFakeTimers } from 'sinon'; import { safelyDefineCustomElement } from '../../../utils/dom'; import { keysOf } from '../../../utils/object'; import { equal, isFunction } from '../../../utils/unit'; import { CanPlay } from '../../CanPlay'; import { mediaContext, MediaContextRecord } from '../../context'; import { FAKE_MEDIA_PROVIDER_ELEMENT_TAG_NAME, FakeMediaProviderElement } from '../../test-utils'; import { ViewType } from '../../ViewType'; import { MediaProviderConnectEvent, MediaProviderElement } from '../MediaProviderElement'; safelyDefineCustomElement( FAKE_MEDIA_PROVIDER_ELEMENT_TAG_NAME, FakeMediaProviderElement ); describe('MediaProviderElement', function () { async function buildFixture() { const provider = await fixture<FakeMediaProviderElement>( `<vds-fake-media-provider></vds-fake-media-provider>` ); return { provider }; } describe('render', function () { it('should render DOM correctly', async function () { const { provider } = await buildFixture(); expect(provider).dom.to.equal(` <vds-fake-media-provider></vds-fake-media-provider> `); }); it('should render shadow DOM correctly', async function () { const { provider } = await buildFixture(); expect(provider).shadowDom.to.equal(''); }); }); describe('lifecycle', function () { it('should dispatch connect event when connected to DOM', async function () { const provider = document.createElement('vds-fake-media-provider'); setTimeout(() => { window.document.body.append(provider); }); const { detail } = (await oneEvent( document, 'vds-media-provider-connect' )) as MediaProviderConnectEvent; expect(detail.element).to.be.instanceOf(MediaProviderElement); expect(isFunction(detail.onDisconnect)).to.be.true; }); it('should dispose of disconnect callbacks when disconnected from DOM', async function () { const provider = document.createElement('vds-fake-media-provider'); setTimeout(() => { window.document.body.append(provider); }); const { detail } = (await oneEvent( document, 'vds-media-provider-connect' )) as MediaProviderConnectEvent; const callback = mock(); detail.onDisconnect(callback); provider.remove(); expect(callback).to.have.been.calledOnce; }); }); describe('props', function () { it('should have defined all ctx props', async function () { const { provider } = await buildFixture(); const ignore = new Set<keyof MediaContextRecord>([ 'canRequestFullscreen', 'bufferedAmount', 'seekableAmount', 'customControls', 'live', 'idle', 'isAudio', 'isVideo', 'isLiveVideo', 'isAudioView', 'isVideoView' ]); keysOf(mediaContext).forEach((prop) => { if (ignore.has(prop)) return; expect(equal(provider.ctx[prop], mediaContext[prop].initialValue), prop) .to.be.true; }); }); it('should have defined ctx props as provider props', async function () { const { provider } = await buildFixture(); const ignore = new Set<keyof MediaContextRecord>([ 'canRequestFullscreen', 'bufferedAmount', 'seekableAmount', 'customControls', 'idle', 'isAudio', 'isVideo', 'isLiveVideo', 'isAudioView', 'isVideoView' ]); keysOf(mediaContext).forEach((prop) => { if (ignore.has(prop)) return; expect(equal(provider[prop], mediaContext[prop].initialValue), prop).to .be.true; }); }); it('should update provider when volume is set', async function () { const { provider } = await buildFixture(); const volume = 0.75; const volumeSpy = spy(provider, '_setVolume'); provider.mediaRequestQueue.serveImmediately = true; provider.volume = volume; expect(volumeSpy).to.have.been.calledWith(volume); }); it('should update provider when currentTime is set', async function () { const { provider } = await buildFixture(); const currentTime = 420; const currentTimeSpy = spy(provider, '_setCurrentTime'); provider.mediaRequestQueue.serveImmediately = true; provider.currentTime = currentTime; expect(currentTimeSpy).to.have.been.calledWith(currentTime); }); it('should update provider when paused is set', async function () { const { provider } = await buildFixture(); const playSpy = spy(provider, 'play'); const pauseSpy = spy(provider, 'pause'); provider.mediaRequestQueue.serveImmediately = true; provider.paused = false; expect(playSpy).to.have.been.calledOnce; provider.paused = true; expect(pauseSpy).to.have.been.calledOnce; }); it('should update provider when muted is set', async function () { const { provider } = await buildFixture(); const mutedSpy = spy(provider, '_setMuted'); provider.mediaRequestQueue.serveImmediately = true; provider.muted = true; expect(mutedSpy).to.have.been.calledWith(true); }); }); describe('methods', function () { describe('shouldPlayType', function () { it('shoudPlayType should return false given canPlay is no', async function () { const { provider } = await buildFixture(); stub(provider, 'canPlayType').callsFake(() => CanPlay.No); expect(provider.shouldPlayType('')).to.be.false; }); it('shoudPlayType should return true given canPlay is maybe', async function () { const { provider } = await buildFixture(); stub(provider, 'canPlayType').callsFake(() => CanPlay.Maybe); expect(provider.shouldPlayType('')).to.be.true; }); it('shoudPlayType should return true given canPlay is probably', async function () { const { provider } = await buildFixture(); stub(provider, 'canPlayType').callsFake(() => CanPlay.Probably); expect(provider.shouldPlayType('')).to.be.true; }); }); describe('throwIfNotReadyForPlayback', function () { it('should throw if not ready', async function () { const { provider } = await buildFixture(); provider.ctx.canPlay = false; expect(() => { // @ts-expect-error Accessing protected property provider._throwIfNotReadyForPlayback(); }).to.throw(); }); it('should not throw if ready', async function () { const { provider } = await buildFixture(); provider.ctx.canPlay = true; expect(() => { // @ts-expect-error Accessing protected property provider._throwIfNotReadyForPlayback(); }).to.not.throw(); }); }); describe('resetPlayback', function () { it('should set currentTime to 0', async function () { const { provider } = await buildFixture(); const setTimeSpy = spy(provider, '_setCurrentTime'); // @ts-expect-error Accessing protected property provider._resetPlayback(); expect(setTimeSpy).to.have.been.calledOnceWith(0); }); }); describe('throwIfNotVideoView', function () { it('should throw if view type is not video', async function () { const { provider } = await buildFixture(); provider.ctx.viewType = ViewType.Unknown; expect(() => { // @ts-expect-error Accessing protected property provider._throwIfNotVideoView(); }).to.throw(); provider.ctx.viewType = ViewType.Audio; expect(() => { // @ts-expect-error Accessing protected property provider._throwIfNotVideoView(); }).to.throw(); }); it('should NOT throw if view type is of type video', async function () { const { provider } = await buildFixture(); provider.ctx.viewType = ViewType.Video; expect(() => { // @ts-expect-error Accessing protected property provider._throwIfNotVideoView(); }).to.not.throw(); }); }); describe('attemptAutoplay', function () { it('should not call play if autoplay is false', async function () { const { provider } = await buildFixture(); provider.autoplay = false; provider.ctx.canPlay = true; const playSpy = spy(provider, 'play'); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy).to.not.have.been.called; }); it('should not call play if not ready for playback', async function () { const { provider } = await buildFixture(); provider.autoplay = true; provider.ctx.canPlay = false; const playSpy = spy(provider, 'play'); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy).to.not.have.been.called; }); it('should not call play if playback has started', async function () { const { provider } = await buildFixture(); provider.autoplay = true; provider.ctx.canPlay = true; provider.ctx.started = true; const playSpy = spy(provider, 'play'); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy).to.not.have.been.called; }); it('should not call play if reached max attempts', async function () { const { provider } = await buildFixture(); provider.autoplay = true; provider.ctx.canPlay = true; // @ts-expect-error Accessing protected properties provider._autoplayRetryCount = provider._maxAutoplayRetries; const playSpy = spy(provider, 'play'); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy).to.not.have.been.called; }); it('should not retry if successful', async function () { const { provider } = await buildFixture(); provider.autoplay = true; provider.ctx.canPlay = true; const playSpy = spy(provider, 'play'); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy).to.have.been.calledOnce; // @ts-expect-error Accessing protected property expect(provider._autoplayRetryCount).to.equal(0); }); it('should give up after 2 attempts', async function () { const { provider } = await buildFixture(); provider.autoplay = true; provider.ctx.canPlay = true; const playSpy = stub(provider, 'play'); playSpy.callsFake(() => { throw Error(''); }); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy.getCalls()).to.have.length(2); }); it('should try muted on last attempt', async function () { const { provider } = await buildFixture(); provider.autoplay = true; provider.ctx.canPlay = true; provider.mediaRequestQueue.serveImmediately = true; // @ts-expect-error Accessing protected properties provider._autoplayRetryCount = provider._maxAutoplayRetries - 1; const playSpy = stub(provider, 'play'); playSpy.callsFake(() => { throw Error(''); }); const mutedSpy = spy(provider, '_setMuted'); // @ts-expect-error Accessing protected property await provider._attemptAutoplay(); expect(playSpy.getCalls()).to.have.length(1); expect(mutedSpy).to.have.been.calledOnceWith(true); }); }); }); describe('queue', function () { it('should queue request given provider is not ready and flush once ready', async function () { const { provider } = await buildFixture(); const volumeSpy = spy(provider, '_setVolume'); // Queue. provider.volume = 0.53; expect(provider.mediaRequestQueue.size, 'queue size').to.equal(1); // Flush. await provider.mediaRequestQueue.flush(); // Check. expect(provider.mediaRequestQueue.size, 'new queue size').to.equal(0); expect(volumeSpy).to.have.been.calledWith(0.53); }); it('should make request immediately if provider is ready', async function () { const { provider } = await buildFixture(); const volumeSpy = spy(provider, '_setVolume'); provider.mediaRequestQueue.serveImmediately = true; provider.volume = 0.53; await elementUpdated(provider); expect(provider.mediaRequestQueue.size, 'queue size').to.equal(0); expect(volumeSpy).to.have.been.calledWith(0.53); }); it('should overwrite request keys and only call once per "type"', async function () { const { provider } = await buildFixture(); const playSpy = spy(provider, 'play'); const pauseSpy = spy(provider, 'pause'); provider.paused = false; setTimeout(() => { provider.paused = true; expect(provider.mediaRequestQueue.size, 'queue size').to.equal(1); provider.mediaRequestQueue.flush(); }); await provider.mediaRequestQueue.waitForFlush(); expect(playSpy).to.not.have.been.called; expect(pauseSpy).to.have.been.calledOnce; }); }); });
the_stack
import React, { Dispatch, PropsWithChildren, SetStateAction, SyntheticEvent, } from "react"; import produce from "immer"; import get from "lodash/get"; import chunk from "lodash/chunk"; import { Alert, Accessibility, Box, Checkbox, Dropdown, DropdownItemProps, Flex, FormDropdown as FluentUIFormDropdown, FormRadioGroup as FluentUIFormRadioGroup, Input, RadioGroupItemProps, selectableListBehavior, SiteVariablesPrepared, Text, TextArea, AccessibilityDefinition, } from "@fluentui/react-northstar"; import { ICSSInJSStyle } from "@fluentui/styles"; import { ExclamationCircleIcon, ExclamationTriangleIcon, } from "@fluentui/react-icons-northstar"; import { getText, TTextObject, TTranslations } from "../../translations"; import { IFormProps, IFormState, TFormErrors } from "./Form"; /** * Properties for each option for Enumerable inputs (radio buttons, checkboxes, dropdowns). * @public */ export interface IEnumerableInputOption { /** * The option’s text content to display. */ title: TTextObject; /** * The option’s value, which should be unique for the input in which it’s available. */ value: string; } /** * Properties shared by all enumerable inputs (radio buttons, checkboxes, dropdowns). * @public */ export interface IEnumerableInputBase { /** * The input’s label. */ title: TTextObject; /** * The input’s options. */ options: IEnumerableInputOption[]; /** * The input’s unique ID. */ inputId: string; } /** * Properties shared by singleton enumerable inputs (radio buttons, single-select dropdowns). * @public */ export interface IEnumerableSingletonInputBase extends IEnumerableInputBase { /** * The input’s initial value. */ initialValue?: string; } /** * Properties shared by enumerable inputs supporting multiple selections (checkboxes, * multiple-select dropdowns). * @public */ export interface IEnumerableMultipleInputBase extends IEnumerableInputBase { /** * The input’s initial values. */ initialValues?: string[]; } /** * Properties shared by text inputs (single- and multi-line). * @public */ export interface ITextInputBase { /** * The input’s label. */ title: TTextObject; /** * The input’s unique ID */ inputId: string; /** * The input’s placeholder content. */ placeholder?: TTextObject; /** * The input’s initial value. */ initialValue?: string; } /** * An inline input’s width. * @public */ export enum EInputWidth { /** * The input should share the width with the other inline inputs. */ split = "split", /** * The input should occupy the full width of the Form */ full = "full", } interface IPreparedInput { formState: IFormState; setFormState: Dispatch<SetStateAction<IFormState>>; t: TTranslations; errors?: TFormErrors; breakpointOffset?: number; } /** * The types of inline inputs. * @public */ export enum EInlineInputType { text = "text", dropdown = "dropdown", } /** * The types of input blocks. * @public */ export enum EInputBlockType { inlineInputs = "inline-inputs", dropdown = "dropdown", multilineText = "multiline-text", radioButtons = "radio-buttons", checkboxes = "checkboxes", } /** * A single-line text field. * @public */ export interface ITextField extends ITextInputBase { type: EInlineInputType.text; width?: EInputWidth; } /** * A multi-line text field. * @public */ export interface IMultilineTextInput extends ITextInputBase { type: EInputBlockType.multilineText; } interface IPreparedMultilineTextInput extends IMultilineTextInput, IPreparedInput {} /** * @public */ export type TInlineField = IDropdownInput | IDropdownMultipleInput | ITextField; /** * A block containing a set of one or more text inputs or dropdowns. * @public */ export interface IInlineInputsBlock { type: EInputBlockType.inlineInputs; fields: TInlineField[]; } interface IPreparedInlineInputs extends IInlineInputsBlock, IPreparedInput {} /** * A single-select dropdown. * @public */ export interface IDropdownInput extends IEnumerableSingletonInputBase { type: EInlineInputType.dropdown | EInputBlockType.dropdown; multiple?: false; width?: EInputWidth; } interface IPreparedDropdownInput extends IDropdownInput, IPreparedInput {} /** * A multiple-select dropdown. * @public */ export interface IDropdownMultipleInput extends IEnumerableMultipleInputBase { type: EInlineInputType.dropdown | EInputBlockType.dropdown; multiple: true; width?: EInputWidth; } interface IPreparedDropdownMultipleInput extends IDropdownMultipleInput, IPreparedInput {} /** * A set of radio buttons (from which only one can be selected). * @public */ export interface IRadioButtonsInput extends IEnumerableSingletonInputBase { type: EInputBlockType.radioButtons; } interface IPreparedRadioButtonsInput extends IRadioButtonsInput, IPreparedInput {} /** * A set of checkboxes. * @public */ export interface ICheckboxesInput extends IEnumerableMultipleInputBase { type: EInputBlockType.checkboxes; } interface IPreparedCheckboxesInput extends ICheckboxesInput, IPreparedInput {} /** * A block with a single input which occupies the full width of the form. * @public */ export type TInputBlock = | IMultilineTextInput | IDropdownInput | IDropdownMultipleInput | IRadioButtonsInput | ICheckboxesInput; type TPreparedInputBlock = | IPreparedInlineInputs | IPreparedMultilineTextInput | IPreparedDropdownInput | IPreparedDropdownMultipleInput | IPreparedRadioButtonsInput | IPreparedCheckboxesInput; /** * @public */ export interface ISection { /** * The title of the section, rendered as an `h#` element. */ title?: TTextObject; /** * Text content of the section rendered before the input groups as a `p` element. */ preface?: TTextObject; /** * The input blocks to render in this section, which can either be a block with an individual * input, or a block with a set of inline inputs. */ inputBlocks?: (TInputBlock | IInlineInputsBlock)[]; } interface IFormSectionProps extends IPreparedInput { section: ISection; header?: false; keyPrefix: string; } interface IFormHeaderSectionProps { section: ISection; header: true; errors?: TFormErrors; t: TTranslations; } export const MaxWidth = ({ children, styles, flush, align = "center", }: PropsWithChildren<any>) => ( <Box styles={{ margin: (function () { switch (align) { case "left": return "0 auto 0 0"; default: return "0 auto"; } })(), maxWidth: flush ? "none" : "29.75rem", padding: flush ? 0 : "2rem", ...styles, }} > {children} </Box> ); interface IErrorMessageProps { excludeIcon?: boolean; message: TTextObject; id?: string; t?: TTranslations; styles?: ICSSInJSStyle; } const errorId = (describesId: string) => `${describesId}__error`; const labelId = (describesId: string) => `${describesId}__label`; const fullInputId = (inputId: string) => `input_${inputId}`; const ErrorMessage = ({ excludeIcon, message, id, t, styles, }: IErrorMessageProps) => ( <Box variables={({ colorScheme }: SiteVariablesPrepared) => ({ color: colorScheme.red.foreground, })} {...(id && { id })} styles={{ paddingLeft: ".375rem", ...styles }} > {!excludeIcon && ( <ExclamationCircleIcon outline size="small" styles={{ marginRight: ".25rem" }} /> )} <Text size="small" content={getText(t?.locale, message)} /> </Box> ); const DropdownBlock = ( props: IPreparedDropdownInput | IPreparedDropdownMultipleInput ) => { const { options, t, inputId, title, errors, formState, setFormState } = props; const id = fullInputId(inputId); const error = get(errors, inputId, false); const selectedValues = Array.isArray(formState[inputId]) ? formState[inputId] : formState[inputId] ? [formState[inputId]] : []; const items = options.map(({ title, value }) => ({ key: `${inputId}__${value}`, selected: selectedValues.includes(value), header: getText(t?.locale, title), "data-value": value, })); return ( <FluentUIFormDropdown fluid id={id} label={getText(t?.locale, title)} styles={{ marginBottom: ".75rem" }} onChange={(_e, props) => { setFormState( produce(formState, (draft) => { if (props.multiple) { const values = (get( props, "value", [] ) as DropdownItemProps[]).map( (selectedItemProps: DropdownItemProps) => get(selectedItemProps, "data-value") ); values.length ? (draft[inputId] = values) : delete draft[inputId]; } else { draft[inputId] = get(props, ["value", "data-value"]); } }) ); }} defaultValue={ props.multiple ? items.filter(({ "data-value": value }) => selectedValues.includes(value) ) : items.find(({ "data-value": value }) => selectedValues.includes(value) ) } items={items} {...(props.multiple && { multiple: true })} {...(error && { error: true, errorMessage: <ErrorMessage message={error} t={t} />, })} /> ); }; const splitQuery = (rowSize: number, breakpointOffset: number) => `@media (min-width: ${16 * 8.25 * rowSize + 16 * breakpointOffset}px)`; const textInputStyles = ( rowSize: number, group: number, breakpointOffset = 0 ) => ({ flex: "1 0 auto", marginRight: ".75rem", marginBottom: group === 0 ? ".25rem" : ".75rem", width: "100%", [splitQuery(rowSize, breakpointOffset)]: { order: group, width: `calc(${(100 / rowSize).toFixed(1)}% - .75rem)`, }, ...(group === 0 && { alignSelf: "flex-end" }), }); const InlineInputsBlock = ({ fields, t, errors, formState, setFormState, breakpointOffset, }: IPreparedInlineInputs) => { const rows: TInlineField[][] = []; let i = 0; while (i < fields.length) { switch (fields[i]?.width) { case "split": let j = i + 1; while (fields[j]?.width === "split") { j += 1; } Array.prototype.push.apply(rows, chunk(fields.slice(i, j + 1), 3)); i = j; break; default: rows.push([fields[i]]); i += 1; break; } } return ( <> {rows.map((rowFields, r) => { // TODO: row should have a stable field to use as the key, since the key // will be incorrect if the rows are shuffled. I've used the index for // now since it's more (but not totally) correct than the previous // behavior of using a generated id that changed on each render. return ( <Box key={`form-content__row-${r}`} styles={{ display: "flex", flexFlow: "row wrap", [splitQuery(rowFields.length, breakpointOffset || 0)]: { marginRight: "-.75rem", }, }} > {rowFields.map((field) => { const { inputId, title, type } = field; const id = fullInputId(inputId); const error = get(errors, inputId, false); return ( <React.Fragment key={`form-content__${inputId}`}> <Input.Label htmlFor={id} id={labelId(id)} styles={textInputStyles( rowFields.length, 0, breakpointOffset )} > {getText(t?.locale, title)} </Input.Label> {(() => { switch (type) { case "dropdown": const { options, multiple } = field as IDropdownInput; const selectedValues = Array.isArray(formState[inputId]) ? formState[inputId] : formState[inputId] ? [formState[inputId]] : []; const items = options.map(({ title, value }) => ({ key: `${inputId}__${value}`, selected: selectedValues.includes(value), header: getText(t?.locale, title), "data-value": value, })); return ( <Dropdown fluid id={id} label={getText(t?.locale, title)} styles={{ ...textInputStyles( rowFields.length, 1, breakpointOffset ), ...(error && { marginBottom: 0 }), }} onChange={(_e, props) => { setFormState( produce(formState, (draft) => { if (props.multiple) { const values = (get( props, "value", [] ) as DropdownItemProps[]).map( (selectedItemProps: DropdownItemProps) => get(selectedItemProps, "data-value") ); values.length ? (draft[inputId] = values) : delete draft[inputId]; } else { draft[inputId] = get(props, [ "value", "data-value", ]); } }) ); }} defaultValue={ multiple ? items.filter(({ "data-value": value }) => selectedValues.includes(value) ) : items.find(({ "data-value": value }) => selectedValues.includes(value) ) } items={items} {...(multiple && { multiple: true })} {...(error && { error: true })} /> ); case "text": const { placeholder } = field as ITextField; return ( <Input fluid id={id} {...(placeholder && { placeholder: getText(t.locale, placeholder), })} {...(error && { error: true })} styles={{ ...textInputStyles( rowFields.length, 1, breakpointOffset ), ...(error && { marginBottom: 0 }), }} aria-labelledby={[labelId(id)] .concat(error ? errorId(id) : []) .join(" ")} value={formState[inputId] as string} onChange={(_e, props) => { if (props && "value" in props) { setFormState( produce(formState, (draft) => { draft[inputId] = props.value.toString(); }) ); } }} /> ); default: return null; } })()} {error ? ( <ErrorMessage message={error} t={t} id={errorId(id)} styles={textInputStyles( rowFields.length, 2, breakpointOffset )} /> ) : ( <Box styles={{ ...textInputStyles( rowFields.length, 2, breakpointOffset ), marginBottom: 0, }} /> )} </React.Fragment> ); })} </Box> ); })} </> ); }; const CheckboxesBlock = ({ options, title, t, inputId, errors, formState, setFormState, }: IPreparedCheckboxesInput) => { const id = fullInputId(inputId); const error = get(errors, inputId, false); return ( <Box styles={{ marginBottom: ".75rem" }}> <Input.Label htmlFor={id} id={labelId(id)}> {getText(t?.locale, title)} </Input.Label> <Box id={id} accessibility={selectableListBehavior as () => AccessibilityDefinition} aria-labelledby={[labelId(id)] .concat(error ? errorId(id) : []) .join(" ")} aria-multiselectable="true" > {options.map(({ title, value }) => { const selected = formState[inputId]?.includes(value); return ( <Box key={`${id}__${value}`}> <Checkbox role="option" aria-selected={selected ? "true" : "false"} checked={selected} variables={{ layout: "radio-like" }} label={getText(t?.locale, title)} data-value={value} onChange={(e, props) => { setFormState( produce(formState, (draft) => { const value = get(props, "data-value"); if (props?.checked) { Array.isArray(draft[inputId]) ? (draft[inputId] as string[]).push(value) : (draft[inputId] = [value]); } else { const next_values = (draft[inputId] as string[]).filter( (v) => v !== value ); next_values.length > 0 ? (draft[inputId] = next_values) : delete draft[inputId]; } }) ); }} /> </Box> ); })} </Box> {error && <ErrorMessage message={error} t={t} id={errorId(id)} />} </Box> ); }; const MultilineTextBlock = ({ title, placeholder, t, inputId, errors, formState, setFormState, }: IPreparedMultilineTextInput) => { const id = fullInputId(inputId); const error = get(errors, inputId, false); return ( <Box styles={{ marginBottom: ".75rem" }}> <Input.Label htmlFor={id} id={labelId(id)}> {getText(t?.locale, title)} </Input.Label> <TextArea fluid={true} resize="vertical" id={id} value={(formState[inputId] as string) || ""} {...(placeholder && { placeholder: getText(t?.locale, placeholder) })} onChange={(e, props) => { setFormState( produce(formState, (draft) => { props && props.value ? (draft[inputId] = props.value) : delete draft[inputId]; }) ); }} /> {error && <ErrorMessage message={error} t={t} />} </Box> ); }; const RadioButtonsBlock = ({ options, t, inputId, title, errors, formState, setFormState, }: IPreparedRadioButtonsInput) => { const id = fullInputId(inputId); const error = get(errors, inputId, false); return ( <FluentUIFormRadioGroup id={id} vertical styles={{ marginBottom: ".75rem" }} label={getText(t?.locale, title)} {...(error && { errorMessage: <ErrorMessage message={error} t={t} /> })} items={options.map(({ title, value }) => { const label = getText(t?.locale, title); const key = `${inputId}__${value}`; const name = label; const checked = formState[inputId] === value; const onChange = ( _e: SyntheticEvent<HTMLElement, Event>, props: RadioGroupItemProps | undefined ) => { if (props && props.checked && props.value) setFormState( produce(formState, (draft) => { draft[inputId] = props.value!.toString(); }) ); }; return { key, value, label, name, checked, onChange }; })} /> ); }; const FormInputBlock = (props: TPreparedInputBlock) => { switch (props.type) { case "inline-inputs": return <InlineInputsBlock {...props} />; case "multiline-text": return <MultilineTextBlock {...props} />; case "dropdown": return <DropdownBlock {...props} />; case "checkboxes": return <CheckboxesBlock {...props} />; case "radio-buttons": return <RadioButtonsBlock {...props} />; default: return null; } }; const FormSection = (props: IFormSectionProps | IFormHeaderSectionProps) => { const { errors, header, section, t } = props; return ( <> {section.title && ( <Text as={header ? "h1" : "h2"} weight={header ? "bold" : "semibold"} size={header ? "large" : "medium"} > {getText(t.locale, section.title)} </Text> )} {section.preface && ( <Text as="p" variables={({ colorScheme }: SiteVariablesPrepared) => ({ color: colorScheme.default.foreground2, })} > {getText(t.locale, section.preface)} </Text> )} {section.inputBlocks?.length && section.inputBlocks.map((inputBlock, gi) => ( <FormInputBlock {...inputBlock} {...{ t, errors, formState: (props as IFormSectionProps).formState, setFormState: (props as IFormSectionProps).setFormState, breakpointOffset: (props as IFormSectionProps).breakpointOffset, }} key={`${(props as IFormSectionProps).keyPrefix}__Group-${gi}`} /> ))} </> ); }; interface IFormContentProps extends Omit<IFormProps, "submit"> { formState: IFormState; setFormState: Dispatch<SetStateAction<IFormState>>; t: TTranslations; flush?: boolean; align?: string; breakpointOffset?: number; } export const setInitialValue = ( acc: IFormState, field: | TInlineField | IMultilineTextInput | IDropdownInput | IDropdownMultipleInput | IRadioButtonsInput | ICheckboxesInput ) => { if ( field.hasOwnProperty("initialValue") && (field as | ITextField | IMultilineTextInput | IDropdownInput | IRadioButtonsInput).initialValue ) acc[field.inputId] = (field as | ITextField | IDropdownInput | IRadioButtonsInput).initialValue!; else if (field.hasOwnProperty("initialValues")) acc[field.inputId] = (field as IDropdownMultipleInput | ICheckboxesInput).initialValues || []; return acc; }; export const FormContent = React.memo( ({ topError, flush, t, headerSection, sections, errors, formState, setFormState, align, breakpointOffset, }: IFormContentProps) => { return ( <MaxWidth {...{ flush, align }}> {topError && ( <Alert danger visible dismissible content={ <Flex vAlign="center"> <ExclamationTriangleIcon outline styles={{ marginRight: ".25rem" }} /> <Text styles={{ margin: ".25rem 0" }} content={getText(t.locale, topError)} /> </Flex> } /> )} {headerSection && ( <FormSection header section={headerSection} {...{ t, errors }} /> )} {sections.map((section, si) => { const key = `Form__Section-${si}`; return ( <FormSection {...{ section, t, key, keyPrefix: key, errors, formState, setFormState, breakpointOffset, }} /> ); })} </MaxWidth> ); } );
the_stack
module android.app { import DialogInterface = android.content.DialogInterface; import Drawable = android.graphics.drawable.Drawable; import Bundle = android.os.Bundle; import Message = android.os.Message; import TypedValue = android.util.TypedValue; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import View = android.view.View; import WindowManager = android.view.WindowManager; import AdapterView = android.widget.AdapterView; import Button = android.widget.Button; import ListAdapter = android.widget.ListAdapter; import ListView = android.widget.ListView; import Application = android.app.Application; import Dialog = android.app.Dialog; import Context = android.content.Context; /** * A subclass of Dialog that can display one, two or three buttons. If you only want to * display a String in this dialog box, use the setMessage() method. If you * want to display a more complex view, look up the FrameLayout called "custom" * and add your view to it: * * <pre> * FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom); * fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT)); * </pre> * * <p>The AlertDialog class takes care of automatically setting * {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} for you based on whether * any views in the dialog return true from {@link View#onCheckIsTextEditor() * View.onCheckIsTextEditor()}. Generally you want this set for a Dialog * without text editors, so that it will be placed on top of the current * input method UI. You can modify this behavior by forcing the flag to your * desired mode after calling {@link #onCreate}. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about creating dialogs, read the * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p> * </div> */ export class AlertDialog extends Dialog implements DialogInterface { private mAlert:AlertController; /** * Special theme constant for {@link #AlertDialog(Context, int)}: use * the traditional (pre-Holo) alert dialog theme. */ static THEME_TRADITIONAL:number = 1; /** * Special theme constant for {@link #AlertDialog(Context, int)}: use * the holographic alert theme with a dark background. */ static THEME_HOLO_DARK:number = 2; /** * Special theme constant for {@link #AlertDialog(Context, int)}: use * the holographic alert theme with a light background. */ static THEME_HOLO_LIGHT:number = 3; /** * Special theme constant for {@link #AlertDialog(Context, int)}: use * the device's default alert theme with a dark background. */ static THEME_DEVICE_DEFAULT_DARK:number = 4; /** * Special theme constant for {@link #AlertDialog(Context, int)}: use * the device's default alert theme with a light background. */ static THEME_DEVICE_DEFAULT_LIGHT:number = 5; /** * Construct an AlertDialog that uses an explicit theme. The actual style * that an AlertDialog uses is a private implementation, however you can * here supply either the name of an attribute in the theme from which * to get the dialog's style (such as {@link android.R.attr#alertDialogTheme} * or one of the constants {@link #THEME_TRADITIONAL}, * {@link #THEME_HOLO_DARK}, or {@link #THEME_HOLO_LIGHT}. */ constructor(context:Context, cancelable?:boolean, cancelListener?:DialogInterface.OnCancelListener) { super(context); //this.mWindow.alwaysReadCloseOnTouchAttr(); this.setCancelable(cancelable); this.setOnCancelListener(cancelListener); this.mAlert = new AlertController(context, this, this.getWindow()); } //static resolveDialogTheme(context:Context, resid:number):number { // if (resid == AlertDialog.THEME_TRADITIONAL) { // return com.android.internal.R.style.Theme_Dialog_Alert; // } else if (resid == AlertDialog.THEME_HOLO_DARK) { // return com.android.internal.R.style.Theme_Holo_Dialog_Alert; // } else if (resid == AlertDialog.THEME_HOLO_LIGHT) { // return com.android.internal.R.style.Theme_Holo_Light_Dialog_Alert; // } else if (resid == AlertDialog.THEME_DEVICE_DEFAULT_DARK) { // return com.android.internal.R.style.Theme_DeviceDefault_Dialog_Alert; // } else if (resid == AlertDialog.THEME_DEVICE_DEFAULT_LIGHT) { // return com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog_Alert; // } else if (resid >= 0x01000000) { // // start of real resource IDs. // return resid; // } else { // let outValue:TypedValue = new TypedValue(); // context.getTheme().resolveAttribute(com.android.internal.R.attr.alertDialogTheme, outValue, true); // return outValue.resourceId; // } //} /** * Gets one of the buttons used in the dialog. * <p> * If a button does not exist in the dialog, null will be returned. * * @param whichButton The identifier of the button that should be returned. * For example, this can be * {@link DialogInterface#BUTTON_POSITIVE}. * @return The button from the dialog, or null if a button does not exist. */ getButton(whichButton:number):Button { return this.mAlert.getButton(whichButton); } /** * Gets the list view used in the dialog. * * @return The {@link ListView} from the dialog. */ getListView():ListView { return this.mAlert.getListView(); } setTitle(title:string):void { super.setTitle(title); this.mAlert.setTitle(title); } /** * @see Builder#setCustomTitle(View) */ setCustomTitle(customTitleView:View):void { this.mAlert.setCustomTitle(customTitleView); } setMessage(message:string):void { this.mAlert.setMessage(message); } /** * Set the view to display in that dialog, specifying the spacing to appear around that * view. * * @param view The view to show in the content area of the dialog * @param viewSpacingLeft Extra space to appear to the left of {@code view} * @param viewSpacingTop Extra space to appear above {@code view} * @param viewSpacingRight Extra space to appear to the right of {@code view} * @param viewSpacingBottom Extra space to appear below {@code view} */ setView(view:View, viewSpacingLeft=0, viewSpacingTop=0, viewSpacingRight=0, viewSpacingBottom=0):void { this.mAlert.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight, viewSpacingBottom); } ///** // * Set a message to be sent when a button is pressed. // * // * @param whichButton Which button to set the message for, can be one of // * {@link DialogInterface#BUTTON_POSITIVE}, // * {@link DialogInterface#BUTTON_NEGATIVE}, or // * {@link DialogInterface#BUTTON_NEUTRAL} // * @param text The text to display in positive button. // * @param msg The {@link Message} to be sent when clicked. // */ //setButton(whichButton:number, text:CharSequence, msg:Message):void { // this.mAlert.setButton(whichButton, text, null, msg); //} /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param whichButton Which button to set the listener on, can be one of * {@link DialogInterface#BUTTON_POSITIVE}, * {@link DialogInterface#BUTTON_NEGATIVE}, or * {@link DialogInterface#BUTTON_NEUTRAL} * @param text The text to display in positive button. * @param listener The {@link DialogInterface.OnClickListener} to use. */ setButton(whichButton:number, text:string, listener:DialogInterface.OnClickListener):void { this.mAlert.setButton(whichButton, text, listener, null); } ///** // * @deprecated Use {@link #setButton(int, CharSequence, Message)} with // * {@link DialogInterface#BUTTON_POSITIVE}. // */ //setButton(text:CharSequence, msg:Message):void { // this.setButton(BUTTON_POSITIVE, text, msg); //} // ///** // * @deprecated Use {@link #setButton(int, CharSequence, Message)} with // * {@link DialogInterface#BUTTON_NEGATIVE}. // */ //setButton2(text:CharSequence, msg:Message):void { // this.setButton(BUTTON_NEGATIVE, text, msg); //} // ///** // * @deprecated Use {@link #setButton(int, CharSequence, Message)} with // * {@link DialogInterface#BUTTON_NEUTRAL}. // */ //setButton3(text:CharSequence, msg:Message):void { // this.setButton(BUTTON_NEUTRAL, text, msg); //} // ///** // * Set a listener to be invoked when button 1 of the dialog is pressed. // * // * @param text The text to display in button 1. // * @param listener The {@link DialogInterface.OnClickListener} to use. // * @deprecated Use // * {@link #setButton(int, CharSequence, android.content.DialogInterface.OnClickListener)} // * with {@link DialogInterface#BUTTON_POSITIVE} // */ //setButton(text:CharSequence, listener:OnClickListener):void { // this.setButton(BUTTON_POSITIVE, text, listener); //} // ///** // * Set a listener to be invoked when button 2 of the dialog is pressed. // * @param text The text to display in button 2. // * @param listener The {@link DialogInterface.OnClickListener} to use. // * @deprecated Use // * {@link #setButton(int, CharSequence, android.content.DialogInterface.OnClickListener)} // * with {@link DialogInterface#BUTTON_NEGATIVE} // */ //setButton2(text:CharSequence, listener:OnClickListener):void { // this.setButton(BUTTON_NEGATIVE, text, listener); //} // ///** // * Set a listener to be invoked when button 3 of the dialog is pressed. // * @param text The text to display in button 3. // * @param listener The {@link DialogInterface.OnClickListener} to use. // * @deprecated Use // * {@link #setButton(int, CharSequence, android.content.DialogInterface.OnClickListener)} // * with {@link DialogInterface#BUTTON_POSITIVE} // */ //setButton3(text:CharSequence, listener:OnClickListener):void { // this.setButton(BUTTON_NEUTRAL, text, listener); //} // ///** // * Set resId to 0 if you don't want an icon. // * @param resId the resourceId of the drawable to use as the icon or 0 // * if you don't want an icon. // */ //setIcon(resId:number):void { // this.mAlert.setIcon(resId); //} setIcon(icon:Drawable):void { this.mAlert.setIcon(icon); } ///** // * Set an icon as supplied by a theme attribute. e.g. android.R.attr.alertDialogIcon // * // * @param attrId ID of a theme attribute that points to a drawable resource. // */ //setIconAttribute(attrId:number):void { // let out:TypedValue = new TypedValue(); // this.mContext.getTheme().resolveAttribute(attrId, out, true); // this.mAlert.setIcon(out.resourceId); //} // //setInverseBackgroundForced(forceInverseBackground:boolean):void { // this.mAlert.setInverseBackgroundForced(forceInverseBackground); //} protected onCreate(savedInstanceState:Bundle):void { super.onCreate(savedInstanceState); this.mAlert.installContent(); } onKeyDown(keyCode:number, event:KeyEvent):boolean { if (this.mAlert.onKeyDown(keyCode, event)) return true; return super.onKeyDown(keyCode, event); } onKeyUp(keyCode:number, event:KeyEvent):boolean { if (this.mAlert.onKeyUp(keyCode, event)) return true; return super.onKeyUp(keyCode, event); } } export module AlertDialog{ export class Builder { private P:AlertController.AlertParams; //private mTheme:number = 0; /** * Constructor using a context and theme for this builder and * the {@link AlertDialog} it creates. The actual theme * that an AlertDialog uses is a private implementation, however you can * here supply either the name of an attribute in the theme from which * to get the dialog's style (such as {@link android.R.attr#alertDialogTheme} * or one of the constants * {@link AlertDialog#THEME_TRADITIONAL AlertDialog.THEME_TRADITIONAL}, * {@link AlertDialog#THEME_HOLO_DARK AlertDialog.THEME_HOLO_DARK}, or * {@link AlertDialog#THEME_HOLO_LIGHT AlertDialog.THEME_HOLO_LIGHT}. */ constructor(context:Context) { this.P = new AlertController.AlertParams(context); //this.mTheme = theme; } /** * Returns a {@link Context} with the appropriate theme for dialogs created by this Builder. * Applications should use this Context for obtaining LayoutInflaters for inflating views * that will be used in the resulting dialogs, as it will cause views to be inflated with * the correct theme. * * @return A Context for built Dialogs. */ getContext():Context { return this.P.mContext; } ///** // * Set the title using the given resource id. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setTitle(titleId:number):Builder { // this.P.mTitle = this.P.mContext.getText(titleId); // return this; //} /** * Set the title displayed in the {@link Dialog}. * * @return This Builder object to allow for chaining of calls to set methods */ setTitle(title:string):Builder { this.P.mTitle = title; return this; } /** * Set the title using the custom view {@code customTitleView}. The * methods {@link #setTitle(int)} and {@link #setIcon(int)} should be * sufficient for most titles, but this is provided if the title needs * more customization. Using this will replace the title and icon set * via the other methods. * * @param customTitleView The custom view to use as the title. * * @return This Builder object to allow for chaining of calls to set methods */ setCustomTitle(customTitleView:View):Builder { this.P.mCustomTitleView = customTitleView; return this; } ///** // * Set the message to display using the given resource id. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setMessage(messageId:number):Builder { // this.P.mMessage = this.P.mContext.getText(messageId); // return this; //} /** * Set the message to display. * * @return This Builder object to allow for chaining of calls to set methods */ setMessage(message:string):Builder { this.P.mMessage = message; return this; } ///** // * Set the resource id of the {@link Drawable} to be used in the title. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setIcon(iconId:number):Builder { // this.P.mIconId = iconId; // return this; //} /** * Set the {@link Drawable} to be used in the title. * * @return This Builder object to allow for chaining of calls to set methods */ setIcon(icon:Drawable):Builder { this.P.mIcon = icon; return this; } ///** // * Set an icon as supplied by a theme attribute. e.g. android.R.attr.alertDialogIcon // * // * @param attrId ID of a theme attribute that points to a drawable resource. // */ //setIconAttribute(attrId:number):Builder { // let out:TypedValue = new TypedValue(); // this.P.mContext.getTheme().resolveAttribute(attrId, out, true); // this.P.mIconId = out.resourceId; // return this; //} ///** // * Set a listener to be invoked when the positive button of the dialog is pressed. // * @param textId The resource id of the text to display in the positive button // * @param listener The {@link DialogInterface.OnClickListener} to use. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setPositiveButton(textId:number, listener:OnClickListener):Builder { // this.P.mPositiveButtonText = this.P.mContext.getText(textId); // this.P.mPositiveButtonListener = listener; // return this; //} /** * Set a listener to be invoked when the positive button of the dialog is pressed. * @param text The text to display in the positive button * @param listener The {@link DialogInterface.OnClickListener} to use. * * @return This Builder object to allow for chaining of calls to set methods */ setPositiveButton(text:string, listener:DialogInterface.OnClickListener):Builder { this.P.mPositiveButtonText = text; this.P.mPositiveButtonListener = listener; return this; } ///** // * Set a listener to be invoked when the negative button of the dialog is pressed. // * @param textId The resource id of the text to display in the negative button // * @param listener The {@link DialogInterface.OnClickListener} to use. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setNegativeButton(textId:number, listener:OnClickListener):Builder { // this.P.mNegativeButtonText = this.P.mContext.getText(textId); // this.P.mNegativeButtonListener = listener; // return this; //} /** * Set a listener to be invoked when the negative button of the dialog is pressed. * @param text The text to display in the negative button * @param listener The {@link DialogInterface.OnClickListener} to use. * * @return This Builder object to allow for chaining of calls to set methods */ setNegativeButton(text:string, listener:DialogInterface.OnClickListener):Builder { this.P.mNegativeButtonText = text; this.P.mNegativeButtonListener = listener; return this; } ///** // * Set a listener to be invoked when the neutral button of the dialog is pressed. // * @param textId The resource id of the text to display in the neutral button // * @param listener The {@link DialogInterface.OnClickListener} to use. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setNeutralButton(textId:number, listener:OnClickListener):Builder { // this.P.mNeutralButtonText = this.P.mContext.getText(textId); // this.P.mNeutralButtonListener = listener; // return this; //} /** * Set a listener to be invoked when the neutral button of the dialog is pressed. * @param text The text to display in the neutral button * @param listener The {@link DialogInterface.OnClickListener} to use. * * @return This Builder object to allow for chaining of calls to set methods */ setNeutralButton(text:string, listener:DialogInterface.OnClickListener):Builder { this.P.mNeutralButtonText = text; this.P.mNeutralButtonListener = listener; return this; } /** * Sets whether the dialog is cancelable or not. Default is true. * * @return This Builder object to allow for chaining of calls to set methods */ setCancelable(cancelable:boolean):Builder { this.P.mCancelable = cancelable; return this; } /** * Sets the callback that will be called if the dialog is canceled. * * <p>Even in a cancelable dialog, the dialog may be dismissed for reasons other than * being canceled or one of the supplied choices being selected. * If you are interested in listening for all cases where the dialog is dismissed * and not just when it is canceled, see * {@link #setOnDismissListener(android.content.DialogInterface.OnDismissListener) setOnDismissListener}.</p> * @see #setCancelable(boolean) * @see #setOnDismissListener(android.content.DialogInterface.OnDismissListener) * * @return This Builder object to allow for chaining of calls to set methods */ setOnCancelListener(onCancelListener:DialogInterface.OnCancelListener):Builder { this.P.mOnCancelListener = onCancelListener; return this; } /** * Sets the callback that will be called when the dialog is dismissed for any reason. * * @return This Builder object to allow for chaining of calls to set methods */ setOnDismissListener(onDismissListener:DialogInterface.OnDismissListener):Builder { this.P.mOnDismissListener = onDismissListener; return this; } /** * Sets the callback that will be called if a key is dispatched to the dialog. * * @return This Builder object to allow for chaining of calls to set methods */ setOnKeyListener(onKeyListener:DialogInterface.OnKeyListener):Builder { this.P.mOnKeyListener = onKeyListener; return this; } ///** // * Set a list of items to be displayed in the dialog as the content, you will be notified of the // * selected item via the supplied listener. This should be an array type i.e. R.array.foo // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setItems(itemsId:number, listener:OnClickListener):Builder { // this.P.mItems = this.P.mContext.getResources().getTextArray(itemsId); // this.P.mOnClickListener = listener; // return this; //} /** * Set a list of items to be displayed in the dialog as the content, you will be notified of the * selected item via the supplied listener. * * @return This Builder object to allow for chaining of calls to set methods */ setItems(items:string[], listener:DialogInterface.OnClickListener):Builder { this.P.mItems = items; this.P.mOnClickListener = listener; return this; } /** * Set a list of items, which are supplied by the given {@link ListAdapter}, to be * displayed in the dialog as the content, you will be notified of the * selected item via the supplied listener. * * @param adapter The {@link ListAdapter} to supply the list of items * @param listener The listener that will be called when an item is clicked. * * @return This Builder object to allow for chaining of calls to set methods */ setAdapter(adapter:ListAdapter, listener:DialogInterface.OnClickListener):Builder { this.P.mAdapter = adapter; this.P.mOnClickListener = listener; return this; } ///** // * Set a list of items, which are supplied by the given {@link Cursor}, to be // * displayed in the dialog as the content, you will be notified of the // * selected item via the supplied listener. // * // * @param cursor The {@link Cursor} to supply the list of items // * @param listener The listener that will be called when an item is clicked. // * @param labelColumn The column name on the cursor containing the string to display // * in the label. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setCursor(cursor:Cursor, listener:OnClickListener, labelColumn:string):Builder { // this.P.mCursor = cursor; // this.P.mLabelColumn = labelColumn; // this.P.mOnClickListener = listener; // return this; //} // ///** // * Set a list of items to be displayed in the dialog as the content, // * you will be notified of the selected item via the supplied listener. // * This should be an array type, e.g. R.array.foo. The list will have // * a check mark displayed to the right of the text for each checked // * item. Clicking on an item in the list will not dismiss the dialog. // * Clicking on a button will dismiss the dialog. // * // * @param itemsId the resource id of an array i.e. R.array.foo // * @param checkedItems specifies which items are checked. It should be null in which case no // * items are checked. If non null it must be exactly the same length as the array of // * items. // * @param listener notified when an item on the list is clicked. The dialog will not be // * dismissed when an item is clicked. It will only be dismissed if clicked on a // * button, if no buttons are supplied it's up to the user to dismiss the dialog. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setMultiChoiceItems(itemsId:number, checkedItems:boolean[], listener:OnMultiChoiceClickListener):Builder { // this.P.mItems = this.P.mContext.getResources().getTextArray(itemsId); // this.P.mOnCheckboxClickListener = listener; // this.P.mCheckedItems = checkedItems; // this.P.mIsMultiChoice = true; // return this; //} /** * Set a list of items to be displayed in the dialog as the content, * you will be notified of the selected item via the supplied listener. * The list will have a check mark displayed to the right of the text * for each checked item. Clicking on an item in the list will not * dismiss the dialog. Clicking on a button will dismiss the dialog. * * @param items the text of the items to be displayed in the list. * @param checkedItems specifies which items are checked. It should be null in which case no * items are checked. If non null it must be exactly the same length as the array of * items. * @param listener notified when an item on the list is clicked. The dialog will not be * dismissed when an item is clicked. It will only be dismissed if clicked on a * button, if no buttons are supplied it's up to the user to dismiss the dialog. * * @return This Builder object to allow for chaining of calls to set methods */ setMultiChoiceItems(items:string[], checkedItems:boolean[], listener:DialogInterface.OnMultiChoiceClickListener):Builder { this.P.mItems = items; this.P.mOnCheckboxClickListener = listener; this.P.mCheckedItems = checkedItems; this.P.mIsMultiChoice = true; return this; } ///** // * Set a list of items to be displayed in the dialog as the content, // * you will be notified of the selected item via the supplied listener. // * The list will have a check mark displayed to the right of the text // * for each checked item. Clicking on an item in the list will not // * dismiss the dialog. Clicking on a button will dismiss the dialog. // * // * @param cursor the cursor used to provide the items. // * @param isCheckedColumn specifies the column name on the cursor to use to determine // * whether a checkbox is checked or not. It must return an integer value where 1 // * means checked and 0 means unchecked. // * @param labelColumn The column name on the cursor containing the string to display in the // * label. // * @param listener notified when an item on the list is clicked. The dialog will not be // * dismissed when an item is clicked. It will only be dismissed if clicked on a // * button, if no buttons are supplied it's up to the user to dismiss the dialog. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setMultiChoiceItems(cursor:Cursor, isCheckedColumn:string, labelColumn:string, listener:OnMultiChoiceClickListener):Builder { // this.P.mCursor = cursor; // this.P.mOnCheckboxClickListener = listener; // this.P.mIsCheckedColumn = isCheckedColumn; // this.P.mLabelColumn = labelColumn; // this.P.mIsMultiChoice = true; // return this; //} // ///** // * Set a list of items to be displayed in the dialog as the content, you will be notified of // * the selected item via the supplied listener. This should be an array type i.e. // * R.array.foo The list will have a check mark displayed to the right of the text for the // * checked item. Clicking on an item in the list will not dismiss the dialog. Clicking on a // * button will dismiss the dialog. // * // * @param itemsId the resource id of an array i.e. R.array.foo // * @param checkedItem specifies which item is checked. If -1 no items are checked. // * @param listener notified when an item on the list is clicked. The dialog will not be // * dismissed when an item is clicked. It will only be dismissed if clicked on a // * button, if no buttons are supplied it's up to the user to dismiss the dialog. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setSingleChoiceItems(itemsId:number, checkedItem:number, listener:OnClickListener):Builder { // this.P.mItems = this.P.mContext.getResources().getTextArray(itemsId); // this.P.mOnClickListener = listener; // this.P.mCheckedItem = checkedItem; // this.P.mIsSingleChoice = true; // return this; //} // ///** // * Set a list of items to be displayed in the dialog as the content, you will be notified of // * the selected item via the supplied listener. The list will have a check mark displayed to // * the right of the text for the checked item. Clicking on an item in the list will not // * dismiss the dialog. Clicking on a button will dismiss the dialog. // * // * @param cursor the cursor to retrieve the items from. // * @param checkedItem specifies which item is checked. If -1 no items are checked. // * @param labelColumn The column name on the cursor containing the string to display in the // * label. // * @param listener notified when an item on the list is clicked. The dialog will not be // * dismissed when an item is clicked. It will only be dismissed if clicked on a // * button, if no buttons are supplied it's up to the user to dismiss the dialog. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setSingleChoiceItems(cursor:Cursor, checkedItem:number, labelColumn:string, listener:OnClickListener):Builder { // this.P.mCursor = cursor; // this.P.mOnClickListener = listener; // this.P.mCheckedItem = checkedItem; // this.P.mLabelColumn = labelColumn; // this.P.mIsSingleChoice = true; // return this; //} /** * Set a list of items to be displayed in the dialog as the content, you will be notified of * the selected item via the supplied listener. The list will have a check mark displayed to * the right of the text for the checked item. Clicking on an item in the list will not * dismiss the dialog. Clicking on a button will dismiss the dialog. * * @param items the items to be displayed. * @param checkedItem specifies which item is checked. If -1 no items are checked. * @param listener notified when an item on the list is clicked. The dialog will not be * dismissed when an item is clicked. It will only be dismissed if clicked on a * button, if no buttons are supplied it's up to the user to dismiss the dialog. * * @return This Builder object to allow for chaining of calls to set methods */ setSingleChoiceItems(items:string[], checkedItem:number, listener:DialogInterface.OnClickListener):Builder { this.P.mItems = items; this.P.mOnClickListener = listener; this.P.mCheckedItem = checkedItem; this.P.mIsSingleChoice = true; return this; } /** * Set a list of items to be displayed in the dialog as the content, you will be notified of * the selected item via the supplied listener. The list will have a check mark displayed to * the right of the text for the checked item. Clicking on an item in the list will not * dismiss the dialog. Clicking on a button will dismiss the dialog. * * @param adapter The {@link ListAdapter} to supply the list of items * @param checkedItem specifies which item is checked. If -1 no items are checked. * @param listener notified when an item on the list is clicked. The dialog will not be * dismissed when an item is clicked. It will only be dismissed if clicked on a * button, if no buttons are supplied it's up to the user to dismiss the dialog. * * @return This Builder object to allow for chaining of calls to set methods */ setSingleChoiceItemsWithAdapter(adapter:ListAdapter, checkedItem:number, listener:DialogInterface.OnClickListener):Builder { this.P.mAdapter = adapter; this.P.mOnClickListener = listener; this.P.mCheckedItem = checkedItem; this.P.mIsSingleChoice = true; return this; } /** * Sets a listener to be invoked when an item in the list is selected. * * @param listener The listener to be invoked. * @see AdapterView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) * * @return This Builder object to allow for chaining of calls to set methods */ setOnItemSelectedListener(listener:AdapterView.OnItemSelectedListener):Builder { this.P.mOnItemSelectedListener = listener; return this; } ///** // * Set a custom view to be the contents of the Dialog. If the supplied view is an instance // * of a {@link ListView} the light background will be used. // * // * @param view The view to use as the contents of the Dialog. // * // * @return This Builder object to allow for chaining of calls to set methods // */ //setView(view:View):Builder { // this.P.mView = view; // this.P.mViewSpacingSpecified = false; // return this; //} /** * Set a custom view to be the contents of the Dialog, specifying the * spacing to appear around that view. If the supplied view is an * instance of a {@link ListView} the light background will be used. * * @param view The view to use as the contents of the Dialog. * @param viewSpacingLeft Spacing between the left edge of the view and * the dialog frame * @param viewSpacingTop Spacing between the top edge of the view and * the dialog frame * @param viewSpacingRight Spacing between the right edge of the view * and the dialog frame * @param viewSpacingBottom Spacing between the bottom edge of the view * and the dialog frame * @return This Builder object to allow for chaining of calls to set * methods * * * This is currently hidden because it seems like people should just * be able to put padding around the view. * @hide */ setView(view:View, viewSpacingLeft=0, viewSpacingTop=0, viewSpacingRight=0, viewSpacingBottom=0):Builder { this.P.mView = view; if(!viewSpacingLeft && !viewSpacingTop && !viewSpacingRight && !viewSpacingBottom){ this.P.mViewSpacingSpecified = false; }else{ this.P.mViewSpacingSpecified = true; this.P.mViewSpacingLeft = viewSpacingLeft; this.P.mViewSpacingTop = viewSpacingTop; this.P.mViewSpacingRight = viewSpacingRight; this.P.mViewSpacingBottom = viewSpacingBottom; } return this; } /** * Sets the Dialog to use the inverse background, regardless of what the * contents is. * * @param useInverseBackground Whether to use the inverse background * * @return This Builder object to allow for chaining of calls to set methods */ setInverseBackgroundForced(useInverseBackground:boolean):Builder { this.P.mForceInverseBackground = useInverseBackground; return this; } /** * @hide */ setRecycleOnMeasureEnabled(enabled:boolean):Builder { this.P.mRecycleOnMeasure = enabled; return this; } /** * Creates a {@link AlertDialog} with the arguments supplied to this builder. It does not * {@link Dialog#show()} the dialog. This allows the user to do any extra processing * before displaying the dialog. Use {@link #show()} if you don't have any other processing * to do and want this to be created and displayed. */ create():AlertDialog { const dialog:AlertDialog = new AlertDialog(this.P.mContext); this.P.apply(dialog.mAlert); dialog.setCancelable(this.P.mCancelable); if (this.P.mCancelable) { dialog.setCanceledOnTouchOutside(true); } dialog.setOnCancelListener(this.P.mOnCancelListener); dialog.setOnDismissListener(this.P.mOnDismissListener); if (this.P.mOnKeyListener != null) { dialog.setOnKeyListener(this.P.mOnKeyListener); } return dialog; } /** * Creates a {@link AlertDialog} with the arguments supplied to this builder and * {@link Dialog#show()}'s the dialog. */ show():AlertDialog { let dialog:AlertDialog = this.create(); dialog.show(); return dialog; } } } }
the_stack
/// <reference types="jquery" /> /// <reference types="knockout" /> // By default, Durandal uses JQuery's Defer/Promise implementation, but durandal supports injecting/configuring // usage of different JavaScript Defer/Promise libraries (f.ex. Q or ES6 Promise polyfills). // You might therefore want to use a different interface from a community typings file or your custom unified interface. // When using f.ex. Q as Defer/Promise library replace the lines below with: // <reference types="q" /> // interface DurandalPromise<T> extends Q.Promise<T> // interface DurandalDeferred<T> extends Q.Deferred<T> interface DurandalPromise<T> extends JQueryPromise<T> { } interface DurandalDeferred<T> extends JQueryDeferred<T> { } /** * The system module encapsulates the most basic features used by other modules. * @requires require * @requires jquery */ declare module 'durandal/system' { var theModule: DurandalSystemModule; export = theModule; } interface DurandalSystemModule { /** * Durandal's version. */ version: string; /** * A noop function. */ noop: Function; /** * Gets the module id for the specified object. * @param {object} obj The object whose module id you wish to determine. * @returns {string} The module id. */ getModuleId(obj: any): string; /** * Sets the module id for the specified object. * @param {object} obj The object whose module id you wish to set. * @param {string} id The id to set for the specified object. */ setModuleId(obj: any, id: string): void; /** * Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned. * @param {object} module The module to use to get/create the default object for. * @returns {object} The default object for the module. */ resolveObject(module: any): any; /** * Gets/Sets whether or not Durandal is in debug mode. * @param {boolean} [enable] Turns on/off debugging. * @returns {boolean} Whether or not Durandal is current debugging. */ debug(enable?: boolean): boolean; /** * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. * @param {object} info* The objects to log. */ log(...msgs: any[]): void; /** * Logs an error. * @param {string} obj The error to report. */ error(error: string): void; /** * Logs an error. * @param {Error} obj The error to report. */ error(error: Error): void; /** * Asserts a condition by throwing an error if the condition fails. * @param {boolean} condition The condition to check. * @param {string} message The message to report in the error if the condition check fails. */ assert(condition: boolean, message: string): void; /** * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. * @param {function} [action] The action to defer. You will be passed the deferred object as a parameter. * @returns {Deferred} The deferred object. */ defer<T>(action?: (dfd: DurandalDeferred<T>) => void): DurandalDeferred<T>; /** * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid). * @returns {string} The guid. */ guid(): string; /** * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. * @param {string} moduleId The id of the module to load. * @returns {Promise} A promise for the loaded module. */ acquire(moduleId: string): DurandalPromise<any>; /** * Uses require.js to obtain an array of modules. This function returns a promise which resolves with the modules instances in an array. * @param {string[]} moduleIds The ids of the modules to load. * @returns {Promise} A promise for the loaded module. */ acquire(modules: string[]): DurandalPromise<any[]>; /** * Uses require.js to obtain multiple modules. This function returns a promise which resolves with the module instances in an array. * @param {string} moduleIds* The ids of the modules to load. * @returns {Promise} A promise for the loaded module. */ acquire(...moduleIds: string[]): DurandalPromise<any[]>; /** * Extends the first object with the properties of the following objects. * @param {object} obj The target object to extend. * @param {object} extension* Uses to extend the target object. */ extend(obj: any, ...extensions: any[]): any; /** * Uses a setTimeout to wait the specified milliseconds. * @param {number} milliseconds The number of milliseconds to wait. * @returns {Promise} */ wait(milliseconds: number): DurandalPromise<any>; /** * Gets all the owned keys of the specified object. * @param {object} object The object whose owned keys should be returned. * @returns {string[]} The keys. */ keys(obj: any): string[]; /** * Determines if the specified object is an html element. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isElement(obj: any): boolean; /** * Determines if the specified object is an array. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isArray(obj: any): boolean; /** * Determines if the specified object is a boolean. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isObject(obj: any): boolean; /** * Determines if the specified object is a promise. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isPromise(obj: any): boolean; /** * Determines if the specified object is a function arguments object. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isArguments(obj: any): boolean; /** * Determines if the specified object is a function. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isFunction(obj: any): boolean; /** * Determines if the specified object is a string. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isString(obj: any): boolean; /** * Determines if the specified object is a number. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isNumber(obj: any): boolean; /** * Determines if the specified object is a date. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isDate(obj: any): boolean; /** * Determines if the specified object is a boolean. * @param {object} object The object to check. * @returns {boolean} True if matches the type, false otherwise. */ isBoolean(obj: any): boolean; } /** * The viewEngine module provides information to the viewLocator module which is used to locate the view's source file. The viewEngine also transforms a view id into a view instance. * @requires system * @requires jquery */ declare module 'durandal/viewEngine' { var theModule: DurandalViewEngineModule; export = theModule; } interface DurandalViewEngineModule { /** * The file extension that view source files are expected to have. * @default .html */ viewExtension: string; /** * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path). * @default text */ viewPlugin: string; /** * Parameters passed to the RequireJS loader plugin used by the viewLocator to obtain the view source. * @default The empty string by default. */ viewPluginParameters: string; /** * Determines if the url is a url for a view, according to the view engine. * @param {string} url The potential view url. * @returns {boolean} True if the url is a view url, false otherwise. */ isViewUrl(url: string): boolean; /** * Converts a view url into a view id. * @param {string} url The url to convert. * @returns {string} The view id. */ convertViewUrlToViewId(url: string): string; /** * Converts a view id into a full RequireJS path. * @param {string} viewId The view id to convert. * @returns {string} The require path. */ convertViewIdToRequirePath(viewId: string): string; /** * Parses the view engine recognized markup and returns DOM elements. * @param {string} markup The markup to parse. * @returns {HTMLElement[]} The elements. */ parseMarkup(markup: string): Node[]; /** * Calls `parseMarkup` and then pipes the results through `ensureSingleElement`. * @param {string} markup The markup to process. * @returns {HTMLElement} The view. */ processMarkup(markup: string): HTMLElement; /** * Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped. * @param {HTMLElement[]} allElements The elements. * @returns {HTMLElement} A single element. */ ensureSingleElement(allElements: Node[]): HTMLElement; /** * Gets the view associated with the id from the cache of parsed views. * @param {string} id The view id to lookup in the cache. * @return {DOMElement|null} The cached view or null if it's not in the cache. */ tryGetViewFromCache(id: string): HTMLElement; /** * Puts the view associated with the id into the cache of parsed views. * @param {string} id The view id whose view should be cached. * @param {DOMElement} view The view to cache. */ putViewInCache(id: string, view: HTMLElement): void; /** * Creates the view associated with the view id. * @param {string} viewId The view id whose view should be created. * @returns {DurandalPromise<HTMLElement>} A promise of the view. */ createView(viewId: string): DurandalPromise<HTMLElement>; /** * Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development. * @param {string} viewId The view id whose view should be created. * @param {string} requirePath The require path that was attempted. * @param {Error} requirePath The error that was returned from the attempt to locate the default view. * @returns {Promise} A promise for the fallback view. */ createFallbackView(viewId: string, requirePath: string, err: Error): DurandalPromise<HTMLElement>; } /** * Durandal events originate from backbone.js but also combine some ideas from signals.js as well as some additional improvements. * Events can be installed into any object and are installed into the `app` module by default for convenient app-wide eventing. * @requires system */ declare module 'durandal/events' { var theModule: DurandalEventModule; export = theModule; } /** * The binder joins an object instance and a DOM element tree by applying databinding and/or invoking binding lifecycle callbacks (binding and bindingComplete). * @requires system * @requires knockout */ declare module 'durandal/binder' { interface BindingInstruction { applyBindings: boolean; } /** * Called before every binding operation. Does nothing by default. * @param {object} data The data that is about to be bound. * @param {DOMElement} view The view that is about to be bound. * @param {object} instruction The object that carries the binding instructions. */ export var binding: (data: any, view: HTMLElement, instruction: BindingInstruction) => void; /** * Called after every binding operation. Does nothing by default. * @param {object} data The data that has just been bound. * @param {DOMElement} view The view that has just been bound. * @param {object} instruction The object that carries the binding instructions. */ export var bindingComplete: (data: any, view: HTMLElement, instruction: BindingInstruction) => void; /** * Indicates whether or not the binding system should throw errors or not. * @default false The binding system will not throw errors by default. Instead it will log them. */ export var throwOnErrors: boolean; /** * Gets the binding instruction that was associated with a view when it was bound. * @param {DOMElement} view The view that was previously bound. * @returns {object} The object that carries the binding instructions. */ export function getBindingInstruction(view: HTMLElement): BindingInstruction; /** * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. * @param {KnockoutBindingContext} bindingContext The current binding context. * @param {DOMElement} view The view to bind. * @param {object} [obj] The data to bind to, causing the creation of a child binding context if present. * @param {string} [dataAlias] An alias for $data if present. */ export function bindContext(bindingContext: KnockoutBindingContext, view: HTMLElement, obj?: any, dataAlias?: string): BindingInstruction; /** * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. * @param {object} obj The data to bind to. * @param {DOMElement} view The view to bind. */ export function bind(obj: any, view: HTMLElement): BindingInstruction; } /** * The activator module encapsulates all logic related to screen/component activation. * An activator is essentially an asynchronous state machine that understands a particular state transition protocol. * The protocol ensures that the following series of events always occur: `canDeactivate` (previous state), `canActivate` (new state), `deactivate` (previous state), `activate` (new state). * Each of the _can_ callbacks may return a boolean, affirmative value or promise for one of those. If either of the _can_ functions yields a false result, then activation halts. * @requires system * @requires knockout */ declare module 'durandal/activator' { /** * The default settings used by activators. * @property {ActivatorSettings} defaults */ export var defaults: DurandalActivatorSettings; /** * Creates a new activator. * @method create * @param {object} [initialActiveItem] The item which should be immediately activated upon creation of the ativator. * @param {ActivatorSettings} [settings] Per activator overrides of the default activator settings. * @returns {Activator} The created activator. */ export function create<T>(initialActiveItem?: T, settings?: DurandalActivatorSettings): DurandalActivator<T>; /** * Determines whether or not the provided object is an activator or not. * @method isActivator * @param {object} object Any object you wish to verify as an activator or not. * @returns {boolean} True if the object is an activator; false otherwise. */ export function isActivator(object: any): boolean; } /** * The viewLocator module collaborates with the viewEngine module to provide views (literally dom sub-trees) to other parts of the framework as needed. The primary consumer of the viewLocator is the composition module. * @requires system * @requires viewEngine */ declare module 'durandal/viewLocator' { var theModule: DurandalViewLocatorModule; export = theModule; } interface DurandalViewLocatorModule { /** * Allows you to set up a convention for mapping module folders to view folders. It is a convenience method that customizes `convertModuleIdToViewId` and `translateViewIdToArea` under the covers. * @param {string} [modulesPath] A string to match in the path and replace with the viewsPath. If not specified, the match is 'viewmodels'. * @param {string} [viewsPath] The replacement for the modulesPath. If not specified, the replacement is 'views'. * @param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location. */ useConvention(modulesPath?: string, viewsPath?: string, areasPath?: string): void; /** * Maps an object instance to a view instance. * @param {object} obj The object to locate the view for. * @param {string} [area] The area to translate the view to. * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. * @returns {Promise} A promise of the view. */ locateViewForObject(obj: any, area: string, elementsToSearch?: HTMLElement[]): DurandalPromise<HTMLElement>; /** * Converts a module id into a view id. By default the ids are the same. * @param {string} moduleId The module id. * @returns {string} The view id. */ convertModuleIdToViewId(moduleId: string): string; /** * If no view id can be determined, this function is called to genreate one. By default it attempts to determine the object's type and use that. * @param {object} obj The object to determine the fallback id for. * @returns {string} The view id. */ determineFallbackViewId(obj: any): string; /** * Takes a view id and translates it into a particular area. By default, no translation occurs. * @param {string} viewId The view id. * @param {string} area The area to translate the view to. * @returns {string} The translated view id. */ translateViewIdToArea(viewId: string, area: string): string; /** * Locates the specified view. * @param {string|DOMElement} view A view. It will be immediately returned. * @param {string} [area] The area to translate the view to. * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. * @returns {Promise} A promise of the view. */ locateView(view: HTMLElement, area?: string, elementsToSearch?: HTMLElement[]): DurandalPromise<HTMLElement>; /** * Locates the specified view. * @param {string|DOMElement} viewUrlOrId A view url or view id to locate. * @param {string} [area] The area to translate the view to. * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. * @returns {Promise} A promise of the view. */ locateView(viewUrlOrId: string, area?: string, elementsToSearch?: HTMLElement[]): DurandalPromise<HTMLElement>; } /** * The composition module encapsulates all functionality related to visual composition. * @requires system * @requires viewLocator * @requires binder * @requires viewEngine * @requires activator * @requires jquery * @requires knockout */ declare module 'durandal/composition' { interface CompositionTransation { /** * Registers a callback which will be invoked when the current composition transaction has completed. The transaction includes all parent and children compositions. * @param {function} callback The callback to be invoked when composition is complete. */ complete(callback: Function): void; } interface CompositionContext { mode: string; parent: HTMLElement; activeView: HTMLElement; triggerAttach(): void; bindingContext?: KnockoutBindingContext; cacheViews?: boolean; viewElements?: HTMLElement[]; model?: any; view?: any; area?: string; preserveContext?: boolean; activate?: boolean; strategy?: (context: CompositionContext) => DurandalPromise<HTMLElement>; composingNewView: boolean; child: HTMLElement; binding?: (child: HTMLElement, parent: HTMLElement, context: CompositionContext) => void; attached?: (child: HTMLElement, parent: HTMLElement, context: CompositionContext) => void; compositionComplete?: (child: HTMLElement, parent: HTMLElement, context: CompositionContext) => void; transition?: string; } /** * Converts a transition name to its moduleId. * @param {string} name The name of the transtion. * @returns {string} The moduleId. */ export function convertTransitionToModuleId(name: string): string; /** * The name of the transition to use in all compositions. * @default null */ export var defaultTransitionName: string; /** * Represents the currently executing composition transaction. */ export var current: CompositionTransation; /** * Registers a binding handler that will be invoked when the current composition transaction is complete. * @param {string} name The name of the binding handler. * @param {object} [config] The binding handler instance. If none is provided, the name will be used to look up an existing handler which will then be converted to a composition handler. * @param {function} [initOptionsFactory] If the registered binding needs to return options from its init call back to knockout, this function will server as a factory for those options. It will receive the same parameters that the init function does. */ export function addBindingHandler(name: string, config?: KnockoutBindingHandler, initOptionsFactory?: (element?: HTMLElement, valueAccessor?: any, allBindingsAccessor?: any, viewModel?: any, bindingContext?: KnockoutBindingContext) => any): void; /** * Gets an object keyed with all the elements that are replacable parts, found within the supplied elements. The key will be the part name and the value will be the element itself. * @param {DOMElement[]} elements The elements to search for parts. * @returns {object} An object keyed by part. */ export function getParts(elements: HTMLElement[]): any; /** * Gets an object keyed with all the elements that are replacable parts, found within the supplied element. The key will be the part name and the value will be the element itself. * @param {DOMElement} element The element to search for parts. * @returns {object} An object keyed by part. */ export function getParts(element: HTMLElement): any; /** * Eecutes the default view location strategy. * @param {object} context The composition context containing the model and possibly existing viewElements. * @returns {promise} A promise for the view. */ export var defaultStrategy: (context: CompositionContext) => DurandalPromise<HTMLElement>; /** * Initiates a composition. * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the parent for the composition. * @param {object} settings The composition settings. * @param {object} [bindingContext] The current binding context. */ export function compose(element: HTMLElement, settings: CompositionContext, bindingContext: KnockoutBindingContext): void; } /** * The app module controls app startup, plugin loading/configuration and root visual display. * @requires system * @requires viewEngine * @requires composition * @requires events * @requires jquery */ declare module 'durandal/app' { var theModule: DurandalAppModule; export = theModule; } /** * The dialog module enables the display of message boxes, custom modal dialogs and other overlays or slide-out UI abstractions. Dialogs are constructed by the composition system which interacts with a user defined dialog context. The dialog module enforced the activator lifecycle. * @requires system * @requires app * @requires composition * @requires activator * @requires viewEngine * @requires jquery * @requires knockout */ declare module 'plugins/dialog' { import composition = require('durandal/composition'); /** * Models a message box's message, title and options. * @class */ class Box { constructor(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object); /** * Selects an option and closes the message box, returning the selected option through the dialog system's promise. * @param {string} dialogResult The result to select. */ selectOption(dialogResult: string): void; /** * Provides the view to the composition system. * @returns {DOMElement} The view of the message box. */ getView(): HTMLElement; /** * Configures a custom view to use when displaying message boxes. * @method setViewUrl * @param {string} viewUrl The view url relative to the base url which the view locator will use to find the message box's view. */ static setViewUrl(viewUrl: string): void; /** * The title to be used for the message box if one is not provided. * @default Application * @static */ static defaultTitle: string; /** * The options to display in the message box if none are specified. * @default ['Ok'] * @static */ static defaultOptions: string[]; /** * Sets the classes and styles used throughout the message box markup. * @method setDefaults * @param {object} settings A settings object containing the following optional properties: buttonClass, primaryButtonClass, secondaryButtonClass, class, style. */ static setDefaults(settings: Object): void; /** * The markup for the message box's view. */ static defaultViewMarkup: string; } interface DialogContext { /** * In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module. * @param {Dialog} theDialog The dialog model. */ addHost(theDialog: Dialog): void; /** * This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup. * @param {Dialog} theDialog The dialog model. */ removeHost(theDialog: Dialog): void; /** * This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model. * @param {DOMElement} child The dialog view. * @param {DOMElement} parent The parent view. * @param {object} context The composition context. */ compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void; /** * Opacity of the blockout. The default is 0.6. */ blockoutOpacity?: number; } interface Dialog { host: HTMLElement; owner: any; context: DialogContext; activator: DurandalActivator<any>; close(): DurandalPromise<any>; settings: composition.CompositionContext; } /** * The constructor function used to create message boxes. */ export var MessageBox: Box; /** * The css zIndex that the last dialog was displayed at. */ export var currentZIndex: number; /** * Gets the next css zIndex at which a dialog should be displayed. * @returns {number} The next usable zIndex. */ export function getNextZIndex(): number; /** * Determines whether or not there are any dialogs open. * @returns {boolean} True if a dialog is open. false otherwise. */ export function isOpen(): boolean; /** * Gets the dialog context by name or returns the default context if no name is specified. * @param {string} [name] The name of the context to retrieve. * @returns {DialogContext} True context. */ export function getContext(name?: string): DialogContext; /** * Adds (or replaces) a dialog context. * @param {string} name The name of the context to add. * @param {DialogContext} dialogContext The context to add. */ export function addContext(name: string, modalContext: DialogContext): void; /** * Gets the dialog model that is associated with the specified object. * @param {object} obj The object for whom to retrieve the dialog. * @returns {Dialog} The dialog model. */ export function getDialog(obj: any): Dialog; /** * Closes the dialog associated with the specified object. * @param {object} obj The object whose dialog should be closed. * @param {object} results* The results to return back to the dialog caller after closing. */ export function close(obj: any, ...results: any[]): void; /** * Shows a dialog. * @param {object|string} obj The object (or moduleId) to display as a dialog. * @param {object} [activationData] The data that should be passed to the object upon activation. * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified. * @returns {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. */ export function show(obj: any, activationData?: any, context?: string): DurandalPromise<any>; /** * Shows a message box. * @param {string} message The message to display in the dialog. * @param {string} [title] The title message. * @param {string[]} [options] The options to provide to the user. * @param {boolean} [autoclose] Automatically close the the message box when clicking outside? * @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles. * @returns {Promise} A promise that resolves when the message box is closed and returns the selected option. */ export function showMessage(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object): DurandalPromise<string>; /** * Shows a message box. * @param {string} message The message to display in the dialog. * @param {string} [title] The title message. * @param {DialogButton[]} [options] The options to provide to the user. * @param {boolean} [autoclose] Automatically close the the message box when clicking outside? * @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles. * @returns {Promise} A promise that resolves when the message box is closed and returns the selected option. */ export function showMessage(message: string, title?: string, options?: DialogButton[], autoclose?: boolean, settings?: Object): DurandalPromise<any>; /** * Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods. * @param {object} [config] Add a `messageBox` property to supply a custom message box constructor. Add a `messageBoxView` property to supply custom view markup for the built-in message box. You can also use messageBoxViewUrl to specify the view url. */ export function install(config: Object): void; } /** * This module is based on Backbone's core history support. It abstracts away the low level details of working with browser history and url changes in order to provide a solid foundation for a router. * @requires system * @requires jquery */ declare module 'plugins/history' { /** * The setTimeout interval used when the browser does not support hash change events. * @default 50 */ export var interval: number; /** * Indicates whether or not the history module is actively tracking history. */ export var active: boolean; /** * Gets the true hash value. Cannot use location.hash directly due to a bug in Firefox where location.hash will always be decoded. * @param {string} [window] The optional window instance * @returns {string} The hash. */ export function getHash(window?: Window): string; /** * Get the cross-browser normalized URL fragment, either from the URL, the hash, or the override. * @param {string} fragment The fragment. * @param {boolean} forcePushState Should we force push state? * @returns {string} The fragment. */ export function getFragment(fragment: string, forcePushState: boolean): string; /** * Activate the hash change handling, returning `true` if the current URL matches an existing route, and `false` otherwise. * @param {HistoryOptions} options. * @returns {boolean|undefined} Returns true/false from loading the url unless the silent option was selected. */ export function activate(options: DurandalHistoryOptions): boolean; /** * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. */ export function deactivate(): void; /** * Checks the current URL to see if it has changed, and if it has, calls `loadUrl`, normalizing across the hidden iframe. * @returns {boolean} Returns true/false from loading the url. */ export function checkUrl(): boolean; /** * Attempts to load the current URL fragment. A pass-through to options.routeHandler. * @returns {boolean} Returns true/false from the route handler. */ export function loadUrl(): boolean; /** * Save a fragment into the hash history, or replace the URL state if the * 'replace' option is passed. You are responsible for properly URL-encoding * the fragment in advance. * The options object can contain `trigger: false` if you wish to not have the * route callback be fired, or `replace: true`, if * you wish to modify the current URL without adding an entry to the history. * @param {string} fragment The url fragment to navigate to. * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. * @return {boolean} Returns true/false from loading the url. */ export function navigate(fragment: string, trigger?: boolean): boolean; /** * Save a fragment into the hash history, or replace the URL state if the * 'replace' option is passed. You are responsible for properly URL-encoding * the fragment in advance. * The options object can contain `trigger: false` if you wish to not have the * route callback be fired, or `replace: true`, if * you wish to modify the current URL without adding an entry to the history. * @param {string} fragment The url fragment to navigate to. * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. * @return {boolean} Returns true/false from loading the url. */ export function navigate(fragment: string, options: DurandalNavigationOptions): boolean; /** * Navigates back in the browser history. */ export function navigateBack(): void; } /** * Enables common http request scenarios. * @requires jquery * @requires knockout */ declare module 'plugins/http' { /** * The name of the callback parameter to inject into jsonp requests by default. * @default callback */ export var callbackParam: string; /** * Converts the data to JSON. * @param {object} data The data to convert to JSON. * @return {string} JSON. */ export function toJSON(data: Object): string; /** * Makes an HTTP GET request. * @param {string} url The url to send the get request to. * @param {object} [query] An optional key/value object to transform into query string parameters. * @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @returns {Promise} A promise of the get response data. */ export function get(url: string, query?: Object, headers?: Object): DurandalPromise<any>; /** * Makes an JSONP request. * @param {string} url The url to send the get request to. * @param {object} [query] An optional key/value object to transform into query string parameters. * @param {string} [callbackParam] The name of the callback parameter the api expects (overrides the default callbackParam). * @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @returns {Promise} A promise of the response data. */ export function jsonp(url: string, query?: Object, callbackParam?: string, headers?: Object): DurandalPromise<any>; /** * Makes an HTTP POST request. * @param {string} url The url to send the post request to. * @param {object} data The data to post. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @returns {Promise} A promise of the response data. */ export function post(url: string, data: Object, headers?: Object): DurandalPromise<any>; /** * Makes an HTTP PUT request. * @method put * @param {string} url The url to send the put request to. * @param {object} data The data to put. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @return {Promise} A promise of the response data. */ export function put(url: string, data: Object, headers?: Object): DurandalPromise<any>; /** * Makes an HTTP DELETE request. * @method remove * @param {string} url The url to send the delete request to. * @param {object} [query] An optional key/value object to transform into query string parameters. * @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. * @return {Promise} A promise of the get response data. */ export function remove(url: string, query?: Object, headers?: Object): DurandalPromise<any>; } /** * Enables automatic observability of plain javascript object for ES5 compatible browsers. Also, converts promise properties into observables that are updated when the promise resolves. * @requires system * @requires binder * @requires knockout */ declare module 'plugins/observable' { function observable(obj: any, property: string): KnockoutObservable<any>; namespace observable { /** * Converts an entire object into an observable object by re-writing its attributes using ES5 getters and setters. Attributes beginning with '_' or '$' are ignored. * @param {object} obj The target object to convert. */ export function convertObject(obj: any): void; /** * Converts a normal property into an observable property using ES5 getters and setters. * @param {object} obj The target object on which the property to convert lives. * @param {string} propertyName The name of the property to convert. * @param {object} [original] The original value of the property. If not specified, it will be retrieved from the object. * @returns {KnockoutObservable} The underlying observable. */ export function convertProperty(obj: any, propertyName: string, original?: any): KnockoutObservable<any>; /** * Defines a computed property using ES5 getters and setters. * @param {object} obj The target object on which to create the property. * @param {string} propertyName The name of the property to define. * @param {function|object} evaluatorOrOptions The Knockout computed function or computed options object. * @returns {KnockoutComputed} The underlying computed observable. */ export function defineProperty<T>(obj: any, propertyName: string, evaluatorOrOptions?: KnockoutComputedDefine<T>): KnockoutComputed<T>; /** * Installs the plugin into the view model binder's `beforeBind` hook so that objects are automatically converted before being bound. */ export function install(config: Object): void; } export = observable; } /** * Serializes and deserializes data to/from JSON. * @requires system */ declare module 'plugins/serializer' { interface SerializerOptions { /** * The default replacer function used during serialization. By default properties starting with '_' or '$' are removed from the serialized object. * @param {string} key The object key to check. * @param {object} value The object value to check. * @returns {object} The value to serialize. */ replacer?: (key: string, value: any) => any; /** * The amount of space to use for indentation when writing out JSON. * @default undefined */ space: any; } interface DeserializerOptions { /** * Gets the type id for an object instance, using the configured `typeAttribute`. * @param {object} object The object to serialize. * @returns {string} The type. */ getTypeId: (object: any) => string; /** * Gets the constructor based on the type id. * @param {string} typeId The type id. * @returns {Function} The constructor. */ getConstructor: (typeId: string) => () => any; /** * The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping. * @param {string} key The attribute key. * @param {object} value The object value associated with the key. * @returns {object} The value. */ reviver: (key: string, value: any) => any; } /** * The name of the attribute that the serializer should use to identify an object's type. * @default type */ export var typeAttribute: string; /** * The amount of space to use for indentation when writing out JSON. * @default undefined */ export var space: any; /** * The default replacer function used during serialization. By default properties starting with '_' or '$' are removed from the serialized object. * @param {string} key The object key to check. * @param {object} value The object value to check. * @returns {object} The value to serialize. */ export function replacer(key: string, value: any): any; /** * Serializes the object. * @param {object} object The object to serialize. * @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults. * @returns {string} The JSON string. */ export function serialize(object: any, settings?: string): string; /** * Serializes the object. * @param {object} object The object to serialize. * @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults. * @returns {string} The JSON string. */ export function serialize(object: any, settings?: number): string; /** * Serializes the object. * @param {object} object The object to serialize. * @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults. * @returns {string} The JSON string. */ export function serialize(object: any, settings?: SerializerOptions): string; /** * Gets the type id for an object instance, using the configured `typeAttribute`. * @param {object} object The object to serialize. * @returns {string} The type. */ export function getTypeId(object: any): string; /** * Maps type ids to object constructor functions. Keys are type ids and values are functions. */ export var typeMap: any; /** * Adds a type id/constructor function mampping to the `typeMap`. * @param {string} typeId The type id. * @param {function} constructor The constructor. */ export function registerType(typeId: string, constructor: () => any): void; /** * The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping. * @param {string} key The attribute key. * @param {object} value The object value associated with the key. * @param {function} getTypeId A custom function used to get the type id from a value. * @param {object} getConstructor A custom function used to get the constructor function associated with a type id. * @returns {object} The value. */ export function reviver(key: string, value: any, getTypeId: (value: any) => string, getConstructor: (id: string) => () => any): any; /** * Deserialize the JSON. * @param {text} text The JSON string. * @param {DeserializerOptions} settings Settings can specify a reviver, getTypeId function or getConstructor function. * @returns {object} The deserialized object. */ export function deserialize<T>(text: string, settings?: DeserializerOptions): T; /** * Clone the object. * @param {object} obj The object to clone. * @param {object} [settings] Settings can specify any of the options allowed by the serialize or deserialize methods. * @return {object} The new clone. */ export function clone<T>(obj: T, settings?: Object): T; } /** * Layers the widget sugar on top of the composition system. * @requires system * @requires composition * @requires jquery * @requires knockout */ declare module 'plugins/widget' { interface WidgetSettings { kind: string; model?: any; view?: any; } /** * Creates a ko binding handler for the specified kind. * @param {string} kind The kind to create a custom binding handler for. */ export function registerKind(kind: string): void; /** * Maps views and module to the kind identifier if a non-standard pattern is desired. * @param {string} kind The kind name. * @param {string} [viewId] The unconventional view id to map the kind to. * @param {string} [moduleId] The unconventional module id to map the kind to. */ export function mapKind(kind: string, viewId?: string, moduleId?: string): void; /** * Maps a kind name to it's module id. First it looks up a custom mapped kind, then falls back to `convertKindToModulePath`. * @param {string} kind The kind name. * @returns {string} The module id. */ export function mapKindToModuleId(kind: string): string; /** * Converts a kind name to it's module path. Used to conventionally map kinds who aren't explicitly mapped through `mapKind`. * @param {string} kind The kind name. * @returns {string} The module path. */ export function convertKindToModulePath(kind: string): string; /** * Maps a kind name to it's view id. First it looks up a custom mapped kind, then falls back to `convertKindToViewPath`. * @param {string} kind The kind name. * @returns {string} The view id. */ export function mapKindToViewId(kind: string): string; /** * Converts a kind name to it's view id. Used to conventionally map kinds who aren't explicitly mapped through `mapKind`. * @param {string} kind The kind name. * @returns {string} The view id. */ export function convertKindToViewPath(kind: string): string; /** * Creates a widget. * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the target element for the widget. * @param {object} settings The widget settings. * @param {object} [bindingContext] The current binding context. */ export function create(element: HTMLElement, settings: WidgetSettings, bindingContext?: KnockoutBindingContext): void; } /** * Connects the history module's url and history tracking support to Durandal's activation and composition engine allowing you to easily build navigation-style applications. * @requires system * @requires app * @requires activator * @requires events * @requires composition * @requires history * @requires knockout * @requires jquery */ declare module 'plugins/router' { var theModule: DurandalRootRouter; export = theModule; } interface DurandalEventSubscription { /** * Attaches a callback to the event subscription. * @param {function} callback The callback function to invoke when the event is triggered. * @param {object} [context] An object to use as `this` when invoking the `callback`. * @chainable */ then(thenCallback: Function, context?: any): DurandalEventSubscription; /** * Attaches a callback to the event subscription. * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated. * @param {object} [context] An object to use as `this` when invoking the `callback`. * @chainable */ on(thenCallback: Function, context?: any): DurandalEventSubscription; /** * Cancels the subscription. * @chainable */ off(): DurandalEventSubscription; } interface DurandalEventSupport<T> { /** * Creates a subscription or registers a callback for the specified event. * @param {string} events One or more events, separated by white space. * @returns {Subscription} A subscription is returned. */ on(events: string): DurandalEventSubscription; /** * Creates a subscription or registers a callback for the specified event. * @param {string} events One or more events, separated by white space. * @param {function} [callback] The callback function to invoke when the event is triggered. * @param {object} [context] An object to use as `this` when invoking the `callback`. * @returns {Events} The events object is returned for chaining. */ on(events: string, callback: Function, context?: any): T; /** * Removes the callbacks for the specified events. * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed. * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed. * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed. * @chainable */ off(events: string, callback: Function, context?: any): T; /** * Triggers the specified events. * @param {string} [events] One or more events, separated by white space to trigger. * @chainable */ trigger(events: string, ...eventArgs: any[]): T; /** * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object. * @param {string} events One or more events, separated by white space to trigger by invoking the returned function. * @returns {function} Calling the function will invoke the previously specified events on the events object. */ proxy(events: string): Function; } interface DurandalEventModule { new (): DurandalEventSupport<Object>; includeIn(targetObject: any): void; } interface DialogButton { text: string; value: any; } interface DurandalAppModule extends DurandalEventSupport<DurandalAppModule> { /** * The title of your application. */ title: string; /** * Shows a dialog via the dialog plugin. * @param {object|string} obj The object (or moduleId) to display as a dialog. * @param {object} [activationData] The data that should be passed to the object upon activation. * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified. * @returns {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. */ showDialog(obj: any, activationData?: any, context?: string): DurandalPromise<any>; /** * Closes the dialog associated with the specified object. via the dialog plugin. * @param {object} obj The object whose dialog should be closed. * @param {object} results* The results to return back to the dialog caller after closing. */ closeDialog(obj: any, ...results: any[]): void; /** * Shows a message box via the dialog plugin. * @param {string} message The message to display in the dialog. * @param {string} [title] The title message. * @param {string[]} [options] The options to provide to the user. * @param {boolean} [autoclose] Automatically close the the message box when clicking outside? * @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles. * @returns {Promise} A promise that resolves when the message box is closed and returns the selected option. */ showMessage(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object): DurandalPromise<string>; /** * Shows a message box. * @param {string} message The message to display in the dialog. * @param {string} [title] The title message. * @param {DialogButton[]} [options] The options to provide to the user. * @param {boolean} [autoclose] Automatically close the the message box when clicking outside? * @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles. * @returns {Promise} A promise that resolves when the message box is closed and returns the selected option. */ showMessage(message: string, title?: string, options?: DialogButton[], autoclose?: boolean, settings?: Object): DurandalPromise<any>; /** * Configures one or more plugins to be loaded and installed into the application. * @method configurePlugins * @param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin. * @param {string} [baseUrl] The base url to load the plugins from. */ configurePlugins(config: Object, baseUrl?: string): void; /** * Starts the application. * @returns {promise} */ start(): DurandalPromise<any>; /** * Sets the root module/view for the application. * @param {string} root The root view or module. * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. * @param {string} [applicationHost] The application host element id. By default the id 'applicationHost' will be used. */ setRoot(root: any, transition?: string, applicationHost?: string): void; /** * Sets the root module/view for the application. * @param {string} root The root view or module. * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. * @param {string} [applicationHost] The application host element. By default the id 'applicationHost' will be used. */ setRoot(root: any, transition?: string, applicationHost?: HTMLElement): void; } interface DurandalActivatorSettings { /** * The default value passed to an object's deactivate function as its close parameter. * @default true */ closeOnDeactivate: boolean; /** * Lower-cased words which represent a truthy value. * @default ['yes', 'ok', 'true'] */ affirmations: string[]; /** * Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array. * @param {object} value * @returns {boolean} */ interpretResponse(value: any): boolean; /** * Determines whether or not the current item and the new item are the same. * @param {object} currentItem * @param {object} newItem * @param {object} currentActivationData * @param {object} newActivationData * @returns {boolean} */ areSameItem(currentItem: any, newItem: any, currentActivationData: any, newActivationData: any): boolean; /** * Called immediately before the new item is activated. * @param {object} newItem */ beforeActivate(newItem: any): any; /** * Called immediately after the old item is deactivated. * @param {object} oldItem The previous item. * @param {boolean} close Whether or not the previous item was closed. * @param {function} setter The activate item setter function. */ afterDeactivate(oldItem: any, close: boolean, setter: Function): void; } interface DurandalActivator<T> extends KnockoutComputed<T> { /** * The settings for this activator. */ settings: DurandalActivatorSettings; /** * An observable which indicates whether or not the activator is currently in the process of activating an instance. * @returns {boolean} */ isActivating: KnockoutObservable<boolean>; /** * Determines whether or not the specified item can be deactivated. * @param {object} item The item to check. * @param {boolean} close Whether or not to check if close is possible. * @returns {promise} */ canDeactivateItem(item: T, close: boolean): DurandalPromise<boolean>; /** * Deactivates the specified item. * @param {object} item The item to deactivate. * @param {boolean} close Whether or not to close the item. * @returns {promise} */ deactivateItem(item: T, close: boolean): DurandalPromise<boolean>; /** * Determines whether or not the specified item can be activated. * @param {object} item The item to check. * @param {object} activationData Data associated with the activation. * @returns {promise} */ canActivateItem(newItem: T, activationData?: any): DurandalPromise<boolean>; /** * Activates the specified item. * @param {object} newItem The item to activate. * @param {object} newActivationData Data associated with the activation. * @returns {promise} */ activateItem(newItem: T, activationData?: any): DurandalPromise<boolean>; /** * Determines whether or not the activator, in its current state, can be activated. * @returns {promise} */ canActivate(): DurandalPromise<boolean>; /** * Activates the activator, in its current state. * @returns {promise} */ activate(): DurandalPromise<boolean>; /** * Determines whether or not the activator, in its current state, can be deactivated. * @returns {promise} */ canDeactivate(close: boolean): DurandalPromise<boolean>; /** * Deactivates the activator, in its current state. * @returns {promise} */ deactivate(close: boolean): DurandalPromise<boolean>; /** * Adds canActivate, activate, canDeactivate and deactivate functions to the provided model which pass through to the corresponding functions on the activator. */ includeIn(includeIn: any): void; /** * Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them. */ forItems(items: any[]): DurandalActivator<T>; } interface DurandalHistoryOptions { /** * The function that will be called back when the fragment changes. */ routeHandler?: (fragment: string) => void; /** * The url root used to extract the fragment when using push state. */ root?: string; /** * Use hash change when present. * @default true */ hashChange?: boolean; /** * Use push state when present. * @default false */ pushState?: boolean; /** * Prevents loading of the current url when activating history. * @default false */ silent?: boolean; /** * Override default history init behavior by navigating directly to this route. */ startRoute?: string; } interface DurandalNavigationOptions { trigger: boolean; replace: boolean; } interface DurandalRouteConfiguration { title?: any; moduleId?: string; hash?: string; route?: string | string[]; routePattern?: RegExp; isActive?: KnockoutComputed<boolean>; nav?: any; hasChildRoutes?: boolean; viewUrl?: string; } interface DurandalRouteInstruction { fragment: string; queryString: string; config: DurandalRouteConfiguration; params: any[]; queryParams: { [index: string]: any }; } interface DurandalRelativeRouteSettings { moduleId?: string; route?: string; fromParent?: boolean; dynamicHash?: string; } interface DurandalRouterBase<T> extends DurandalEventSupport<T> { /** * The route handlers that are registered. Each handler consists of a `routePattern` and a `callback`. */ handlers: { routePattern: RegExp; callback: (fragment: string) => void; }[]; /** * The route configs that are registered. */ routes: DurandalRouteConfiguration[]; /** * The active item/screen based on the current navigation state. */ activeItem: DurandalActivator<any>; /** * The route configurations that have been designated as displayable in a nav ui (nav:true). */ navigationModel: KnockoutObservableArray<DurandalRouteConfiguration>; /** * Indicates that the router (or a child router) is currently in the process of navigating. */ isNavigating: KnockoutComputed<boolean>; /** * An observable surfacing the active routing instruction that is currently being processed or has recently finished processing. * The instruction object has `config`, `fragment`, `queryString`, `params` and `queryParams` properties. */ activeInstruction: KnockoutObservable<DurandalRouteInstruction>; /** * Parses a query string into an object. * @param {string} queryString The query string to parse. * @returns {object} An object keyed according to the query string parameters. */ parseQueryString(queryString: string): Object; /** * Add a route to be tested when the url fragment changes. * @param {RegEx} routePattern The route pattern to test against. * @param {function} callback The callback to execute when the route pattern is matched. */ route(routePattern: RegExp, callback: (fragment: string) => void): void; /** * Attempt to load the specified URL fragment. If a route succeeds with a match, returns `true`. If no defined routes matches the fragment, returns `false`. * @param {string} fragment The URL fragment to find a match for. * @returns {boolean} True if a match was found, false otherwise. */ loadUrl(fragment: string): boolean; /** * Updates the document title based on the activated module instance, the routing instruction and the app.title. * @param {object} instance The activated module. * @param {object} instruction The routing instruction associated with the action. It has a `config` property that references the original route mapping config. */ updateDocumentTitle(instance: Object, instruction: DurandalRouteInstruction): void; /** * Save a fragment into the hash history, or replace the URL state if the * 'replace' option is passed. You are responsible for properly URL-encoding * the fragment in advance. * The options object can contain `trigger: false` if you wish to not have the * route callback be fired, or `replace: true`, if * you wish to modify the current URL without adding an entry to the history. * @param {string} fragment The url fragment to navigate to. * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. * @return {boolean} Returns true/false from loading the url. */ navigate(fragment: string, trigger?: boolean): boolean; /** * Save a fragment into the hash history, or replace the URL state if the * 'replace' option is passed. You are responsible for properly URL-encoding * the fragment in advance. * The options object can contain `trigger: false` if you wish to not have the * route callback be fired, or `replace: true`, if * you wish to modify the current URL without adding an entry to the history. * @param {string} fragment The url fragment to navigate to. * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. * @return {boolean} Returns true/false from loading the url. */ navigate(fragment: string, options: DurandalNavigationOptions): boolean; /** * Navigates back in the browser history. */ navigateBack(): void; /** * Converts a route to a hash suitable for binding to a link's href. * @param {string} route * @returns {string} The hash. */ convertRouteToHash(route: string): string; /** * Converts a route to a module id. This is only called if no module id is supplied as part of the route mapping. * @param {string} route * @returns {string} The module id. */ convertRouteToModuleId(route: string): string; /** * Converts a route to a displayable title. This is only called if no title is specified as part of the route mapping. * @method convertRouteToTitle * @param {string} route * @returns {string} The title. */ convertRouteToTitle(route: string): string; /** * Maps route patterns to modules. * @param {string} route A route. * @chainable */ map(route: string): T; /** * Maps route patterns to modules. * @param {string} route A route pattern. * @param {string} moduleId The module id to map the route to. * @chainable */ map(route: string, moduleId: string): T; /** * Maps route patterns to modules. * @param {RegExp} route A route pattern. * @param {string} moduleId The module id to map the route to. * @chainable */ map(route: RegExp, moduleId: string): T; /** * Maps route patterns to modules. * @param {string} route A route pattern. * @param {RouteConfiguration} config The route's configuration. * @chainable */ map(route: string, config: DurandalRouteConfiguration): T; /** * Maps route patterns to modules. * @method map * @param {RegExp} route A route pattern. * @param {RouteConfiguration} config The route's configuration. * @chainable */ map(route: RegExp, config: DurandalRouteConfiguration): T; /** * Maps route patterns to modules. * @param {RouteConfiguration} config The route's configuration. * @chainable */ map(config: DurandalRouteConfiguration): T; /** * Maps route patterns to modules. * @param {RouteConfiguration[]} configs An array of route configurations. * @chainable */ map(configs: DurandalRouteConfiguration[]): T; /** * Builds an observable array designed to bind a navigation UI to. The model will exist in the `navigationModel` property. * @param {number} defaultOrder The default order to use for navigation visible routes that don't specify an order. The defualt is 100. * @chainable */ buildNavigationModel(defaultOrder?: number): T; /** * Configures the router to map unknown routes to modules at the same path. * @chainable */ mapUnknownRoutes(): T; /** * Configures the router use the specified module id for all unknown routes. * @param {string} notFoundModuleId Represents the module id to route all unknown routes to. * @param {string} [replaceRoute] Optionally provide a route to replace the url with. * @chainable */ mapUnknownRoutes(notFoundModuleId: string, replaceRoute?: string): T; /** * Configures how the router will handle unknown routes. * @param {function} callback Called back with the route instruction containing the route info. The function can then modify the instruction by adding a moduleId and the router will take over from there. * @chainable */ mapUnknownRoutes(callback: (instruction: DurandalRouteInstruction) => void): T; /** * Configures how the router will handle unknown routes. * @param {RouteConfiguration} config The route configuration to use for unknown routes. * @chainable */ mapUnknownRoutes(config: DurandalRouteConfiguration): T; /** * Resets the router by removing handlers, routes, event handlers and previously configured options. * @chainable */ reset(): T; /** * Makes all configured routes and/or module ids relative to a certain base url. * @param {string} settings The value is used as the base for routes and module ids. * @chainable */ makeRelative(settings: string): T; /** * Makes all configured routes and/or module ids relative to a certain base url. * @param {RelativeRouteSettings} settings If an object, you can specify `route` and `moduleId` separately. In place of specifying route, you can set `fromParent:true` to make routes automatically relative to the parent router's active route. * @chainable */ makeRelative(settings: DurandalRelativeRouteSettings): T; /** * Creates a child router. * @returns {Router} The child router. */ createChildRouter(): T; /** * Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting. * @param {object} instance The module instance that is about to be activated by the router. * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties. * @returns {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types. */ guardRoute?: (instance: Object, instruction: DurandalRouteInstruction) => DurandalPromise<boolean | string> | boolean | string; /** * Parent router of the current child router. */ parent?: DurandalRouter; } interface DurandalRouter extends DurandalRouterBase<DurandalRouter> { } interface DurandalRootRouter extends DurandalRouterBase<DurandalRootRouter> { /** * Makes the RegExp generated for routes case sensitive, rather than the default of case insensitive. */ makeRoutesCaseSensitive(): void; /** * Activates the router and the underlying history tracking mechanism. * @returns {Promise} A promise that resolves when the router is ready. */ activate(options?: DurandalHistoryOptions): DurandalPromise<any>; /** * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. */ deactivate(): void; /** * Installs the router's custom ko binding handler. */ install(): void; }
the_stack
import { ExecFileException } from 'child_process' import * as fs from 'fs' import * as path from 'path' import { option } from 'fp-ts' import { Tail } from 'tail' import * as vscode from 'vscode' import * as AW2E from '@shared/activity-webview-to-extension' import * as E2AW from '@shared/extension-to-activity-webview' import * as E2VCGW from '@shared/extension-to-reopt-vcg-webview' import * as Interfaces from '@shared/interfaces' import * as WorkspaceState from '@shared/workspace-state' import { createReoptProject } from './create-reopt-project' import { openReoptProject, openReoptProjectViaDialog, } from './open-reopt-project' import * as reopt from './reopt' import * as reoptVCG from './reopt-vcg' async function openOutputFile(outputFile: string): Promise<void> { const absoluteUri = vscode.Uri.file(path.resolve(outputFile)) const doc = await vscode.workspace.openTextDocument(absoluteUri) await vscode.window.showTextDocument(doc, { preview: false, }) } /** Just like vscode.OutputChannel, but the 'dispose' method is hidden. */ export type PrivateOutputChannel = Pick<vscode.OutputChannel, 'appendLine' | 'show'> /** * When the user switches reopt projects, we drop the output channel for the * project to be closed, and open a new output channel for the project to be * opened. This way, the messages in the output pane are always relevant to the * currently opened project. */ export type ReplaceOutputChannel = (newChannel: string) => PrivateOutputChannel function makeDisplayError( replaceOutputChannel: ReplaceOutputChannel, ): (err: ExecFileException) => void { return (err) => { const channel = replaceOutputChannel('reopt error') // in my experience so far, the 'stack' has strictly more information // when present if (err.stack) { channel.appendLine(err.stack) } else { channel.appendLine(err.message) } channel.appendLine('The following command errored, scroll up for error messages.') channel.appendLine(err.cmd || 'No command, please report.') channel.show() } } /** * Returns a string that can be displayed to the user while reopt is running in * a given mode. * @param reoptMode - Mode reopt is running in * @returns User-friendly string description */ function getTitleForReoptMode( reoptMode: reopt.ReoptMode, ): string { switch (reoptMode) { case reopt.ReoptMode.GenerateCFG: return 'Generating CFG...' case reopt.ReoptMode.GenerateDisassembly: return 'Generating disassembly...' case reopt.ReoptMode.GenerateFunctions: return 'Generating functions...' case reopt.ReoptMode.GenerateLLVM: return 'Generating LLVM...' } } /** * Contains the shared logic for calling reopt and updating the IDE state, for * all interesting modes in which we can run reopt. * @param context - VSCode extension context * @param diagnosticCollection - current diagnostic collection * @param replaceOutputChannel - cf. 'ReplaceOutputChannel' * @returns Given a reopt mode, returns a function that runs reopt in that mode, * and displays the results. */ function makeReoptGenerate( context: vscode.ExtensionContext, diagnosticCollection: vscode.DiagnosticCollection, replaceOutputChannel: ReplaceOutputChannel, reoptVCGWebviewPromise: Promise<Interfaces.ReoptVCGWebview>, ): (reoptMode: reopt.ReoptMode) => void { return (reoptMode) => { vscode.window .withProgress( { location: vscode.ProgressLocation.Notification, title: getTitleForReoptMode(reoptMode), cancellable: true, }, // TODO: we can probably kill the child process upon cancellation (_progress, _token) => reopt.runReoptToGenerateFile(context, reoptMode) ) .then( // on fulfilled processOutputAndEvents(context, diagnosticCollection, reoptMode, reoptVCGWebviewPromise), // on rejected makeDisplayError(replaceOutputChannel), ) } } /** * * @param context - VSCode extension context * @param webview - Extension webview * @param diagnosticCollection - Current diagnostic collection * @param replaceConfigurationWatcher - While a reopt project is open, we have a * filesystem watcher for its project file. When a different project is open, * we call this to replace the old watcher with a new one. * @param replaceOutputChannel - see [[ReplaceOutputChannel]] * @returns */ export function makeMessageHandler( context: vscode.ExtensionContext, activityWebview: Interfaces.ActivityWebview, diagnosticCollection: vscode.DiagnosticCollection, reoptVCGWebviewPromise: Promise<Interfaces.ReoptVCGWebview>, replaceConfigurationWatcher: (w?: vscode.FileSystemWatcher) => void, replaceOutputChannel: ReplaceOutputChannel, ): (m: AW2E.ActivityWebviewToExtension) => Promise<void> { const reoptGenerate = makeReoptGenerate( context, diagnosticCollection, replaceOutputChannel, reoptVCGWebviewPromise, ) const resetProject = () => { WorkspaceState.clearVariable(context, WorkspaceState.reoptProjectConfiguration) WorkspaceState.clearVariable(context, WorkspaceState.reoptProjectFile) WorkspaceState.clearVariable(context, WorkspaceState.reoptVCGEntries) activityWebview.postMessage( { tag: E2AW.closedProjectTag } as E2AW.ClosedProject ) reoptVCGWebviewPromise.then(w => w.postMessage( { tag: E2VCGW.Tags.setReoptVCGEntries, entries: [], } as E2VCGW.SetReoptVCGEntries ) ) } return async (message: AW2E.ActivityWebviewToExtension) => { switch (message.tag) { case AW2E.closeProject: { resetProject() replaceConfigurationWatcher(undefined) return } case AW2E.createProjectFile: { resetProject() const reoptProjectFile = await createReoptProject() const watcher = await openReoptProject(context, activityWebview, reoptProjectFile) replaceConfigurationWatcher(watcher) return } case AW2E.generateCFG: { reoptGenerate(reopt.ReoptMode.GenerateCFG) return } // case W2E.generateDisassembly: { // reoptGenerate(reopt.ReoptMode.GenerateObject) // return // } case AW2E.generateFunctions: { reoptGenerate(reopt.ReoptMode.GenerateFunctions) return } case AW2E.generateLLVM: { reoptGenerate(reopt.ReoptMode.GenerateLLVM) return } case AW2E.jumpToSymbol: { const { fsPath, range } = message.symbol const doc = await vscode.workspace.openTextDocument(fsPath) const editor = await vscode.window.showTextDocument(doc) const startPosition = new vscode.Position(range.start.line, range.start.character) const endPosition = new vscode.Position(range.end.line, range.end.character) // Move symbol into view and select it editor.selection = new vscode.Selection(startPosition, endPosition) editor.revealRange( new vscode.Range(startPosition, endPosition), vscode.TextEditorRevealType.AtTop, ) return } case AW2E.openProject: { resetProject() const watcher = await openReoptProjectViaDialog(context, activityWebview) replaceConfigurationWatcher(watcher) return } case AW2E.showProjectFile: { const projectFile = WorkspaceState.readReoptProjectFile(context) if (projectFile === undefined) { // this should not be possible, but just in case... vscode.window.showErrorMessage( 'Could not show project file: please reopen the project.', ) return } const doc = await vscode.workspace.openTextDocument(projectFile) await vscode.window.showTextDocument(doc) return } // forces exhaustivity checking default: { const exhaustiveCheck: never = message throw new Error(`Unhandled color case: ${exhaustiveCheck}`) } } } } /** * Reopt generates an events file when running. This processes it, displaying * relevant information to the user at the end of a run: what errors happened in * the process and where/why. * @param context - VSCode extension context * @param diagnosticsCollection - Current diagnostics collection * @param eventsFile - The generated events file */ async function processEventsFile( context: vscode.ExtensionContext, diagnosticsCollection: vscode.DiagnosticCollection, eventsFile: fs.PathLike, ): Promise<void> { // We need the disassembly file to show errors. This makes sure that it has // been generated. const disassemblyFile = await reopt.runReoptToGenerateDisassembly(context) reopt.displayReoptEventsAsDiagnostics( context, diagnosticsCollection, disassemblyFile, eventsFile, ) } function processOutputAndEvents( context: vscode.ExtensionContext, diagnosticCollection: vscode.DiagnosticCollection, reoptMode: reopt.ReoptMode, reoptVCGWebviewPromise: Promise<Interfaces.ReoptVCGWebview>, ): (files: Interfaces.OutputAndEventsFiles) => Promise<void> { return async ({ outputFile, eventsFile, }) => { openOutputFile(outputFile) processEventsFile(context, diagnosticCollection, eventsFile) // Then, if the file was LLVM, we can run reopt-vcg if (reoptMode !== reopt.ReoptMode.GenerateLLVM) { return } const projectConfiguration = WorkspaceState.readReoptProjectConfiguration(context) if (!projectConfiguration) { return } const projectName = projectConfiguration.name const annotationsFile = projectConfiguration.annotations if (option.isNone(projectName)) { return } // Cannot run reopt-vcg if there is no annotations file if (option.isNone(annotationsFile)) { vscode.window.showErrorMessage( 'Not running reopt-vcg because the configuration does not specify an annotations file.' ) return } const workingDirectory = path.dirname(projectConfiguration.binaryFile) const resolvedAnnotationsFile = path.resolve(workingDirectory, annotationsFile.value) if (!fs.existsSync(resolvedAnnotationsFile)) { vscode.window.showErrorMessage( `Not running reopt-vcg because the annotations file does not exist: ${annotationsFile.value} resolved to ${resolvedAnnotationsFile}` ) return } // We also need a handler to the reopt-vcg webview to send the results // to. // FIXME: I'm worried that if the user has never clicked on the panel // that shows the result, we will stay here forever. const webview = await reoptVCGWebviewPromise // Tell the webview to forget about pre-existing entries webview.postMessage({ tag: E2VCGW.Tags.setReoptVCGEntries, entries: [], } as E2VCGW.SetReoptVCGEntries) const jsonsFile = reopt.replaceExtensionWith('jsons')(annotationsFile.value) const resolvedJSONsFile = path.resolve(workingDirectory, jsonsFile) // Since we are going to start reading the file in parallel with // reopt-vcg starting to write into it, we better make sure it does not // contain old lines! fs.closeSync(fs.openSync(resolvedJSONsFile, 'w')) const entries: Interfaces.ReoptVCGEntry[] = [] WorkspaceState.writeReoptVCGEntries(context, entries) /** * WARNING: Make sure to `unwatch` the file when reopt-vcg is done, or * you will have multiple watchers at the same time! */ const tail = new Tail(resolvedJSONsFile, { fromBeginning: true }) tail.on('line', line => { const entry = JSON.parse(line) entries.push(entry) WorkspaceState.writeReoptVCGEntries(context, entries) webview.postMessage({ tag: E2VCGW.Tags.addReoptVCGEntry, entry, } as E2VCGW.AddReoptVCGEntry) }) vscode.window .withProgress( { location: vscode.ProgressLocation.Notification, title: 'Running reopt-vcg', cancellable: true, }, // TODO: we can probably kill the child process upon cancellation (_progress, _token) => ( reoptVCG.runReoptVCG( context, { annotationsFile: annotationsFile.value, jsonsFile, }, ).finally(() => { tail.unwatch() }) ) ) } }
the_stack
// <copyright file="submit-idea.tsx" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> import * as React from "react"; import { WithTranslation, withTranslation } from "react-i18next"; import * as microsoftTeams from "@microsoft/teams-js"; import { Text, Flex, Provider, Label, Input, AddIcon, Loader, Image, Button, CloseIcon, InfoIcon, TextArea, Dropdown, TrashCanIcon } from "@fluentui/react-northstar"; import { TFunction } from "i18next"; import { IdeaEntity, ApprovalStatus } from "../models/idea"; import { isNullorWhiteSpace } from "../../helpers/helper"; import { ICategoryDetails } from "../models/category"; import { getAllCategories } from "../../api/category-api"; import { addNewPostContent } from "../../api/idea-api"; import { createBrowserHistory } from "history"; import Constants from "../../constants/resources"; import "../../styles/submit-idea.css"; interface IState { loading: boolean, selectedCategory: string | undefined, categories: Array<ICategoryDetails>, theme: string; tagValidation: ITagValidationParameters; tagsList: Array<string>; tag: string; documentsList: Array<string>; documentLink: string; isTitlePresent: boolean, isDescriptionPresent: boolean, isCategorySelected: boolean, isLinkValid: boolean, submitLoading: boolean, ideaTitle: string, ideaDescription: string, alertMessage: string, alertType: number, showAlert: boolean, isIdeaSubmitedsuccessfully: boolean, } export interface ITagValidationParameters { isEmpty: boolean; isExisting: boolean; isLengthValid: boolean; isTagsCountValid: boolean; containsSemicolon: boolean; } const browserHistory = createBrowserHistory({ basename: "" }); class SubmitIdea extends React.Component<WithTranslation, IState> { localize: TFunction; userObjectId: string = ""; upn: string = ""; items: any; appUrl: string = (new URL(window.location.href)).origin; constructor(props) { super(props); this.localize = this.props.t; this.state = { loading: true, selectedCategory: undefined, categories: [], theme: "", isTitlePresent: true, isDescriptionPresent: true, isCategorySelected: true, isLinkValid: true, ideaTitle: "", ideaDescription: "", submitLoading: false, documentLink: "", documentsList: [], tagsList: [], tag: "", tagValidation: { isEmpty: false, isExisting: false, isLengthValid: true, isTagsCountValid: true, containsSemicolon: false }, alertMessage: "", alertType: 0, showAlert: false, isIdeaSubmitedsuccessfully: false } } public componentDidMount() { microsoftTeams.initialize(); microsoftTeams.getContext((context) => { this.userObjectId = context.userObjectId!; this.upn = context.upn!; this.setState({ theme: context.theme! }); this.getCategory(); }); } getA11SelectionMessage = { onAdd: item => { if (item) { this.setState({ selectedCategory: item, isCategorySelected: true }) }; return ""; }, }; /** *Get categories from API */ async getCategory() { let category = await getAllCategories(); if (category.status === 200 && category.data) { this.setState({ categories: category.data, }); } else { } this.setState({ loading: false }); } checkIfSubmitAllowed = () => { if (isNullorWhiteSpace(this.state.ideaTitle)) { this.setState({ isTitlePresent: false }); return false; } if (isNullorWhiteSpace(this.state.ideaDescription)) { this.setState({ isDescriptionPresent: false }); return false; } if (this.state.selectedCategory === undefined) { this.setState({ isCategorySelected: false }); return false; } return true; } /** *Check if tag is valid */ checkIfTagIsValid = () => { let validationParams: ITagValidationParameters = { isEmpty: false, isLengthValid: true, isExisting: false, isTagsCountValid: false, containsSemicolon: false }; if (this.state.tag.trim() === "") { validationParams.isEmpty = true; } if (this.state.tag.length > Constants.tagMaxLength) { validationParams.isLengthValid = false; } let tags = this.state.tagsList; let isTagExist = tags.find((tag: string) => { if (tag.toLowerCase() === this.state.tag.toLowerCase()) { return tag; } }); if (this.state.tag.split(";").length > 1) { validationParams.containsSemicolon = true; } if (isTagExist) { validationParams.isExisting = true; } if (this.state.tagsList.length < Constants.tagsMaxCount) { validationParams.isTagsCountValid = true; } this.setState({ tagValidation: validationParams }); if (!validationParams.isEmpty && !validationParams.isExisting && validationParams.isLengthValid && validationParams.isTagsCountValid && !validationParams.containsSemicolon) { return true; } return false; } /** *Sets state of tagsList by removing tag using its index. *@param index Index of tag to be deleted. */ onTagRemoveClick = (index: number) => { let tags = this.state.tagsList; tags.splice(index, 1); this.setState({ tagsList: tags }); } /** *Returns text component containing error message for empty tag input field */ private getTagError = () => { if (this.state.tagValidation.isEmpty) { return (<Text content={this.localize("emptyTagError")} className="field-error-message" error size="medium" />); } else if (!this.state.tagValidation.isLengthValid) { return (<Text content={this.localize("tagLengthError")} className="field-error-message" error size="medium" />); } else if (this.state.tagValidation.isExisting) { return (<Text content={this.localize("sameTagExistsError")} className="field-error-message" error size="medium" />); } else if (!this.state.tagValidation.isTagsCountValid) { return (<Text content={this.localize("tagsCountError")} className="field-error-message" error size="medium" />); } else if (this.state.tagValidation.containsSemicolon) { return (<Text content={this.localize("semicolonTagError")} className="field-error-message" error size="medium" />); } return (<></>); } /** *Sets state of tagsList by adding new tag. */ onTagAddClick = () => { if (this.checkIfTagIsValid()) { let tagList = this.state.tagsList; tagList.push(this.state.tag.toLowerCase()); this.setState({ tagsList: tagList, tag: "" }); } } /** * Adds tag when enter key is pressed * @param event Object containing event details */ onTagKeyDown = (event: any) => { if (event.key === 'Enter') { this.onTagAddClick(); } } /** *Sets tag state. *@param tag Tag string */ onTagChange = (tag: string) => { this.setState({ tag: tag }) } /** *Sets title state. *@param title Title string */ onTitleChange = (value: string) => { this.setState({ ideaTitle: value, isTitlePresent: true }); } /** *Sets description state. *@param description Description string */ onDescriptionChange = (description: string) => { this.setState({ ideaDescription: description, isDescriptionPresent: true }); } /** *Sets document link state. *@param tag Tag string */ onDocumentChange = (link: string) => { this.setState({ documentLink: link }) } /** *Sets state for showing alert notification. *@param content Notification message *@param type Boolean value indicating 1- Success */ showAlert = (content: string, type: number) => { this.setState({ alertMessage: content, alertType: type, showAlert: true }, () => { setTimeout(() => { this.setState({ showAlert: false }) }, 4000); }); } /** *Sets state for hiding alert notification. */ hideAlert = () => { this.setState({ showAlert: false }) } /** *Sets state of documentsList by adding new document. */ onDocumentAddClick = () => { if (this.validateLink()) { let documentsList = this.state.documentsList; documentsList.push(this.state.documentLink); this.setState({ documentsList: documentsList, documentLink: "" }); } } handleSubmit = () => { if (this.checkIfSubmitAllowed()) { this.setState({ submitLoading: true }); let category = this.state.categories.filter(row => row.categoryName === this.state.selectedCategory).shift(); let idea: IdeaEntity = { category: this.state.selectedCategory, categoryId: category?.categoryId, createdByObjectId: this.userObjectId, description: this.state.ideaDescription, title: this.state.ideaTitle, documentLinks: JSON.stringify(this.state.documentsList), tags: this.state.tagsList.join(";"), status: ApprovalStatus.Pending, totalVotes: undefined, approvedOrRejectedByName: undefined, approverOrRejecterUserId: undefined, createdByName: undefined, createdByUserPrincipalName: this.upn, createdDate: undefined, feedback: undefined, ideaId: undefined, updatedDate: undefined } // Post idea this.createNewIdea(idea); } } /** *Get ideas from API */ async createNewIdea(idea: any) { let response = await addNewPostContent(idea); if (response.status === 200 && response.data) { this.showAlert(this.localize("ideaSubmittedSuccessMessage"), 1); this.setState({ submitLoading: false, isIdeaSubmitedsuccessfully: true }); } } validateLink = () => { let expression = Constants.urlValidationRegEx; let regex = new RegExp(expression); if (this.state.documentLink.match(regex)) { this.setState({ isLinkValid: true }) return true; } else { this.setState({ isLinkValid: false }) return false; } } /** * Adds document link when enter key is pressed * @param event Object containing event details */ onDocumentKeyDown = (event: any) => { if (event.key === 'Enter') { this.onDocumentAddClick(); } } onDocumentRemoveClick = (index: number) => { let documents = this.state.documentsList; documents.splice(index, 1); this.setState({ documentsList: documents }); } /** *Returns text component containing error message for failed name field validation *@param {boolean} isValuePresent Indicates whether value is present */ private getRequiredFieldError = (isValuePresent: boolean) => { if (!isValuePresent) { return (<Text content={this.localize('fieldRequiredMessage')} className="field-error-message" error size="medium" />); } return (<></>); } /** *Returns text component containing error message for failed name field validation *@param {boolean} isValidLink Indicates whether value is present */ private getInValidLinkError = (isValidLink: boolean) => { if (!isValidLink) { return (<Text content={this.localize('inValidLinkError')} className="field-error-message" error size="medium" />); } return (<></>); } /** * Renders the component. */ public render(): JSX.Element { if (!this.state.loading && !this.state.isIdeaSubmitedsuccessfully) { return ( <Provider> <div className="module-container"> <Flex className="tab-container" column gap="gap.smaller"> <Flex className="top-spacing"> <Text size="small" content={"*" + this.localize("titleFormLabel")} /> <Flex.Item push> {this.getRequiredFieldError(this.state.isTitlePresent)} </Flex.Item> </Flex> <Flex gap="gap.smaller"> <Flex.Item> <Input fluid maxLength={200} placeholder={this.localize("nameIdeaPlaceholder")} value={this.state.ideaTitle} onChange={(event: any) => this.onTitleChange(event.target.value)} /> </Flex.Item> </Flex> <Flex className="add-toppadding"> <Text size="small" content={"*" + this.localize("synopsisTitle")} /> <Flex.Item push> {this.getRequiredFieldError(this.state.isDescriptionPresent)} </Flex.Item> </Flex> <Flex> <Flex.Item> <TextArea maxLength={500} className="response-text-area" fluid value={this.state.ideaDescription} placeholder={this.localize("synopsisPlaceholder")} onChange={(event: any) => this.onDescriptionChange(event.target.value)} /> </Flex.Item> </Flex> <Flex className="add-toppadding"> <Text size="small" content={"*" + this.localize("category")} /> <Flex.Item push> {this.getRequiredFieldError(this.state.isCategorySelected)} </Flex.Item> </Flex> <Dropdown fluid items={this.state.categories.map((category) => category.categoryName)} value={this.state.selectedCategory} placeholder={this.localize("categoryPlaceholder")} getA11ySelectionMessage={this.getA11SelectionMessage} /> <div> <Flex gap="gap.smaller" className="add-toppadding"> <Text size="small" content={this.localize("tagsFormLabel")} /> <InfoIcon outline className="info-icon" title={this.localize("tagInfo")} size="small" /> <Flex.Item push> <div> {this.getTagError()} </div> </Flex.Item> </Flex> <Flex gap="gap.smaller" vAlign="center" className="margin-top-small" > <Input maxLength={Constants.tagMaxLength} placeholder={this.localize("tagPlaceholder")} fluid value={this.state.tag} onKeyDown={this.onTagKeyDown} onChange={(event: any) => this.onTagChange(event.target.value)} /> <Flex.Item push> <div></div> </Flex.Item> <AddIcon key="search" onClick={this.onTagAddClick} className="add-icon hover-effect" /> </Flex> <Flex gap="gap.smaller" vAlign="center"> <div> { this.state.tagsList.map((value: string, index) => { if (value.trim().length > 0) { return ( <Label circular content={<Text className="tag-text-form" content={value.trim()} title={value.trim()} size="small" />} className={this.state.theme === Constants.dark ? "tags-label-wrapper-dark" : "tags-label-wrapper"} icon={<CloseIcon key={index} className="hover-effect" onClick={() => this.onTagRemoveClick(index)} />} /> ) } }) } </div> </Flex> </div> <div> <Flex gap="gap.smaller" className="add-toppadding"> <Text size="small" content={this.localize("documentsFormLabel")} /> <Flex.Item push> <div> {this.getInValidLinkError(this.state.isLinkValid)} </div> </Flex.Item> </Flex> <Flex gap="gap.smaller" className="margin-top-small" vAlign="center"> <Input placeholder={this.localize("documentPlaceholder")} fluid value={this.state.documentLink} onKeyDown={this.onDocumentKeyDown} onChange={(event: any) => this.onDocumentChange(event.target.value)} /> <Flex.Item push> <div></div> </Flex.Item> <AddIcon key="search" onClick={this.onDocumentAddClick} className="add-icon hover-effect" /> </Flex> <div className="document-text"> { this.state.documentsList.map((value: string, index) => { if (value.trim().length > 0) { return ( <Flex vAlign="center" key={index} className="margin-top-medium"> <Text color="blue" className="document-hover" styles={{ paddingRight: "0.3rem" }} truncated content={value.trim()} /> <Flex.Item align="center"> <TrashCanIcon outline styles={{ paddingRight: "0.5rem" }} className="hover-effect" onClick={() => this.onDocumentRemoveClick(index)} /> </Flex.Item> </Flex> ) } }) } </div> </div> </Flex> <Flex className="tab-footer" hAlign="end" ><Button primary content={this.localize("submitIdeaButtonText")} onClick={this.handleSubmit} disabled={this.state.submitLoading} loading={this.state.submitLoading} /> </Flex> </div> </Provider>) } else if (this.state.isIdeaSubmitedsuccessfully) { return ( <div className="submit-idea-success-message-container"> <Flex column gap="gap.small"> <Flex hAlign="center" className="margin-space"><Image className="preview-image-icon" fluid src={this.appUrl + "/Artifacts/successIcon.png"} /></Flex> <Flex hAlign="center" className="space" column> <Text weight="bold" content={this.localize("ideaPostedSuccessHeading")} size="medium" /> <Text content={this.localize("ideaSubmittedSuccessMessage")} size="medium" /> </Flex> </Flex> </div>) } else { return <Loader /> } } } export default withTranslation()(SubmitIdea)
the_stack
import electron from 'electron'; import memoize from 'memoize-one'; import React from 'react'; import Realm from 'realm'; import { ClassFocussedHandler, IPropertyWithName, ListFocussedHandler, IsEmbeddedTypeChecker, SingleListFocussedHandler, JsonViewerDialogExecutor, } from '..'; import { store } from '../../../store'; import { getRange } from '../../../utils'; import { canUseJsonViewer } from '../../../utils/json'; import { showError } from '../../reusable/errors'; import { ILoadingProgress } from '../../reusable/LoadingOverlay'; import { Focus, getClassName, IClassFocus } from '../focus'; import { isPrimitive } from '../primitives'; import { Content, IContentProps } from './Content'; import { ICreateObjectDialogContainerProps } from './CreateObjectDialog'; import { IDeleteObjectsDialogProps } from './DeleteObjectsDialog'; import { IOpenSelectMultipleObjectsDialogContainerProps, IOpenSelectSingleObjectDialogContainerProps, } from './SelectObjectDialog'; import { CellChangeHandler, CellClickHandler, CellContextMenuHandler, CellHighlightedHandler, CellValidatedHandler, IHighlight, ReorderingEndHandler, ReorderingStartHandler, rowHeights, RowMouseDownHandler, } from './Table'; export enum EditMode { Disabled = 'disabled', InputBlur = 'input-blur', KeyPress = 'key-press', } export enum HighlightMode { Disabled = 'disabled', Single = 'single', Multiple = 'multiple', } export type EmbeddedInfo = { parent: Realm.Object & { [key: string]: any }; key: string; }; export type CreateObjectHandler = ( className: string, values: Record<string, unknown>, embeddedInfo?: EmbeddedInfo, ) => void; export type QueryChangeHandler = (query: string) => void; export type SortingChangeHandler = (sorting: ISorting | undefined) => void; export interface ISorting { property: IPropertyWithName; reverse: boolean; } export type SelectObjectAction = | { type: 'object'; object: Realm.Object; propertyName: string } | { type: 'list'; list: Realm.List<any> }; export interface ISelectObjectForObjectDialog extends IOpenSelectSingleObjectDialogContainerProps { action: 'object'; isOpen: true; multiple: false; object: Realm.Object; propertyName: string; } export interface ISelectObjectsForListDialog extends IOpenSelectMultipleObjectsDialogContainerProps { action: 'list'; isOpen: true; list: Realm.List<any>; multiple: true; } export type ISelectObjectDialog = | ISelectObjectForObjectDialog | ISelectObjectsForListDialog | { isOpen: false }; export interface IBaseContentContainerProps { dataVersion?: number; allowCreate: boolean; editMode: EditMode; focus: Focus; highlightMode: HighlightMode; onCellClick?: CellClickHandler; onCellDoubleClick?: CellClickHandler; onCellSingleClick?: CellClickHandler; onClassFocussed?: ClassFocussedHandler; onHighlightChange?: ( highlight: IHighlight | undefined, collection: Realm.Collection<any>, ) => void; onListFocussed?: ListFocussedHandler; onSingleListFocussed?: SingleListFocussedHandler; onShowJsonViewerDialog: (value: unknown) => void; // TODO: reuse from... elsewhere progress?: ILoadingProgress; readOnly: boolean; isEmbeddedType: IsEmbeddedTypeChecker; } export interface IReadOnlyContentContainerProps extends IBaseContentContainerProps { readOnly: true; editMode: EditMode.Disabled; } export interface IReadWriteContentContainerProps extends IBaseContentContainerProps { dataVersionAtBeginning?: number; getClassFocus: (className: string) => IClassFocus; onAddColumnClick: () => void; onCancelTransaction: () => void; onCommitTransaction: () => void; onRealmChanged: () => void; permissionSidebar: boolean; readOnly: boolean; realm: Realm; } export type IContentContainerProps = | IReadOnlyContentContainerProps | IReadWriteContentContainerProps; export interface IContentContainerState { createObjectDialog: ICreateObjectDialogContainerProps; deleteObjectsDialog: IDeleteObjectsDialogProps; error?: Error; hideSystemClasses: boolean; highlight?: IHighlight; isPermissionSidebarOpen: boolean; query: string; selectObjectDialog: ISelectObjectDialog; sorting?: ISorting; } class ContentContainer extends React.Component< IContentContainerProps, IContentContainerState > { // TODO: Reset sorting, highlight and filtering (and scroll) when focus change public state: IContentContainerState = { createObjectDialog: { isOpen: false }, deleteObjectsDialog: { isOpen: false }, hideSystemClasses: !store.shouldShowSystemClasses(), isPermissionSidebarOpen: !this.props.readOnly && this.props.permissionSidebar, query: '', selectObjectDialog: { isOpen: false }, }; public latestCellValidation?: { columnIndex: number; rowIndex: number; valid: boolean; }; private removeStoreListener: (() => void) | null = null; private clickTimeout?: any; private filteredSortedResults = memoize( (results: Realm.Collection<any>, query: string, sorting?: ISorting) => { let filterError: Error | undefined; if (query) { try { results = results.filtered(query); } catch (err) { filterError = err; } } if (sorting) { const propertyName = sorting.property.name; if (propertyName) { results = results.sorted(propertyName, sorting.reverse); } } return { results, filterError }; }, ); private filteredProperties = memoize( (properties: IPropertyWithName[], hideSystemClasses: boolean) => { if (hideSystemClasses) { return properties.filter( p => !(p.objectType && p.objectType.startsWith('__')), ); } else { return properties; } }, ); private contentElement: HTMLElement | null = null; // Used to save the initial vertical coordinate when the user starts dragging to select rows private rowDragStart: { offset: number; rowIndex: number } | undefined; public componentDidUpdate( prevProps: IContentContainerProps, prevState: IContentContainerState, ) { if ( this.state.query !== prevState.query || this.state.sorting !== prevState.sorting ) { this.onResetHighlight(); } else if ( this.props.onHighlightChange && this.state.highlight !== prevState.highlight ) { const { results } = this.filteredSortedResults( this.props.focus.results, this.state.query, this.state.sorting, ); this.props.onHighlightChange(this.state.highlight, results); } } public componentDidCatch(error: Error) { // Add some more explanation to some error messages if (error.message === 'Access to invalidated List object') { error.message = 'The parent object with the list got deleted'; } this.setState({ error }); } public componentWillMount() { this.removeStoreListener = store.onDidChange( store.KEY_SHOW_SYSTEM_CLASSES, showSystemClasses => this.setState({ hideSystemClasses: !showSystemClasses }), ); } public componentWillUnmount() { document.removeEventListener('mouseup', this.onRowMouseUp); if (this.removeStoreListener) { this.removeStoreListener(); } } public render() { const props = this.getProps(); return <Content {...props} />; } public highlightObject(object: Realm.Object | null) { const highlight = this.generateHighlight(object); this.setState({ highlight }); } private contentRef = (element: HTMLElement | null) => { this.contentElement = element; }; private getProps(): IContentProps { const { results, filterError } = this.filteredSortedResults( this.props.focus.results, this.state.query, this.state.sorting, ); const focus: Focus = { ...this.props.focus, properties: this.filteredProperties( this.props.focus.properties, this.state.hideSystemClasses, ), }; const common = { contentRef: this.contentRef, dataVersion: this.props.dataVersion, error: this.state.error, filteredSortedResults: results, focus, highlight: this.state.highlight, isPermissionSidebarOpen: this.state.isPermissionSidebarOpen, onCellChange: this.onCellChange, onCellClick: this.onCellClick, onCellHighlighted: this.onCellHighlighted, onCellValidated: this.onCellValidated, onContextMenu: this.onContextMenu, onRowMouseDown: this.onRowMouseDown, onNewObjectClick: this.onNewObjectClick, onQueryChange: this.onQueryChange, onQueryHelp: this.onQueryHelp, onResetHighlight: this.onResetHighlight, onSortingChange: this.onSortingChange, query: this.state.query, queryError: filterError, sorting: this.state.sorting, }; if (this.props.readOnly) { return { ...common, editMode: EditMode.Disabled, readOnly: true, allowCreate: this.props.allowCreate, }; } else { const { dataVersion = 0, dataVersionAtBeginning = 0 } = this.props; return { ...common, changeCount: dataVersion - dataVersionAtBeginning, createObjectDialog: this.state.createObjectDialog, deleteObjectsDialog: this.state.deleteObjectsDialog, allowCreate: this.props.allowCreate, editMode: this.props.editMode, getClassFocus: this.props.getClassFocus, inTransaction: this.props.realm.isInTransaction, onAddColumnClick: this.props.onAddColumnClick, onCancelTransaction: this.props.onCancelTransaction, onCommitTransaction: this.props.onCommitTransaction, onPermissionSidebarToggle: this.props.permissionSidebar ? this.onPermissionSidebarToggle : undefined, onReorderingEnd: this.onReorderingEnd, onReorderingStart: this.onReorderingStart, realm: this.props.realm, readOnly: false, selectObjectDialog: this.state.selectObjectDialog, }; } } private onCancelCreateObjectDialog = () => { this.setState({ createObjectDialog: { isOpen: false } }); }; private onCancelDeleteObjectsDialog = () => { this.setState({ deleteObjectsDialog: { isOpen: false } }); }; private onCancelSelectObjectDialog = () => { this.setState({ selectObjectDialog: { isOpen: false } }); }; private onQueryChange = (query: string) => { this.setState({ query }); }; private onQueryHelp = () => { const url = 'https://realm.io/docs/javascript/latest/api/tutorial-query-language.html'; electron.shell.openExternal(url); }; private onResetHighlight = () => { this.setState({ highlight: undefined }); }; private onSortingChange: SortingChangeHandler = sorting => { this.setState({ sorting }); }; private generateHighlight( object: Realm.Object | null, scrollToObject = true, ): IHighlight { if (object) { const { results } = this.filteredSortedResults( this.props.focus.results, this.state.query, this.state.sorting, ); const index = results.indexOf(object); const result: IHighlight = { rows: new Set(index > -1 ? [index] : []), }; if (scrollToObject) { result.scrollTo = { center: true, row: index, }; } return result; } else { return { rows: new Set() }; } } private onCellChange: CellChangeHandler = params => { try { this.write(() => { const { parent, property, rowIndex, cellValue } = params; if (property.name !== null) { parent[rowIndex][property.name] = cellValue; } else { parent[rowIndex] = cellValue; } }); } catch (err) { showError('Failed when saving the value', err); } }; private onObjectSelect = ( selectedObjects: Realm.Object | Realm.Object[] | null, ) => { if (this.state.selectObjectDialog.isOpen) { const { selectObjectDialog } = this.state; this.write(() => { if ( selectObjectDialog.action === 'list' && Array.isArray(selectedObjects) ) { selectObjectDialog.list.push(...selectedObjects); } else if ( selectObjectDialog.action === 'object' && !Array.isArray(selectedObjects) ) { // { [p: string]: any } is needed bacause of a Realm JS type issue const parent: { [p: string]: any } = selectObjectDialog.object; parent[selectObjectDialog.propertyName] = selectedObjects; } // Close the dialog this.setState({ selectObjectDialog: { isOpen: false } }); }); } }; private onCellClick: CellClickHandler = (params, e) => { if (this.props.onCellClick) { this.props.onCellClick(params, e); } else { if (!this.latestCellValidation || this.latestCellValidation.valid) { // Ensuring that the last cell validation didn't fail if (this.clickTimeout) { clearTimeout(this.clickTimeout); this.onCellDoubleClick(params, e); this.clickTimeout = null; } else { this.clickTimeout = setTimeout(() => { this.onCellSingleClick(params, e); this.clickTimeout = null; }, 200); } } } }; private onCellSingleClick: CellClickHandler = (params, e) => { if (this.props.onCellSingleClick) { this.props.onCellSingleClick(params, e); } else { const { property, rowObject, cellValue } = params; if (!property) return; if ( canUseJsonViewer(property, cellValue) && this.props.onShowJsonViewerDialog ) { this.props.onShowJsonViewerDialog(cellValue); } else if (property.type === 'list' && this.props.onListFocussed) { this.props.onListFocussed(rowObject, property); } else if ( property.type === 'object' && property.objectType && (cellValue || property.isEmbedded) && this.props.onClassFocussed ) { // Handle Embedded Objects if (property.isEmbedded) { if (cellValue === null && property.name && property.objectType) { this.onShowCreateObjectDialog(property.objectType, { key: property.name, parent: rowObject, }); } else if (this.props.onSingleListFocussed) { this.props.onSingleListFocussed(rowObject, property); } } else { this.props.onClassFocussed(property.objectType, cellValue); } } } }; private onCellDoubleClick: CellClickHandler = (params, e) => { if (this.props.onCellDoubleClick) { this.props.onCellDoubleClick(params, e); } else { const { property, rowObject } = params; if ( property && property.type === 'object' && property.name && property.objectType && !property.isEmbedded ) { this.onShowSelectObjectDialog({ action: { type: 'object', object: rowObject, propertyName: property.name, }, className: property.objectType, isOptional: property.optional, isEmbeddedType: this.props.isEmbeddedType, onShowJsonViewerDialog: this.props.onShowJsonViewerDialog, }); } } }; private onCellHighlighted: CellHighlightedHandler = ({ rowIndex, columnIndex, }) => { this.setState({ highlight: { rows: new Set([rowIndex]), scrollTo: { column: columnIndex, row: rowIndex, }, }, }); }; private onCellValidated: CellValidatedHandler = ( rowIndex, columnIndex, valid, ) => { this.latestCellValidation = { columnIndex, rowIndex, valid, }; }; private onContextMenu: CellContextMenuHandler = ( e: React.MouseEvent<any>, params, ) => { e.preventDefault(); const { allowCreate, focus, readOnly } = this.props; const { Menu, MenuItem } = electron.remote; const contextMenu = new Menu(); if (params) { const { property, rowObject } = params; // If we clicked a property that refers to an object if ( !readOnly && property && property.type === 'object' && property.isEmbedded !== true ) { contextMenu.append( new MenuItem({ label: 'Update reference', click: () => { if (property.objectType && property.name) { this.onShowSelectObjectDialog({ action: { type: 'object', object: rowObject, propertyName: property.name, }, className: property.objectType, isOptional: property.optional, isEmbeddedType: this.props.isEmbeddedType, onShowJsonViewerDialog: this.props.onShowJsonViewerDialog, }); } }, }), ); } // If we have one or more rows highlighted - we can delete those if ( !readOnly && focus && this.state.highlight && this.state.highlight.rows.size > 0 ) { const { label, title, description } = this.generateDeleteTexts( focus, this.state.highlight.rows.size > 1, ); contextMenu.append( new MenuItem({ label, click: () => { if (this.state.highlight) { // Clear the highlight before deleting the objects this.onShowDeleteObjectDialog( title, description, label, this.state.highlight.rows, ); } }, }), ); } } // If we right-clicking on the content we can add an existing object when we are focusing an object list if ( !readOnly && focus && focus.kind === 'list' && focus.property.objectType && !isPrimitive(focus.property.objectType) && !focus.property.isEmbedded ) { const className = getClassName(focus); contextMenu.append( new MenuItem({ label: `Add existing ${className}`, click: () => { if (focus.property.objectType) { this.onShowSelectObjectDialog({ action: { type: 'list', list: focus.results, }, className: focus.property.objectType, isEmbeddedType: this.props.isEmbeddedType, onShowJsonViewerDialog: this.props.onShowJsonViewerDialog, }); } }, }), ); } // If we right-clicking on the content we can always create a new object if (allowCreate && !readOnly && focus) { const className = getClassName(focus); contextMenu.append( new MenuItem({ label: `Create new ${className}`, click: () => { this.onShowCreateObjectDialog(className); }, }), ); } // If we have items to show - popup the menu if (contextMenu.items.length > 0) { contextMenu.popup({ x: e.clientX, y: e.clientY, }); } }; private onShowCreateObjectDialog = ( className: string, embeddedInfo?: EmbeddedInfo, ) => { if (!this.props.readOnly) { const { realm, getClassFocus, isEmbeddedType } = this.props; const schema = className && isPrimitive(className) ? { name: className, properties: { [className]: { type: className, }, }, } : realm.schema.find(s => s.name === className); if (schema) { this.setState({ createObjectDialog: { getClassFocus, isOpen: true, onCancel: this.onCancelCreateObjectDialog, onCreate: this.onCreateObject, schema, isEmbeddedType, embeddedInfo, onShowJsonViewerDialog: this.props.onShowJsonViewerDialog, }, }); } } }; private onShowDeleteObjectDialog = ( title: string, description: string, actionLabel: string, rows: Set<number>, ) => { this.setState({ deleteObjectsDialog: { actionLabel, title, description, isOpen: true, onCancel: this.onCancelDeleteObjectsDialog, onDelete: () => { this.deleteObjects(rows); this.setState({ // Deleting objects will mess up the highlight highlight: undefined, deleteObjectsDialog: { isOpen: false }, }); }, }, }); }; private onCreateObject: CreateObjectHandler = ( className: string, values: Record<string, unknown>, embeddedInfo?: EmbeddedInfo, ) => { if (!this.props.readOnly) { const { focus, realm } = this.props; let rowIndex = -1; this.write(() => { // Writing makes no sense if the realm was not loaded if (realm) { if (embeddedInfo) { const { parent, key } = embeddedInfo; if (focus && focus.kind === 'list') { // Using this method as instanceof Realm.List is not currently valid if (typeof parent[key].push === 'function') { parent[key].push(values); } } else { parent[key] = values; } } else if (isPrimitive(className)) { // Adding a primitive value into a list if (focus && focus.kind === 'list') { const valueToPush = (values as any)[className]; focus.results.push(valueToPush); rowIndex = focus.results.indexOf(valueToPush); } } else { // Adding a new object into a class const object = realm.create(className, values); if (focus) { // New object has been created from a list, so we add it too into the list if (focus.kind === 'list') { focus.results.push(object); } if (getClassName(focus) === className) { rowIndex = focus.results.indexOf(object); } } } this.setState({ createObjectDialog: { isOpen: false }, highlight: { rows: new Set(rowIndex >= 0 ? [rowIndex] : []), scrollTo: { row: rowIndex, }, }, }); } else { throw new Error('onCreateObject called before realm was loaded'); } }); } }; private onRowMouseDown: RowMouseDownHandler = (e, rowIndex) => { // Prevent the content grid from being clicked e.stopPropagation(); const { highlightMode, focus } = this.props; const { highlight } = this.state; if (this.contentElement && highlightMode === HighlightMode.Multiple) { // Create a mutation friendly version of the set of row indices currently highlighted const rows = highlight ? new Set(highlight.rows) : new Set<number>(); // This is a left click with the meta-key (command on Mac) pressed if (e.button === 0 && e.metaKey) { // The user wants to add or remove a row to the current selection if (rows.has(rowIndex)) { rows.delete(rowIndex); } else { rows.add(rowIndex); } this.setState({ highlight: { rows }, }); } else if (e.button === 0 && e.shiftKey) { // The user wants to select since the previous selection if (this.rowDragStart !== undefined) { const rowIndexRange = getRange(this.rowDragStart.rowIndex, rowIndex); for (const i of rowIndexRange) { rows.add(i); } } this.setState({ highlight: { rows } }); } else if (e.button === 0 && focus.kind !== 'list') { // The user left-clicked on a non-list row this.contentElement.addEventListener('mousemove', this.onRowMouseMove); document.addEventListener('mouseup', this.onRowMouseUp); const rect = e.currentTarget.getBoundingClientRect(); this.rowDragStart = { offset: rect.top, rowIndex, }; // Highlight the row this.setState({ highlight: { rows: new Set([rowIndex]) } }); } else if (e.button === 0 && focus.kind === 'list') { // The user left-clicked on a list row - highlight it this.setState({ highlight: { rows: new Set([rowIndex]) } }); } else if (e.button === 2 && rows.size === 0) { // Right clicked when nothing was highlighted: // Select the row but don't start a drag this.setState({ highlight: { rows: new Set([rowIndex]) } }); } } else if (highlightMode === HighlightMode.Single) { this.setState({ highlight: { rows: new Set([rowIndex]) } }); } }; private onRowMouseUp = () => { // If the table element is known, remove the move listener from it if (this.contentElement) { this.contentElement.removeEventListener('mousemove', this.onRowMouseMove); } }; private onRowMouseMove = (e: MouseEvent) => { if (this.rowDragStart) { const { offset, rowIndex } = this.rowDragStart; const offsetRelative = e.clientY - offset; const offsetIndex = Math.floor(offsetRelative / rowHeights.content); const hoveredIndex = rowIndex + offsetIndex; // Compute the set of highlighted row indices const minIndex = Math.min(rowIndex, hoveredIndex); const maxIndex = Math.max(rowIndex, hoveredIndex); const rows = new Set<number>(); for (let i = minIndex; i <= maxIndex; i++) { rows.add(i); } // Highlight the rows this.setState({ highlight: { rows } }); } }; private onNewObjectClick = () => { const { focus } = this.props; const className = getClassName(this.props.focus); const embeddedInfo: EmbeddedInfo | undefined = focus.isEmbedded && focus.kind === 'list' && focus.property.name ? { parent: focus.parent, key: focus.property.name, } : undefined; this.onShowCreateObjectDialog(className, embeddedInfo); }; private onPermissionSidebarToggle = () => { this.setState({ isPermissionSidebarOpen: !this.state.isPermissionSidebarOpen, }); }; private onReorderingStart: ReorderingStartHandler = () => { // Removing any highlight this.setState({ highlight: undefined }); }; private onReorderingEnd: ReorderingEndHandler = ({ oldIndex, newIndex }) => { const { focus } = this.props; if (focus.kind === 'list') { this.write(() => { // For embedded objects, we have to work on detached objects, as we otherwise // delete the moved object (not sure if this is best practice). if (focus.isEmbedded && focus.property.name) { const detached = focus.results.toJSON(); const removed = detached.splice(oldIndex, 1); detached.splice(newIndex, 0, removed[0]); focus.parent[focus.property.name] = detached; } else { const removed = focus.results.splice(oldIndex, 1); focus.results.splice(newIndex, 0, removed[0]); } }); } this.setState({ highlight: { ...this.state.highlight, rows: new Set([newIndex]), }, }); }; private onShowSelectObjectDialog({ className, isOptional = false, action, isEmbeddedType, }: { className: string; isOptional?: boolean; action: SelectObjectAction; isEmbeddedType: IsEmbeddedTypeChecker; onShowJsonViewerDialog: JsonViewerDialogExecutor; }) { if (!this.props.readOnly) { const focus: IClassFocus = this.props.getClassFocus(className); if (action.type === 'object') { const selectObjectDialog: ISelectObjectForObjectDialog = { action: 'object', focus, isOpen: true, isOptional, multiple: false, object: action.object, onCancel: this.onCancelSelectObjectDialog, onSelect: this.onObjectSelect, propertyName: action.propertyName, isEmbeddedType, onShowJsonViewerDialog: this.props.onShowJsonViewerDialog, }; this.setState({ selectObjectDialog }); } else { const selectObjectDialog: ISelectObjectsForListDialog = { action: 'list', focus, isOpen: true, isOptional, list: action.list, multiple: true, onCancel: this.onCancelSelectObjectDialog, onSelect: this.onObjectSelect, isEmbeddedType, onShowJsonViewerDialog: this.props.onShowJsonViewerDialog, }; this.setState({ selectObjectDialog }); } } } private deleteObjects(rowIndices: Set<number>) { if (!this.props.readOnly) { try { const { focus, realm, onClassFocussed } = this.props; this.write(() => { const objects = this.getHighlightedObjects(rowIndices); if (realm && focus.kind === 'class') { for (const object of objects) { realm.delete(object); } } else if (focus.kind === 'list') { // Creating a list of the indices of the objects in the original (unfiltered, unsorted) list const listIndices: number[] = []; for (const object of objects) { const index = focus.results.indexOf(object); listIndices.push(index); } // Sort and reverse, in-place listIndices.sort((a, b) => a - b).reverse(); // Remove these objects from the list one by one - starting from the bottom for (const index of listIndices) { focus.results.splice(index, 1); } } else if (focus.kind === 'single-object') { if (focus.results[0]) { const object = focus.results.pop(); realm.delete(object); if (onClassFocussed) { onClassFocussed(focus.parent.objectSchema().name, focus.parent); } } } }); } catch (err) { showError('Error deleting the object', err); } } } private getHighlightedObjects(rowIndices: Set<number>) { const { results } = this.filteredSortedResults( this.props.focus.results, this.state.query, this.state.sorting, ); const result = new Set<Realm.Object>(); for (const index of rowIndices) { const object = results[index]; result.add(object); } return result; } private generateDeleteTexts(focus: Focus, multiple: boolean) { if (focus.kind === 'list') { const parent = focus.isEmbedded ? focus.parent.objectSchema().name : 'list'; const target = focus.isEmbedded ? 'embedded object' : multiple ? 'rows' : 'row'; const determinedTarget = `${multiple ? 'these' : 'this'} ${target}`; return { label: `Remove selected ${target} from the ${parent}`, title: `Removing ${target}`, description: `Are you sure you want to remove ${determinedTarget} from the ${parent}?`, }; } else { const target = multiple ? 'objects' : 'object'; const determinedTarget = `${multiple ? 'these' : 'this'} ${target}`; return { label: `Delete selected ${target}`, title: `Delete ${target}`, description: `Are you sure you want to delete ${determinedTarget}?`, }; } } private write(callback: () => void) { if (!this.props.readOnly) { if (this.props.realm.isInTransaction) { callback(); // We have to signal changes manually this.props.onRealmChanged(); } else { this.props.realm.write(callback); } } } } export { ContentContainer as Content };
the_stack
import React, { ReactNode, CSSProperties, useContext, useState, useImperativeHandle, useRef, useEffect, } from 'react'; import { isUndefined, isObject } from '../_util/is'; import cs from '../_util/classNames'; import { ConfigContext } from '../ConfigProvider'; import IconDown from '../../icon/react-icon/IconDown'; import IconLoading from '../../icon/react-icon/IconLoading'; import IconClose from '../../icon/react-icon/IconClose'; import IconExpand from '../../icon/react-icon/IconExpand'; import IconSearch from '../../icon/react-icon/IconSearch'; import InputTag, { InputTagProps } from '../InputTag'; import InputComponent from '../Input/input-element'; import { ObjectValueType } from '../InputTag/interface'; import { InputComponentProps } from '../Input/interface'; import include from '../_util/include'; import useForceUpdate from '../_util/hooks/useForceUpdate'; import IconHover from './icon-hover'; import { Backspace, Enter } from '../_util/keycode'; export interface SelectViewCommonProps extends Pick<InputTagProps<unknown>, 'animation' | 'renderTag' | 'dragToSort'> { style?: CSSProperties; className?: string | string[]; children?: ReactNode; inputValue?: string; /** * @zh 选择框默认文字。 * @en Placeholder of element */ placeholder?: string; /** * @zh 是否需要边框 * @en Whether to render border * @defaultValue true */ bordered?: boolean; /** * @zh * 使单选模式可搜索,传入 `{ retainInputValue: true }` 在搜索框聚焦时保留现有内容 * 传入 `{ retainInputValueWhileSelect: true }` 在多选选择时保留输入框内容。 * @en * Whether single mode Select is searchable. `{ retainInputValue: true }` to retain the existing content when the search box is focused, * `{ retainInputValueWhileSelect: true }` to retain the existing content when multiple selection is selected. */ showSearch?: boolean | { retainInputValue?: boolean; retainInputValueWhileSelect?: boolean }; /** * @zh 分别不同尺寸的选择器。对应 `24px`, `28px`, `32px`, `36px` * @en Height of element, `24px` `28px` `32px` `36px` */ size?: 'mini' | 'small' | 'default' | 'large'; /** * @zh 是否为禁用状态。 * @en Whether is disabled */ disabled?: boolean; /** * @zh 是否为错误状态。 * @en Error Style */ error?: boolean; /** * @zh 是否为加载状态。 * @en Whether is in loading */ loading?: boolean; /** * @zh 允许清除值。 * @en Whether allow to clear selected options */ allowClear?: boolean; /** * @zh 是否允许通过输入创建新的选项。 * @en Whether to allow new options to be created by input. * @version 2.13.0 */ allowCreate?: boolean; /** * @zh 最多显示多少个 `tag`,仅在多选或标签模式有效。 * @en The maximum number of `tags` is displayed, only valid in `multiple` and `label` mode. */ maxTagCount?: number; /** * @zh 前缀。 * @en Customize select suffix * @version 2.11.0 */ prefix?: ReactNode; /** * @zh 自定义选择框后缀图标。 * @en Customize select suffix icon */ suffixIcon?: ReactNode; /** * @zh 自定义箭头图标,设置为 `null` 不显示箭头图标。 * @en Customize select arrow icon. */ arrowIcon?: ReactNode | null; /** * @zh 多选时配置选中项的删除图标。当传入`null`,不显示删除图标。 * @en Customize the delete icon of tags selected in `multiple` and `label` mode. */ removeIcon?: ReactNode | null; /** * @zh `allowClear` 时配置清除按钮的图标。 * @en Configure the icon of the clear button when `allowClear`. * @version 2.26.0 */ clearIcon?: ReactNode; /** * @zh 鼠标点击下拉框时的回调 * @en Callback when the mouse clicks on the drop-down box */ onClick?: (e) => void; } export interface SelectViewProps extends SelectViewCommonProps { // state ⬇️ value?: any; popupVisible?: boolean; // other ⬇️ isEmptyValue: boolean; isMultiple?: boolean; prefixCls: string; ariaControls?: string; renderText: (value) => { text; disabled }; onSort?: (value) => void; onRemoveCheckedItem?: (item, index: number, e) => void; onChangeInputValue?: InputComponentProps['onChange']; onKeyDown?: (e) => void; onPaste?: (e) => void; onClear?: (e) => void; onFocus?: (e) => void; onBlur?: (e) => void; } const SearchStatus = { BEFORE: 0, EDITING: 1, NONE: 2, }; export type SelectViewHandle = { dom: HTMLDivElement; focus: () => void; blur: () => void; getWidth: () => number; }; export const SelectView = (props: SelectViewProps, ref) => { const { style, className, size, bordered, allowClear, allowCreate, error, loading, disabled, animation, prefixCls, suffixIcon, arrowIcon, removeIcon, clearIcon, placeholder, renderText, value, inputValue, popupVisible, maxTagCount, isMultiple, isEmptyValue, prefix, ariaControls, renderTag, dragToSort, onKeyDown, onChangeInputValue, onPaste, onClear, onFocus, onBlur, onRemoveCheckedItem, onSort, ...rest } = props; // refs const refInput = useRef(null); const refWrapper = useRef(null); // state const { size: ctxSize, getPrefixCls } = useContext(ConfigContext); const [searchStatus, setSearchStatus] = useState(SearchStatus.NONE); const [focused, setFocused] = useState(false); const forceUpdate = useForceUpdate(); // TODO:Will the search be completely controlled by showSearch? Next major version needs to be considered const showSearch = 'showSearch' in props ? props.showSearch : isMultiple; const canFocusInput = showSearch || allowCreate; const mergedSize = size || ctxSize; const mergedFocused = focused || popupVisible; const isRetainInputValueSearch = isObject(showSearch) && showSearch.retainInputValue; // the formatted text of value. const renderedValue = !isMultiple && value !== undefined ? renderText(value).text : ''; // Avoid losing focus caused by clicking certain icons const keepFocus = (event) => { event && event.preventDefault(); }; const handleFocus = (action: 'focus' | 'blur') => { const element = canFocusInput ? refInput.current : refWrapper.current; if (element) { action === 'focus' ? element.focus() : element.blur(); } }; const tryTriggerFocusChange = (action: 'focus' | 'blur', event) => { // The focus event at this time should be triggered by the input element if (canFocusInput && event.target === refWrapper.current) { return; } if (action === 'focus') { setFocused(true); onFocus && onFocus(event); } else { setFocused(false); onBlur && onBlur(event); } }; const tryTriggerKeyDown = (event) => { // The keyboard event at this time should be triggered by the input element, ignoring the bubbling up keyboard event if (canFocusInput && event.currentTarget === refWrapper.current) { return; } // Prevent the default behavior of the browser when pressing Enter, to avoid submit event in <form> const keyCode = event.keyCode || event.which; if (keyCode === Enter.code) { event.preventDefault(); } onKeyDown && onKeyDown(event); }; useEffect(() => { handleFocus(popupVisible ? 'focus' : 'blur'); if (canFocusInput) { setSearchStatus(popupVisible ? SearchStatus.BEFORE : SearchStatus.NONE); } }, [popupVisible]); useImperativeHandle<any, SelectViewHandle>(ref, () => ({ dom: refWrapper.current, focus: handleFocus.bind(null, 'focus'), blur: handleFocus.bind(null, 'blur'), getWidth: () => refWrapper.current && refWrapper.current.clientWidth, })); const mergedArrowIcon = 'arrowIcon' in props ? ( arrowIcon === null ? null : ( <div className={`${prefixCls}-arrow-icon`}>{arrowIcon}</div> ) ) : canFocusInput ? ( <div className={`${prefixCls}-expand-icon`}> <IconExpand style={{ transform: 'rotate(-45deg)' }} /> </div> ) : ( <div className={`${prefixCls}-arrow-icon`}> <IconDown /> </div> ); const mergedSuffixIcon = loading ? ( <span className={`${prefixCls}-loading-icon`}> <IconLoading /> </span> ) : suffixIcon ? ( <span className={`${prefixCls}-suffix-icon`}>{suffixIcon}</span> ) : props.showSearch && popupVisible ? ( <div className={`${prefixCls}-search-icon`}> <IconSearch /> </div> ) : ( mergedArrowIcon ); // event handling of input box const inputEventHandlers = { paste: onPaste, keyDown: tryTriggerKeyDown, focus: (event) => { event.stopPropagation(); tryTriggerFocusChange('focus', event); }, blur: (event) => { event.stopPropagation(); tryTriggerFocusChange('blur', event); }, change: (newValue, event) => { setSearchStatus(SearchStatus.EDITING); onChangeInputValue && onChangeInputValue(newValue, event); }, }; const renderSingle = () => { let _inputValue: string; switch (searchStatus) { case SearchStatus.BEFORE: _inputValue = inputValue || (isRetainInputValueSearch ? renderedValue : ''); break; case SearchStatus.EDITING: _inputValue = inputValue || ''; break; default: _inputValue = renderedValue; break; } const inputProps: InputComponentProps = { style: { width: '100%' }, // _inputValue after renderText(value) may be rich text, but the value of <input> cannot be object value: typeof _inputValue !== 'object' ? _inputValue : '', // Allow placeholder to display the selected value first when searching placeholder: canFocusInput && renderedValue && typeof renderedValue !== 'object' ? renderedValue : placeholder, }; if (canFocusInput) { inputProps.onPaste = inputEventHandlers.paste; inputProps.onKeyDown = inputEventHandlers.keyDown; inputProps.onFocus = inputEventHandlers.focus; inputProps.onBlur = inputEventHandlers.blur; inputProps.onChange = inputEventHandlers.change; } else { // Avoid input getting focus by Tab // Do NOT pass [disabled] to <input>, otherwise the click event will not be triggered // https://stackoverflow.com/questions/7833854/jquery-detect-click-on-disabled-submit-button inputProps.tabIndex = -1; inputProps.style.pointerEvents = 'none'; } // <input> is used to input and display placeholder, in other cases use <span> to display value to support displaying rich text const needShowInput = !!((mergedFocused && canFocusInput) || isEmptyValue); return ( <> <InputComponent aria-hidden={!needShowInput || undefined} ref={refInput} disabled={disabled} className={cs(`${prefixCls}-view-input`, { [`${prefixCls}-hidden`]: !needShowInput, })} autoComplete="off" {...inputProps} /> <span aria-hidden={needShowInput || undefined} className={cs(`${prefixCls}-view-value`, { [`${prefixCls}-hidden`]: needShowInput })} > {_inputValue} </span> </> ); }; const renderMultiple = () => { const usedValue = isUndefined(value) ? [] : [].concat(value as []); const usedMaxTagCount = typeof maxTagCount === 'number' ? Math.max(maxTagCount, 0) : usedValue.length; const tagsToShow: ObjectValueType[] = []; let lastClosableTagIndex = -1; for (let i = usedValue.length - 1; i >= 0; i--) { const v = usedValue[i]; const result = renderText(v); if (i < usedMaxTagCount) { tagsToShow.unshift({ value: v, label: result.text, closable: !result.disabled, }); } if (!result.disabled && lastClosableTagIndex === -1) { lastClosableTagIndex = i; } } const invisibleTagCount = usedValue.length - usedMaxTagCount; if (invisibleTagCount > 0) { tagsToShow.push({ label: `+${invisibleTagCount}...`, closable: false, // InputTag needs to extract value as key value: '__arco_value_tag_placeholder', }); } const eventHandlers = { onPaste: inputEventHandlers.paste, onKeyDown: inputEventHandlers.keyDown, onFocus: inputEventHandlers.focus, onBlur: inputEventHandlers.blur, onInputChange: inputEventHandlers.change, onRemove: (value, index, event) => { // Should always delete the last option value when press Backspace const keyCode = event.keyCode || event.which; if (keyCode === Backspace.code && lastClosableTagIndex > -1) { value = usedValue[lastClosableTagIndex]; index = lastClosableTagIndex; } // If there is a limit on the maximum number of tags, the parameters passed into InputTag need to be recalculated maxTagCount && forceUpdate(); onRemoveCheckedItem && onRemoveCheckedItem(value, index, event); }, }; return ( <InputTag // Avoid when clicking outside the browser window, InputTag out of focus className={mergedFocused ? `${getPrefixCls('input-tag')}-focus` : ''} ref={refInput} disabled={disabled} dragToSort={dragToSort} disableInput={!showSearch} animation={animation} placeholder={placeholder} value={tagsToShow} inputValue={inputValue} size={mergedSize} tagClassName={`${prefixCls}-tag`} renderTag={renderTag} icon={{ removeIcon }} onChange={(value, reason) => { if (onSort && reason === 'sort') { onSort(value); } }} {...eventHandlers} /> ); }; const classNames = cs( prefixCls, `${prefixCls}-${isMultiple ? 'multiple' : 'single'}`, { [`${prefixCls}-show-search`]: showSearch, [`${prefixCls}-open`]: popupVisible, [`${prefixCls}-size-${mergedSize}`]: mergedSize, [`${prefixCls}-focused`]: mergedFocused, [`${prefixCls}-error`]: error, [`${prefixCls}-disabled`]: disabled, [`${prefixCls}-no-border`]: !bordered, }, className ); const mergedClearIcon = !disabled && !isEmptyValue && allowClear ? ( <IconHover size={mergedSize} key="clearIcon" className={`${prefixCls}-clear-icon`} onClick={onClear} onMouseDown={keepFocus} > {clearIcon !== undefined && clearIcon !== null ? clearIcon : <IconClose />} </IconHover> ) : null; return ( <div role="combobox" aria-haspopup="listbox" aria-autocomplete="list" aria-expanded={popupVisible} aria-disabled={disabled} aria-controls={ariaControls} {...include(rest, ['onClick', 'onMouseEnter', 'onMouseLeave'])} ref={refWrapper} tabIndex={disabled ? -1 : 0} style={style} className={classNames} // When there is an input box, the keyboard events are handled inside the input box to avoid triggering redundant events in the Chinese input method onKeyDown={tryTriggerKeyDown} onFocus={(event) => { if (!disabled && !dragToSort) { // Focus on the input, otherwise you need to press the Tab key twice to focus on the input box if (canFocusInput) { refInput.current && refInput.current.focus(); } else { tryTriggerFocusChange('focus', event); } } }} onBlur={(event) => tryTriggerFocusChange('blur', event)} > <div title={typeof renderedValue === 'string' ? renderedValue : undefined} className={cs(`${prefixCls}-view`, { [`${prefixCls}-view-with-prefix`]: prefix, })} onClick={(e) => popupVisible && canFocusInput && e.stopPropagation()} > {prefix && ( <div aria-hidden="true" className={cs(`${prefixCls}-prefix`)} onMouseDown={(event) => focused && keepFocus(event)} > {prefix} </div> )} {isMultiple ? renderMultiple() : renderSingle()} <div aria-hidden="true" className={`${prefixCls}-suffix`} onMouseDown={(event) => focused && keepFocus(event)} > {mergedClearIcon} {mergedSuffixIcon} </div> </div> </div> ); }; const SelectViewComponent = React.forwardRef<SelectViewHandle, SelectViewProps>(SelectView); SelectViewComponent.displayName = 'SelectView'; export default SelectViewComponent;
the_stack
import { shallowMount, Wrapper } from '@vue/test-utils'; import { DateTime } from 'luxon'; import CustomGranularityCalendar from '@/components/DatePicker/CustomGranularityCalendar.vue'; import { DECADE_NAV, RANGE_PICKERS, WEEK_NAV } from '@/components/DatePicker/GranularityConfigs'; import { DateRange } from '@/lib/dates'; const currentYear = DateTime.now().year; const SAMPLE_DATE_TIME = DateTime.fromRFC2822('25 Nov 2016 13:23 Z', { locale: 'en' }); describe('CustomGranularityCalendar', () => { let wrapper: Wrapper<CustomGranularityCalendar>; const createWrapper = (props: any = {}): void => { wrapper = shallowMount(CustomGranularityCalendar, { sync: false, propsData: { granularity: 'month', ...props, }, }); }; afterEach(() => { if (wrapper) wrapper.destroy(); }); // Test the "month" config with the component itself describe('Month', () => { describe('default', () => { beforeEach(() => { createWrapper(); }); it('should instantiate', () => { expect(wrapper.exists()).toBe(true); }); it('should display all 12 months', () => { const months = wrapper.findAll('.custom-granularity-calendar__option'); expect(months).toHaveLength(12); }); it('should display labels', () => { const labels = wrapper.findAll('.custom-granularity-calendar__option-label'); expect(labels).toHaveLength(12); expect(labels.at(0).text()).toStrictEqual('January'); expect(labels.at(11).text()).toStrictEqual('December'); }); it('should hide descriptions', () => { const descriptions = wrapper.findAll('.custom-granularity-calendar__option-description'); expect(descriptions).toHaveLength(0); }); describe('when clicking on a a month', () => { beforeEach(async () => { const february = wrapper.findAll('.custom-granularity-calendar__option').at(1); await february.trigger('click'); }); it('should emit the selected date range', () => { expect(wrapper.emitted('input')).toHaveLength(1); const emittedDate: DateRange = wrapper.emitted('input')[0][0]; expect(emittedDate.start).toBeInstanceOf(Date); expect(emittedDate.end).toBeInstanceOf(Date); expect(emittedDate.start?.toISOString()).toStrictEqual( `${currentYear}-02-01T00:00:00.000Z`, ); expect(emittedDate.end?.toISOString()).toStrictEqual( `${currentYear}-02-28T23:59:59.999Z`, ); expect(emittedDate.duration).toBe('month'); }); }); }); describe('with selected date range', () => { beforeEach(() => { createWrapper({ value: { start: new Date('12/21/1977'), // only based on start date (for now) }, }); }); it('should set header on corresponding year', () => { expect(wrapper.find('.custom-granularity-calendar__header').text()).toBe('1977'); }); it('should select the corresponding month', () => { expect(wrapper.find('.custom-granularity-calendar__option--selected').text()).toBe( 'December', ); }); describe('when clicking on the previous year button', () => { beforeEach(async () => { await wrapper.find('.header-btn__previous').trigger('click'); }); it('should show the previous year', () => { expect(wrapper.find('.custom-granularity-calendar__header').text()).toBe('1976'); }); }); describe('when clicking on the next year button', () => { beforeEach(async () => { await wrapper.find('.header-btn__next').trigger('click'); }); it('should show the previous year', () => { expect(wrapper.find('.custom-granularity-calendar__header').text()).toBe('1978'); }); }); }); }); describe('When switching granularity with a selected date range', () => { beforeEach(async () => { createWrapper({ granularity: 'month', value: { start: new Date('02/01/2021'), }, }); await wrapper.setProps({ granularity: 'quarter' }); }); it('should emit an updated selected date range', () => { expect(wrapper.emitted('input')).toHaveLength(1); const emittedDate: DateRange = wrapper.emitted('input')[0][0]; expect(emittedDate.start?.toISOString()).toStrictEqual(`2021-01-01T00:00:00.000Z`); expect(emittedDate.end?.toISOString()).toStrictEqual(`2021-03-31T23:59:59.999Z`); expect(emittedDate.duration).toBe('quarter'); }); }); // For everything else, only test date related fonction aka the "Granularity Config" describe('Decade navigation', () => { it('should provide the right label', () => { expect(DECADE_NAV.label(SAMPLE_DATE_TIME)).toBe('2010-2020'); }); it('should provide a date in the next decade', () => { expect(DECADE_NAV.next(SAMPLE_DATE_TIME).year).toBe(2026); }); it('should provide a date in the previous decade', () => { expect(DECADE_NAV.prev(SAMPLE_DATE_TIME).year).toBe(2006); }); }); describe('Week navigation', () => { it('should provide the right label', () => { expect(WEEK_NAV.label(SAMPLE_DATE_TIME)).toBe('W47 - W2 2017'); }); it('should provide a date in the next week', () => { expect(WEEK_NAV.next(SAMPLE_DATE_TIME).weekNumber).toBe(3); }); it('should provide a date in the previous week', () => { expect(WEEK_NAV.prev(SAMPLE_DATE_TIME).weekNumber).toBe(39); }); }); describe('Week options', () => { const options = RANGE_PICKERS.week.selectableRanges.currentOptions(SAMPLE_DATE_TIME); it('should provide the right label', () => { expect(RANGE_PICKERS.week.selectableRanges.label(SAMPLE_DATE_TIME)).toBe('Week 47'); }); it('should provide the right options', () => { expect(options).toHaveLength(8); expect(options.map(dt => dt.weekNumber)).toStrictEqual([47, 48, 49, 50, 51, 52, 1, 2]); }); it('should convert an option to a date range (monday to monday)', () => { const W48 = options[1]; expect(RANGE_PICKERS.week.selectableRanges.optionToRange(W48)).toStrictEqual({ start: new Date('2016-11-28T00:00:00.000Z'), // monday November 28th 2016 end: new Date('2016-12-04T23:59:59.999Z'), // sunday December 4th 2016 duration: 'week', }); }); it('should provide the right description', () => { const W48 = options[1]; const range = RANGE_PICKERS.week.selectableRanges.optionToRange(W48); expect(RANGE_PICKERS.week.selectableRanges.description(range)).toBe('11/28/2016 - 12/4/2016'); }); it('should convert a arbitrary date range to the associated option', () => { expect( RANGE_PICKERS.week.selectableRanges.rangeToOption(new Date('2016-04-12T00:00:00.000Z')), // a tuesda3 ).toStrictEqual(DateTime.utc(2016, 4, 11, { locale: 'en' })); }); }); describe('Quarter options', () => { const options = RANGE_PICKERS.quarter.selectableRanges.currentOptions(SAMPLE_DATE_TIME); it('should provide the right label', () => { expect(RANGE_PICKERS.quarter.selectableRanges.label(SAMPLE_DATE_TIME)).toBe('Quarter 4'); }); it('should provide the right description', () => { const Q2 = options[1]; const range = RANGE_PICKERS.quarter.selectableRanges.optionToRange(Q2); expect(RANGE_PICKERS.quarter.selectableRanges.description(range)).toBe(''); }); it('should provide the right options', () => { expect(options).toHaveLength(4); expect(options.map(dt => dt.quarter)).toStrictEqual([1, 2, 3, 4]); }); it('should convert an option to a date range', () => { const Q2 = options[1]; expect(RANGE_PICKERS.quarter.selectableRanges.optionToRange(Q2)).toStrictEqual({ start: new Date(Date.UTC(2016, 3, 1)), end: new Date(Date.UTC(2016, 5, 30, 23, 59, 59, 999)), duration: 'quarter', }); }); it('should convert a arbitrary date range to the associated option', () => { expect( RANGE_PICKERS.quarter.selectableRanges.rangeToOption( // Weird quarter from the 12th to the 12th new Date(Date.UTC(2016, 3, 12)), ), ).toStrictEqual(DateTime.utc(2016, 4, 1, { locale: 'en' })); }); }); describe('Year options', () => { const options = RANGE_PICKERS.year.selectableRanges.currentOptions(SAMPLE_DATE_TIME); it('should provide the right label', () => { expect(RANGE_PICKERS.year.selectableRanges.label(SAMPLE_DATE_TIME)).toBe('2016'); }); it('should provide the right description', () => { const Year2012 = options[2]; const range = RANGE_PICKERS.year.selectableRanges.optionToRange(Year2012); expect(RANGE_PICKERS.year.selectableRanges.description(range)).toBe(''); }); it('should provide the right options', () => { expect(options).toHaveLength(11); expect(options.map(dt => dt.year)).toStrictEqual([ 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, ]); }); it('should convert an option to a date range', () => { const Year2012 = options[2]; expect(RANGE_PICKERS.year.selectableRanges.optionToRange(Year2012)).toStrictEqual({ start: new Date(Date.UTC(2012, 0, 1)), end: new Date(Date.UTC(2012, 11, 31, 23, 59, 59, 999)), duration: 'year', }); }); it('should convert a arbitrary date range to the associated option', () => { expect( RANGE_PICKERS.year.selectableRanges.rangeToOption( // Weird year from the 12th feb to the 12th feb new Date(Date.UTC(2012, 1, 12)), ), ).toStrictEqual(DateTime.utc(2012, 1, 1, { locale: 'en' })); }); }); describe('bounds', () => { beforeEach(() => { createWrapper({ granularity: 'month', value: new Date('2021-10-19'), // in october 2021 }); }); it('should deactivate choices that have no overlap with the bounds range', async () => { await wrapper.setProps({ bounds: { start: new Date('2021-05-15'), // middle of may 2021 end: new Date('2021-11-31'), // end of november 2021 }, }); const options = wrapper.findAll('.custom-granularity-calendar__option'); const enabledOptionsLabels = options .filter(w => !w.classes('custom-granularity-calendar__option--disabled')) .wrappers.map(w => w.find('.custom-granularity-calendar__option-label').text()); const disabledOptionsLabels = options .filter(w => w.classes('custom-granularity-calendar__option--disabled')) .wrappers.map(w => w.find('.custom-granularity-calendar__option-label').text()); expect(enabledOptionsLabels).toEqual([ 'May', 'June', 'July', 'August', 'September', 'October', 'November', ]); expect(disabledOptionsLabels).toEqual(['January', 'February', 'March', 'April', 'December']); // Clicking on a disabled button should have no effect await options.filter(w => w.text().includes('January')).wrappers[0].trigger('click'); expect(wrapper.emitted('input')).toBeUndefined(); }); it('should deactivate navigation towards NavRanges that would be all disabled', async () => { // NOTE: to avoid being blocked in a sate when a user can't escape (with a start value out-of-bounds), // the navigation buttons are only visually disabled, but remains clickable. await wrapper.setProps({ bounds: { start: new Date('2021-05-01'), // start of may 2021 end: new Date('2021-12-01'), // start of december 2021 }, }); expect(wrapper.find('.header-btn__previous').classes()).toContain( 'custom-granularity-calendar__header-btn--disabled', ); expect(wrapper.find('.header-btn__next').classes()).toContain( 'custom-granularity-calendar__header-btn--disabled', ); // Disable the navigation towards the future, but not towards the past await wrapper.setProps({ bounds: { start: new Date('1990-01-01'), // start of 1990 end: new Date('2021-12-01'), // start of december 2021 }, }); expect(wrapper.find('.header-btn__previous').classes()).not.toContain( 'custom-granularity-calendar__header-btn--disabled', ); expect(wrapper.find('.header-btn__next').classes()).toContain( 'custom-granularity-calendar__header-btn--disabled', ); // Disable the navigation towards the past, but not towards the future await wrapper.setProps({ bounds: { start: new Date('2021-05-01'), // start of may 2021 end: new Date('2049-01-01'), // start of 2049 }, }); expect(wrapper.find('.header-btn__previous').classes()).toContain( 'custom-granularity-calendar__header-btn--disabled', ); expect(wrapper.find('.header-btn__next').classes()).not.toContain( 'custom-granularity-calendar__header-btn--disabled', ); // No bounds, every navigation should be possible await wrapper.setProps({ bounds: {}, }); expect(wrapper.find('.header-btn__previous').classes()).not.toContain( 'custom-granularity-calendar__header-btn--disabled', ); expect(wrapper.find('.header-btn__next').classes()).not.toContain( 'custom-granularity-calendar__header-btn--disabled', ); }); }); });
the_stack
const { sprintf } = require('sprintf-js'); interface StringToStringMap { [key: string]: string; } interface CodeToCountryMap { [key: string]: string[]; } const codeToLanguageE_: StringToStringMap = {}; codeToLanguageE_['aa'] = 'Afar'; codeToLanguageE_['ab'] = 'Abkhazian'; codeToLanguageE_['af'] = 'Afrikaans'; codeToLanguageE_['am'] = 'Amharic'; codeToLanguageE_['an'] = 'Aragonese'; codeToLanguageE_['ar'] = 'Arabic'; codeToLanguageE_['as'] = 'Assamese'; codeToLanguageE_['ay'] = 'Aymara'; codeToLanguageE_['az'] = 'Azerbaijani'; codeToLanguageE_['ba'] = 'Bashkir'; codeToLanguageE_['be'] = 'Byelorussian'; codeToLanguageE_['bg'] = 'Bulgarian'; codeToLanguageE_['bh'] = 'Bihari'; codeToLanguageE_['bi'] = 'Bislama'; codeToLanguageE_['bn'] = 'Bangla'; codeToLanguageE_['bo'] = 'Tibetan'; codeToLanguageE_['br'] = 'Breton'; codeToLanguageE_['bs'] = 'Bosnian'; codeToLanguageE_['ca'] = 'Catalan'; codeToLanguageE_['co'] = 'Corsican'; codeToLanguageE_['cs'] = 'Czech'; codeToLanguageE_['cy'] = 'Welsh'; codeToLanguageE_['da'] = 'Danish'; codeToLanguageE_['de'] = 'German'; codeToLanguageE_['dz'] = 'Bhutani'; codeToLanguageE_['el'] = 'Greek'; codeToLanguageE_['en'] = 'English'; codeToLanguageE_['eo'] = 'Esperanto'; codeToLanguageE_['es'] = 'Spanish'; codeToLanguageE_['et'] = 'Estonian'; codeToLanguageE_['eu'] = 'Basque'; codeToLanguageE_['fa'] = 'Persian'; codeToLanguageE_['fi'] = 'Finnish'; codeToLanguageE_['fj'] = 'Fiji'; codeToLanguageE_['fo'] = 'Faroese'; codeToLanguageE_['fr'] = 'French'; codeToLanguageE_['fy'] = 'Frisian'; codeToLanguageE_['ga'] = 'Irish'; codeToLanguageE_['gd'] = 'Gaelic'; codeToLanguageE_['gl'] = 'Galician'; codeToLanguageE_['gn'] = 'Guarani'; codeToLanguageE_['gu'] = 'Gujarati'; codeToLanguageE_['ha'] = 'Hausa'; codeToLanguageE_['he'] = 'Hebrew'; codeToLanguageE_['hi'] = 'Hindi'; codeToLanguageE_['hr'] = 'Croatian'; codeToLanguageE_['hu'] = 'Hungarian'; codeToLanguageE_['hy'] = 'Armenian'; codeToLanguageE_['ia'] = 'Interlingua'; codeToLanguageE_['id'] = 'Indonesian'; codeToLanguageE_['ie'] = 'Interlingue'; codeToLanguageE_['ik'] = 'Inupiak'; codeToLanguageE_['is'] = 'Icelandic'; codeToLanguageE_['it'] = 'Italian'; codeToLanguageE_['iu'] = 'Inuktitut'; codeToLanguageE_['ja'] = 'Japanese'; codeToLanguageE_['jw'] = 'Javanese'; codeToLanguageE_['ka'] = 'Georgian'; codeToLanguageE_['kk'] = 'Kazakh'; codeToLanguageE_['kl'] = 'Greenlandic'; codeToLanguageE_['km'] = 'Cambodian'; codeToLanguageE_['kn'] = 'Kannada'; codeToLanguageE_['ko'] = 'Korean'; codeToLanguageE_['ks'] = 'Kashmiri'; codeToLanguageE_['ku'] = 'Kurdish'; codeToLanguageE_['ky'] = 'Kirghiz'; codeToLanguageE_['la'] = 'Latin'; codeToLanguageE_['ln'] = 'Lingala'; codeToLanguageE_['lo'] = 'Laothian'; codeToLanguageE_['lt'] = 'Lithuanian'; codeToLanguageE_['lv'] = 'Lettish'; codeToLanguageE_['mg'] = 'Malagasy'; codeToLanguageE_['mi'] = 'Maori'; codeToLanguageE_['mk'] = 'Macedonian'; codeToLanguageE_['ml'] = 'Malayalam'; codeToLanguageE_['mn'] = 'Mongolian'; codeToLanguageE_['mo'] = 'Moldavian'; codeToLanguageE_['mr'] = 'Marathi'; codeToLanguageE_['ms'] = 'Malay'; codeToLanguageE_['mt'] = 'Maltese'; codeToLanguageE_['my'] = 'Burmese'; codeToLanguageE_['na'] = 'Nauru'; codeToLanguageE_['nb'] = 'Norwegian'; codeToLanguageE_['ne'] = 'Nepali'; codeToLanguageE_['nl'] = 'Dutch'; codeToLanguageE_['no'] = 'Norwegian'; codeToLanguageE_['oc'] = 'Occitan'; codeToLanguageE_['om'] = 'Oromo'; codeToLanguageE_['or'] = 'Oriya'; codeToLanguageE_['pa'] = 'Punjabi'; codeToLanguageE_['pl'] = 'Polish'; codeToLanguageE_['ps'] = 'Pushto'; codeToLanguageE_['pt'] = 'Portuguese'; codeToLanguageE_['qu'] = 'Quechua'; codeToLanguageE_['rm'] = 'Rhaeto-Romance'; codeToLanguageE_['rn'] = 'Kirundi'; codeToLanguageE_['ro'] = 'Romanian'; codeToLanguageE_['ru'] = 'Russian'; codeToLanguageE_['rw'] = 'Kinyarwanda'; codeToLanguageE_['sa'] = 'Sanskrit'; codeToLanguageE_['sd'] = 'Sindhi'; codeToLanguageE_['sg'] = 'Sangho'; codeToLanguageE_['sh'] = 'Serbo-Croatian'; codeToLanguageE_['si'] = 'Sinhalese'; codeToLanguageE_['sk'] = 'Slovak'; codeToLanguageE_['sl'] = 'Slovenian'; codeToLanguageE_['sm'] = 'Samoan'; codeToLanguageE_['sn'] = 'Shona'; codeToLanguageE_['so'] = 'Somali'; codeToLanguageE_['sq'] = 'Albanian'; codeToLanguageE_['sr'] = 'Serbian'; codeToLanguageE_['ss'] = 'Siswati'; codeToLanguageE_['st'] = 'Sesotho'; codeToLanguageE_['su'] = 'Sundanese'; codeToLanguageE_['sv'] = 'Swedish'; codeToLanguageE_['sw'] = 'Swahili'; codeToLanguageE_['ta'] = 'Tamil'; codeToLanguageE_['te'] = 'Telugu'; codeToLanguageE_['tg'] = 'Tajik'; codeToLanguageE_['th'] = 'Thai'; codeToLanguageE_['ti'] = 'Tigrinya'; codeToLanguageE_['tk'] = 'Turkmen'; codeToLanguageE_['tl'] = 'Tagalog'; codeToLanguageE_['tn'] = 'Setswana'; codeToLanguageE_['to'] = 'Tonga'; codeToLanguageE_['tr'] = 'Turkish'; codeToLanguageE_['ts'] = 'Tsonga'; codeToLanguageE_['tt'] = 'Tatar'; codeToLanguageE_['tw'] = 'Twi'; codeToLanguageE_['ug'] = 'Uighur'; codeToLanguageE_['uk'] = 'Ukrainian'; codeToLanguageE_['ur'] = 'Urdu'; codeToLanguageE_['uz'] = 'Uzbek'; codeToLanguageE_['vi'] = 'Vietnamese'; codeToLanguageE_['vo'] = 'Volapuk'; codeToLanguageE_['wo'] = 'Wolof'; codeToLanguageE_['xh'] = 'Xhosa'; codeToLanguageE_['yi'] = 'Yiddish'; codeToLanguageE_['yo'] = 'Yoruba'; codeToLanguageE_['za'] = 'Zhuang'; codeToLanguageE_['zh'] = 'Chinese'; codeToLanguageE_['zu'] = 'Zulu'; const codeToLanguage_: StringToStringMap = {}; codeToLanguage_['an'] = 'Aragonés'; codeToLanguage_['da'] = 'Dansk'; codeToLanguage_['de'] = 'Deutsch'; codeToLanguage_['en'] = 'English'; codeToLanguage_['es'] = 'Español'; codeToLanguage_['fr'] = 'Français'; codeToLanguage_['he'] = 'עיברית'; codeToLanguage_['it'] = 'Italiano'; codeToLanguage_['lt'] = 'Lietuvių kalba'; codeToLanguage_['nl'] = 'Nederlands'; codeToLanguage_['pl'] = 'Polski'; codeToLanguage_['pt'] = 'Português'; codeToLanguage_['ru'] = 'Русский'; codeToLanguage_['sk'] = 'Slovenčina'; codeToLanguage_['sq'] = 'Shqip'; codeToLanguage_['sr'] = 'српски језик'; codeToLanguage_['tr'] = 'Türkçe'; codeToLanguage_['ja'] = '日本語'; codeToLanguage_['ko'] = '한국어'; codeToLanguage_['sv'] = 'Svenska'; codeToLanguage_['el'] = 'Ελληνικά'; codeToLanguage_['zh'] = '中文'; codeToLanguage_['ro'] = 'Română'; codeToLanguage_['et'] = 'Eesti Keel'; codeToLanguage_['vi'] = 'Tiếng Việt'; codeToLanguage_['hu'] = 'Magyar'; const codeToCountry_: CodeToCountryMap = { AD: ['Andorra', 'Andorra'], AE: ['United Arab Emirates', 'دولة الإمارات العربيّة المتّحدة'], AF: ['Afghanistan', 'د افغانستان اسلامي دولتدولت اسلامی افغانستان, جمهوری اسلامی افغانستان'], AG: ['Antigua and Barbuda', 'Antigua and Barbuda'], AI: ['Anguilla', 'Anguilla'], AL: ['Albania', 'Shqipëria'], AM: ['Armenia', 'Հայաստան'], AO: ['Angola', 'Angola'], AQ: ['Antarctica', 'Antarctica, Antártico, Antarctique, Антарктике'], AR: ['Argentina', 'Argentina'], AS: ['American Samoa', 'American Samoa'], AT: ['Austria', 'Österreich'], AU: ['Australia', 'Australia'], AW: ['Aruba', 'Aruba'], AX: ['Aland Islands', 'Åland'], AZ: ['Azerbaijan', 'Azərbaycan'], BA: ['Bosnia and Herzegovina', 'Bosna i Hercegovina'], BB: ['Barbados', 'Barbados'], BD: ['Bangladesh', 'গণপ্রজাতন্ত্রী বাংলাদেশ'], BE: ['Belgium', 'België, Belgique, Belgien'], BF: ['Burkina Faso', 'Burkina Faso'], BG: ['Bulgaria', 'България'], BH: ['Bahrain', 'البحرين'], BI: ['Burundi', 'Burundi'], BJ: ['Benin', 'Bénin'], BL: ['Saint-Barthélemy', 'Saint-Barthélemy'], BM: ['Bermuda', 'Bermuda'], BN: ['Brunei Darussalam', 'Brunei Darussalam'], BO: ['Bolivia', 'Bolivia, Bulibiya, Volívia, Wuliwya'], BQ: ['Caribbean Netherlands', 'Caribisch Nederland'], BR: ['Brazil', 'Brasil'], BS: ['Bahamas', 'Bahamas'], BT: ['Bhutan', 'འབྲུག་ཡུལ'], BV: ['Bouvet Island', 'Bouvetøya'], BW: ['Botswana', 'Botswana'], BY: ['Belarus', 'Беларусь'], BZ: ['Belize', 'Belize'], CA: ['Canada', 'Canada'], CC: ['Cocos (Keeling) Islands', 'Cocos (Keeling) Islands'], CD: ['Democratic Republic of the Congo (Congo-Kinshasa, former Zaire)', 'République Démocratique du Congo'], CF: ['Centrafrican Republic', 'République centrafricaine, Ködörösêse tî Bêafrîka'], CG: ['Republic of the Congo (Congo-Brazzaville)', 'République du Congo'], CH: ['Switzerland', 'Schweiz, Suisse, Svizzera, Svizra'], CI: ['Côte d\'Ivoire', 'Côte d\'Ivoire'], CK: ['Cook Islands', 'Cook Islands, Kūki ʻĀirani'], CL: ['Chile', 'Chile'], CM: ['Cameroon', 'Cameroun, Cameroon'], CN: ['China', '中国'], CO: ['Colombia', 'Colombia'], CR: ['Costa Rica', 'Costa Rica'], CU: ['Cuba', 'Cuba'], CV: ['Cabo Verde', 'Cabo Verde'], CW: ['Curaçao', 'Curaçao'], CX: ['Christmas Island', 'Christmas Island'], CY: ['Cyprus', 'Κύπρος, Kibris'], CZ: ['Czech Republic', 'Česká republika'], DE: ['Germany', 'Deutschland'], DJ: ['Djibouti', 'Djibouti, جيبوتي, Jabuuti, Gabuutih'], DK: ['Denmark', 'Danmark'], DM: ['Dominica', 'Dominica'], DO: ['Dominican Republic', 'República Dominicana'], DZ: ['Algeria', 'الجزائر'], EC: ['Ecuador', 'Ecuador'], EE: ['Estonia', 'Eesti'], EG: ['Egypt', 'مصر'], EH: ['Western Sahara', 'Sahara Occidental'], ER: ['Eritrea', 'ኤርትራ, إرتريا, Eritrea'], ES: ['Spain', 'España'], ET: ['Ethiopia', 'ኢትዮጵያ, Itoophiyaa'], FI: ['Finland', 'Suomi'], FJ: ['Fiji', 'Fiji'], FK: ['Falkland Islands', 'Falkland Islands'], FM: ['Micronesia (Federated States of)', 'Micronesia'], FO: ['Faroe Islands', 'Føroyar, Færøerne'], FR: ['France', 'France'], GA: ['Gabon', 'Gabon'], GB: ['United Kingdom', 'United Kingdom'], GD: ['Grenada', 'Grenada'], GE: ['Georgia', 'საქართველო'], GF: ['French Guiana', 'Guyane française'], GG: ['Guernsey', 'Guernsey'], GH: ['Ghana', 'Ghana'], GI: ['Gibraltar', 'Gibraltar'], GL: ['Greenland', 'Kalaallit Nunaat, Grønland'], GM: ['The Gambia', 'The Gambia'], GN: ['Guinea', 'Guinée'], GP: ['Guadeloupe', 'Guadeloupe'], GQ: ['Equatorial Guinea', 'Guiena ecuatorial, Guinée équatoriale, Guiné Equatorial'], GR: ['Greece', 'Ελλάδα'], GS: ['South Georgia and the South Sandwich Islands', 'South Georgia and the South Sandwich Islands'], GT: ['Guatemala', 'Guatemala'], GU: ['Guam', 'Guam, Guåhån'], GW: ['Guinea Bissau', 'Guiné-Bissau'], GY: ['Guyana', 'Guyana'], HK: ['Hong Kong (SAR of China)', '香港, Hong Kong'], HM: ['Heard Island and McDonald Islands', 'Heard Island and McDonald Islands'], HN: ['Honduras', 'Honduras'], HR: ['Croatia', 'Hrvatska'], HT: ['Haiti', 'Haïti, Ayiti'], HU: ['Hungary', 'Magyarország'], ID: ['Indonesia', 'Indonesia'], IE: ['Ireland', 'Ireland, Éire'], IL: ['Israel', 'ישראל'], IM: ['Isle of Man', 'Isle of Man'], IN: ['India', 'भारत, India'], IO: ['British Indian Ocean Territory', 'British Indian Ocean Territory'], IQ: ['Iraq', 'العراق, Iraq'], IR: ['Iran', 'ایران'], IS: ['Iceland', 'Ísland'], IT: ['Italy', 'Italia'], JE: ['Jersey', 'Jersey'], JM: ['Jamaica', 'Jamaica'], JO: ['Jordan', 'الأُرْدُن'], JP: ['Japan', '日本'], KE: ['Kenya', 'Kenya'], KG: ['Kyrgyzstan', 'Кыргызстан, Киргизия'], KH: ['Cambodia', 'កម្ពុជា'], KI: ['Kiribati', 'Kiribati'], KM: ['Comores', 'ﺍﻟﻘﻤﺮي, Comores, Komori'], KN: ['Saint Kitts and Nevis', 'Saint Kitts and Nevis'], KP: ['North Korea', '북조선'], KR: ['South Korea', '대한민국'], KW: ['Kuwait', 'الكويت'], KY: ['Cayman Islands', 'Cayman Islands'], KZ: ['Kazakhstan', 'Қазақстан, Казахстан'], LA: ['Laos', 'ປະຊາຊົນລາວ'], LB: ['Lebanon', 'لبنان, Liban'], LC: ['Saint Lucia', 'Saint Lucia'], LI: ['Liechtenstein', 'Liechtenstein'], LK: ['Sri Lanka', 'ශ්‍රී ලංකා, இலங்கை'], LR: ['Liberia', 'Liberia'], LS: ['Lesotho', 'Lesotho'], LT: ['Lithuania', 'Lietuva'], LU: ['Luxembourg', 'Lëtzebuerg, Luxembourg, Luxemburg'], LV: ['Latvia', 'Latvija'], LY: ['Libya', 'ليبيا'], MA: ['Morocco', 'Maroc, ⵍⵎⵖⵔⵉⴱ, المغرب'], MC: ['Monaco', 'Monaco'], MD: ['Moldova', 'Moldova, Молдавия'], ME: ['Montenegro', 'Crna Gora, Црна Гора'], MF: ['Saint Martin (French part)', 'Saint-Martin'], MG: ['Madagascar', 'Madagasikara, Madagascar'], MH: ['Marshall Islands', 'Marshall Islands'], MK: ['North Macedonia', 'Северна Македонија'], ML: ['Mali', 'Mali'], MM: ['Myanmar', 'မြန်မာ'], MN: ['Mongolia', 'Монгол Улс'], MO: ['Macao (SAR of China)', '澳門, Macau'], MP: ['Northern Mariana Islands', 'Northern Mariana Islands'], MQ: ['Martinique', 'Martinique'], MR: ['Mauritania', 'موريتانيا, Mauritanie'], MS: ['Montserrat', 'Montserrat'], MT: ['Malta', 'Malta'], MU: ['Mauritius', 'Maurice, Mauritius'], MV: ['Maldives', ''], MW: ['Malawi', 'Malawi'], MX: ['Mexico', 'México'], MY: ['Malaysia', ''], MZ: ['Mozambique', 'Mozambique'], NA: ['Namibia', 'Namibia'], NC: ['New Caledonia', 'Nouvelle-Calédonie'], NE: ['Niger', 'Niger'], NF: ['Norfolk Island', 'Norfolk Island'], NG: ['Nigeria', 'Nigeria'], NI: ['Nicaragua', 'Nicaragua'], NL: ['The Netherlands', 'Nederland'], NO: ['Norway', 'Norge, Noreg'], NP: ['Nepal', ''], NR: ['Nauru', 'Nauru'], NU: ['Niue', 'Niue'], NZ: ['New Zealand', 'New Zealand'], OM: ['Oman', 'سلطنة عُمان'], PA: ['Panama', 'Panama'], PE: ['Peru', 'Perú'], PF: ['French Polynesia', 'Polynésie française'], PG: ['Papua New Guinea', 'Papua New Guinea'], PH: ['Philippines', 'Philippines'], PK: ['Pakistan', 'پاکستان'], PL: ['Poland', 'Polska'], PM: ['Saint Pierre and Miquelon', 'Saint-Pierre-et-Miquelon'], PN: ['Pitcairn', 'Pitcairn'], PR: ['Puerto Rico', 'Puerto Rico'], PS: ['Palestinian Territory', 'Palestinian Territory'], PT: ['Portugal', 'Portugal'], PW: ['Palau', 'Palau'], PY: ['Paraguay', 'Paraguay'], QA: ['Qatar', 'قطر'], RE: ['Reunion', 'La Réunion'], RO: ['Romania', 'România'], RS: ['Serbia', 'Србија'], RU: ['Russia', 'Россия'], RW: ['Rwanda', 'Rwanda'], SA: ['Saudi Arabia', 'السعودية'], SB: ['Solomon Islands', 'Solomon Islands'], SC: ['Seychelles', 'Seychelles'], SD: ['Sudan', 'السودان'], SE: ['Sweden', 'Sverige'], SG: ['Singapore', 'Singapore'], SH: ['Saint Helena', 'Saint Helena'], SI: ['Slovenia', 'Slovenija'], SJ: ['Svalbard and Jan Mayen', 'Svalbard and Jan Mayen'], SK: ['Slovakia', 'Slovensko'], SL: ['Sierra Leone', 'Sierra Leone'], SM: ['San Marino', 'San Marino'], SN: ['Sénégal', 'Sénégal'], SO: ['Somalia', 'Somalia, الصومال'], SR: ['Suriname', 'Suriname'], ST: ['São Tomé and Príncipe', 'São Tomé e Príncipe'], SS: ['South Sudan', 'South Sudan'], SV: ['El Salvador', 'El Salvador'], SX: ['Saint Martin (Dutch part)', 'Sint Maarten'], SY: ['Syria', 'سوريا, Sūriyya'], SZ: ['eSwatini', 'eSwatini'], TC: ['Turks and Caicos Islands', 'Turks and Caicos Islands'], TD: ['Chad', 'Tchad, تشاد'], TF: ['French Southern and Antarctic Lands', 'Terres australes et antarctiques françaises'], TG: ['Togo', 'Togo'], TH: ['Thailand', 'ประเทศไทย'], TJ: ['Tajikistan', ','], TK: ['Tokelau', 'Tokelau'], TL: ['Timor-Leste', 'Timor-Leste'], TM: ['Turkmenistan', 'Türkmenistan'], TN: ['Tunisia', 'تونس, Tunisie'], TO: ['Tonga', 'Tonga'], TR: ['Turkey', 'Türkiye'], TT: ['Trinidad and Tobago', 'Trinidad and Tobago'], TV: ['Tuvalu', 'Tuvalu'], TW: ['Taiwan', 'Taiwan'], TZ: ['Tanzania', 'Tanzania'], UA: ['Ukraine', 'Україна'], UG: ['Uganda', 'Uganda'], UM: ['United States Minor Outlying Islands', 'United States Minor Outlying Islands'], US: ['United States of America', 'United States of America'], UY: ['Uruguay', 'Uruguay'], UZ: ['Uzbekistan', ''], VA: ['City of the Vatican', 'Città del Vaticano'], VC: ['Saint Vincent and the Grenadines', 'Saint Vincent and the Grenadines'], VE: ['Venezuela', 'Venezuela'], VG: ['British Virgin Islands', 'British Virgin Islands'], VI: ['United States Virgin Islands', 'United States Virgin Islands'], VN: ['Vietnam', 'Việt Nam'], VU: ['Vanuatu', 'Vanuatu'], WF: ['Wallis and Futuna', 'Wallis-et-Futuna'], WS: ['Samoa', 'Samoa'], YE: ['Yemen', 'اليَمَن'], YT: ['Mayotte', 'Mayotte'], ZA: ['South Africa', 'South Africa'], ZM: ['Zambia', 'Zambia'], ZW: ['Zimbabwe', 'Zimbabwe'], }; let supportedLocales_: any = null; let localeStats_: any = null; const loadedLocales_: any = {}; const defaultLocale_ = 'en_GB'; let currentLocale_ = defaultLocale_; function defaultLocale() { return defaultLocale_; } function localeStats() { if (!localeStats_) localeStats_ = require('./locales/index.js').stats; return localeStats_; } function supportedLocales(): string[] { if (!supportedLocales_) supportedLocales_ = require('./locales/index.js').locales; const output = []; for (const n in supportedLocales_) { if (!supportedLocales_.hasOwnProperty(n)) continue; output.push(n); } return output; } interface SupportedLocalesToLanguagesOptions { includeStats?: boolean; } function supportedLocalesToLanguages(options: SupportedLocalesToLanguagesOptions = null) { if (!options) options = {}; const stats = localeStats(); const locales = supportedLocales(); const output: StringToStringMap = {}; for (let i = 0; i < locales.length; i++) { const locale = locales[i]; output[locale] = countryDisplayName(locale); const stat = stats[locale]; if (options.includeStats && stat) { output[locale] += ` (${stat.percentDone}%)`; } } return output; } function closestSupportedLocale(canonicalName: string, defaultToEnglish: boolean = true, locales: string[] = null) { locales = locales === null ? supportedLocales() : locales; if (locales.indexOf(canonicalName) >= 0) return canonicalName; const requiredLanguage = languageCodeOnly(canonicalName).toLowerCase(); for (let i = 0; i < locales.length; i++) { const locale = locales[i]; const language = locale.split('_')[0]; if (requiredLanguage == language) return locale; } return defaultToEnglish ? 'en_GB' : null; } function countryName(countryCode: string) { const r = codeToCountry_[countryCode] ? codeToCountry_[countryCode] : null; if (!r) return ''; return r.length > 1 && !!r[1] ? r[1] : r[0]; } function languageNameInEnglish(languageCode: string) { return codeToLanguageE_[languageCode] ? codeToLanguageE_[languageCode] : ''; } function languageName(languageCode: string, defaultToEnglish: boolean = true) { if (codeToLanguage_[languageCode]) return codeToLanguage_[languageCode]; if (defaultToEnglish) return languageNameInEnglish(languageCode); return ''; } function languageCodeOnly(canonicalName: string) { if (canonicalName.length < 2) return canonicalName; return canonicalName.substr(0, 2); } function countryCodeOnly(canonicalName: string) { if (canonicalName.length <= 2) return ''; return canonicalName.substr(3); } function countryDisplayName(canonicalName: string) { const languageCode = languageCodeOnly(canonicalName); const countryCode = countryCodeOnly(canonicalName); let output = languageName(languageCode); let extraString; if (countryCode) { if (languageCode == 'zh' && countryCode == 'CN') { extraString = '简体'; // "Simplified" in "Simplified Chinese" } else { extraString = countryName(countryCode); } } if (languageCode == 'zh' && (countryCode == '' || countryCode == 'TW')) extraString = '繁體'; // "Traditional" in "Traditional Chinese" if (extraString) { output += ` (${extraString})`; } else if (countryCode) { // If we have a country code but couldn't match it to a country name, // just display the full canonical name (applies for example to es-419 // for Latin American Spanish). output += ` (${canonicalName})`; } return output; } function localeStrings(canonicalName: string) { const locale = closestSupportedLocale(canonicalName); if (loadedLocales_[locale]) return loadedLocales_[locale]; loadedLocales_[locale] = Object.assign({}, supportedLocales_[locale]); return loadedLocales_[locale]; } function setLocale(canonicalName: string) { if (currentLocale_ == canonicalName) return; currentLocale_ = closestSupportedLocale(canonicalName); } function languageCode() { return languageCodeOnly(currentLocale_); } function localesFromLanguageCode(languageCode: string, locales: string[]): string[] { return locales.filter((l: string) => { return languageCodeOnly(l) === languageCode; }); } function _(s: string, ...args: any[]): string { const strings = localeStrings(currentLocale_); let result = strings[s]; if (result === '' || result === undefined) result = s; try { return sprintf(result, ...args); } catch (error) { return `${result} ${args.join(', ')} (Translation error: ${error.message})`; } } function _n(singular: string, plural: string, n: number, ...args: any[]) { if (n > 1) return _(plural, ...args); return _(singular, ...args); } export { _, _n, supportedLocales, localesFromLanguageCode, languageCodeOnly, countryDisplayName, localeStrings, setLocale, supportedLocalesToLanguages, defaultLocale, closestSupportedLocale, languageCode, countryCodeOnly };
the_stack
import { PluginEndpointDiscovery, PluginCacheManager, } from '@backstage/backend-common'; import { CatalogClient } from '@backstage/catalog-client'; import { stringifyEntityRef } from '@backstage/catalog-model'; import { Config } from '@backstage/config'; import { NotFoundError } from '@backstage/errors'; import { GeneratorBuilder, getLocationForEntity, PreparerBuilder, PublisherBase, } from '@backstage/plugin-techdocs-node'; import express, { Response } from 'express'; import Router from 'express-promise-router'; import { Knex } from 'knex'; import { ScmIntegrations } from '@backstage/integration'; import { DocsSynchronizer, DocsSynchronizerSyncOpts } from './DocsSynchronizer'; import { createCacheMiddleware, TechDocsCache } from '../cache'; import { CachedEntityLoader } from './CachedEntityLoader'; import { DefaultDocsBuildStrategy, DocsBuildStrategy, } from './DocsBuildStrategy'; import * as winston from 'winston'; import { PassThrough } from 'stream'; /** * Required dependencies for running TechDocs in the "out-of-the-box" * deployment configuration (prepare/generate/publish all in the Backend). * * @public */ export type OutOfTheBoxDeploymentOptions = { preparers: PreparerBuilder; generators: GeneratorBuilder; publisher: PublisherBase; logger: winston.Logger; discovery: PluginEndpointDiscovery; database?: Knex; // TODO: Make database required when we're implementing database stuff. config: Config; cache: PluginCacheManager; docsBuildStrategy?: DocsBuildStrategy; buildLogTransport?: winston.transport; }; /** * Required dependencies for running TechDocs in the "recommended" deployment * configuration (prepare/generate handled externally in CI/CD). * * @public */ export type RecommendedDeploymentOptions = { publisher: PublisherBase; logger: winston.Logger; discovery: PluginEndpointDiscovery; config: Config; cache: PluginCacheManager; docsBuildStrategy?: DocsBuildStrategy; buildLogTransport?: winston.transport; }; /** * One of the two deployment configurations must be provided. * * @public */ export type RouterOptions = | RecommendedDeploymentOptions | OutOfTheBoxDeploymentOptions; /** * Typeguard to help createRouter() understand when we are in a "recommended" * deployment vs. when we are in an out-of-the-box deployment configuration. * * * @public */ function isOutOfTheBoxOption( opt: RouterOptions, ): opt is OutOfTheBoxDeploymentOptions { return (opt as OutOfTheBoxDeploymentOptions).preparers !== undefined; } /** * Creates a techdocs router. * * @public */ export async function createRouter( options: RouterOptions, ): Promise<express.Router> { const router = Router(); const { publisher, config, logger, discovery } = options; const catalogClient = new CatalogClient({ discoveryApi: discovery }); const docsBuildStrategy = options.docsBuildStrategy ?? DefaultDocsBuildStrategy.fromConfig(config); const buildLogTransport = options.buildLogTransport ?? new winston.transports.Stream({ stream: new PassThrough() }); // Entities are cached to optimize the /static/docs request path, which can be called many times // when loading a single techdocs page. const entityLoader = new CachedEntityLoader({ catalog: catalogClient, cache: options.cache.getClient(), }); // Set up a cache client if configured. let cache: TechDocsCache | undefined; const defaultTtl = config.getOptionalNumber('techdocs.cache.ttl'); if (defaultTtl) { const cacheClient = options.cache.getClient({ defaultTtl }); cache = TechDocsCache.fromConfig(config, { cache: cacheClient, logger }); } const scmIntegrations = ScmIntegrations.fromConfig(config); const docsSynchronizer = new DocsSynchronizer({ publisher, logger, buildLogTransport, config, scmIntegrations, cache, }); router.get('/metadata/techdocs/:namespace/:kind/:name', async (req, res) => { const { kind, namespace, name } = req.params; const entityName = { kind, namespace, name }; const token = getBearerToken(req.headers.authorization); // Verify that the related entity exists and the current user has permission to view it. const entity = await entityLoader.load(entityName, token); if (!entity) { throw new NotFoundError( `Unable to get metadata for '${stringifyEntityRef(entityName)}'`, ); } try { const techdocsMetadata = await publisher.fetchTechDocsMetadata( entityName, ); res.json(techdocsMetadata); } catch (err) { logger.info( `Unable to get metadata for '${stringifyEntityRef( entityName, )}' with error ${err}`, ); throw new NotFoundError( `Unable to get metadata for '${stringifyEntityRef(entityName)}'`, err, ); } }); router.get('/metadata/entity/:namespace/:kind/:name', async (req, res) => { const { kind, namespace, name } = req.params; const entityName = { kind, namespace, name }; const token = getBearerToken(req.headers.authorization); const entity = await entityLoader.load(entityName, token); if (!entity) { throw new NotFoundError( `Unable to get metadata for '${stringifyEntityRef(entityName)}'`, ); } try { const locationMetadata = getLocationForEntity(entity, scmIntegrations); res.json({ ...entity, locationMetadata }); } catch (err) { logger.info( `Unable to get metadata for '${stringifyEntityRef( entityName, )}' with error ${err}`, ); throw new NotFoundError( `Unable to get metadata for '${stringifyEntityRef(entityName)}'`, err, ); } }); // Check if docs are the latest version and trigger rebuilds if not // Responds with an event-stream that closes after the build finished // Responds with an immediate success if rebuild not needed // If a build is required, responds with a success when finished router.get('/sync/:namespace/:kind/:name', async (req, res) => { const { kind, namespace, name } = req.params; const token = getBearerToken(req.headers.authorization); const entity = await entityLoader.load({ kind, namespace, name }, token); if (!entity?.metadata?.uid) { throw new NotFoundError('Entity metadata UID missing'); } const responseHandler: DocsSynchronizerSyncOpts = createEventStream(res); // By default, techdocs-backend will only try to build documentation for an entity if techdocs.builder is set to // 'local'. If set to 'external', it will assume that an external process (e.g. CI/CD pipeline // of the repository) is responsible for building and publishing documentation to the storage provider. // Altering the implementation of the injected docsBuildStrategy allows for more complex behaviours, based on // either config or the properties of the entity (e.g. annotations, labels, spec fields etc.). const shouldBuild = await docsBuildStrategy.shouldBuild({ entity }); if (!shouldBuild) { // However, if caching is enabled, take the opportunity to check and // invalidate stale cache entries. if (cache) { await docsSynchronizer.doCacheSync({ responseHandler, discovery, token, entity, }); return; } responseHandler.finish({ updated: false }); return; } // Set the synchronization and build process if "out-of-the-box" configuration is provided. if (isOutOfTheBoxOption(options)) { const { preparers, generators } = options; await docsSynchronizer.doSync({ responseHandler, entity, preparers, generators, }); return; } responseHandler.error( new Error( "Invalid configuration. docsBuildStrategy.shouldBuild returned 'true', but no 'preparer' was provided to the router initialization.", ), ); }); // Ensures that the related entity exists and the current user has permission to view it. if (config.getOptionalBoolean('permission.enabled')) { router.use( '/static/docs/:namespace/:kind/:name', async (req, _res, next) => { const { kind, namespace, name } = req.params; const entityName = { kind, namespace, name }; const token = getBearerToken(req.headers.authorization); const entity = await entityLoader.load(entityName, token); if (!entity) { throw new NotFoundError( `Entity not found for ${stringifyEntityRef(entityName)}`, ); } next(); }, ); } // If a cache manager was provided, attach the cache middleware. if (cache) { router.use(createCacheMiddleware({ logger, cache })); } // Route middleware which serves files from the storage set in the publisher. router.use('/static/docs', publisher.docsRouter()); return router; } function getBearerToken(header?: string): string | undefined { return header?.match(/(?:Bearer)\s+(\S+)/i)?.[1]; } /** * Create an event-stream response that emits the events 'log', 'error', and 'finish'. * * @param res - the response to write the event-stream to * @returns A tuple of <log, error, finish> callbacks to emit messages. A call to 'error' or 'finish' * will close the event-stream. */ export function createEventStream( res: Response<any, any>, ): DocsSynchronizerSyncOpts { // Mandatory headers and http status to keep connection open res.writeHead(200, { Connection: 'keep-alive', 'Cache-Control': 'no-cache', 'Content-Type': 'text/event-stream', }); // client closes connection res.socket?.on('close', () => { res.end(); }); // write the event to the stream const send = (type: 'error' | 'finish' | 'log', data: any) => { res.write(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`); // res.flush() is only available with the compression middleware if (res.flush) { res.flush(); } }; return { log: data => { send('log', data); }, error: e => { send('error', e.message); res.end(); }, finish: result => { send('finish', result); res.end(); }, }; }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/fileServersMappers"; import * as Parameters from "../models/parameters"; import { BatchAIManagementClientContext } from "../batchAIManagementClientContext"; /** Class representing a FileServers. */ export class FileServers { private readonly client: BatchAIManagementClientContext; /** * Create a FileServers. * @param {BatchAIManagementClientContext} client Reference to the service client. */ constructor(client: BatchAIManagementClientContext) { this.client = client; } /** * Creates a File Server in the given workspace. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param parameters The parameters to provide for File Server creation. * @param [options] The optional parameters * @returns Promise<Models.FileServersCreateResponse> */ create(resourceGroupName: string, workspaceName: string, fileServerName: string, parameters: Models.FileServerCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.FileServersCreateResponse> { return this.beginCreate(resourceGroupName,workspaceName,fileServerName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.FileServersCreateResponse>; } /** * Deletes a File Server. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, workspaceName: string, fileServerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,workspaceName,fileServerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Gets information about a File Server. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<Models.FileServersGetResponse> */ get(resourceGroupName: string, workspaceName: string, fileServerName: string, options?: msRest.RequestOptionsBase): Promise<Models.FileServersGetResponse>; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, fileServerName: string, callback: msRest.ServiceCallback<Models.FileServer>): void; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, workspaceName: string, fileServerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.FileServer>): void; get(resourceGroupName: string, workspaceName: string, fileServerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FileServer>, callback?: msRest.ServiceCallback<Models.FileServer>): Promise<Models.FileServersGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, fileServerName, options }, getOperationSpec, callback) as Promise<Models.FileServersGetResponse>; } /** * Gets a list of File Servers associated with the specified workspace. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param [options] The optional parameters * @returns Promise<Models.FileServersListByWorkspaceResponse> */ listByWorkspace(resourceGroupName: string, workspaceName: string, options?: Models.FileServersListByWorkspaceOptionalParams): Promise<Models.FileServersListByWorkspaceResponse>; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param callback The callback */ listByWorkspace(resourceGroupName: string, workspaceName: string, callback: msRest.ServiceCallback<Models.FileServerListResult>): void; /** * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param options The optional parameters * @param callback The callback */ listByWorkspace(resourceGroupName: string, workspaceName: string, options: Models.FileServersListByWorkspaceOptionalParams, callback: msRest.ServiceCallback<Models.FileServerListResult>): void; listByWorkspace(resourceGroupName: string, workspaceName: string, options?: Models.FileServersListByWorkspaceOptionalParams | msRest.ServiceCallback<Models.FileServerListResult>, callback?: msRest.ServiceCallback<Models.FileServerListResult>): Promise<Models.FileServersListByWorkspaceResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, options }, listByWorkspaceOperationSpec, callback) as Promise<Models.FileServersListByWorkspaceResponse>; } /** * Creates a File Server in the given workspace. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param parameters The parameters to provide for File Server creation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, workspaceName: string, fileServerName: string, parameters: Models.FileServerCreateParameters, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, workspaceName, fileServerName, parameters, options }, beginCreateOperationSpec, options); } /** * Deletes a File Server. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination * of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param fileServerName The name of the file server within the specified resource group. File * server names can only contain a combination of alphanumeric characters along with dash (-) and * underscore (_). The name must be from 1 through 64 characters long. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, workspaceName: string, fileServerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, workspaceName, fileServerName, options }, beginDeleteMethodOperationSpec, options); } /** * Gets a list of File Servers associated with the specified workspace. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.FileServersListByWorkspaceNextResponse> */ listByWorkspaceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.FileServersListByWorkspaceNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByWorkspaceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.FileServerListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByWorkspaceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.FileServerListResult>): void; listByWorkspaceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FileServerListResult>, callback?: msRest.ServiceCallback<Models.FileServerListResult>): Promise<Models.FileServersListByWorkspaceNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByWorkspaceNextOperationSpec, callback) as Promise<Models.FileServersListByWorkspaceNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.fileServerName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileServer }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByWorkspaceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion, Parameters.maxResults5 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileServerListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.fileServerName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.FileServerCreateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.FileServer }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BatchAI/workspaces/{workspaceName}/fileServers/{fileServerName}", urlParameters: [ Parameters.resourceGroupName, Parameters.workspaceName, Parameters.fileServerName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByWorkspaceNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileServerListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import * as PP from '../../shared/property-path' import { arbitraryJSBlock, clearTopLevelElementUniqueIDs, isJSXArbitraryBlock, isJSXElement, isUtopiaJSXComponent, jsxArbitraryBlock, jsxAttributeOtherJavaScript, jsxAttributeValue, jsxElement, utopiaJSXComponent, defaultPropsParam, getJSXAttribute, jsxAttributesFromMap, isArbitraryJSBlock, ArbitraryJSBlock, jsxElementName, emptyComments, } from '../../shared/element-template' import { setJSXValueAtPath } from '../../shared/jsx-attributes' import { forEachRight } from '../../shared/either' import { EmptyExportsDetail, exportFunction, exportVariable, exportVariables, foldParsedTextFile, isParseFailure, isParseSuccess, parseSuccess, ParseSuccess, } from '../../shared/project-file-types' import { clearParseResultUniqueIDsAndEmptyBlocks, JustImportViewAndReact, testParseCode, testParseModifyPrint, } from './parser-printer.test-utils' import { BakedInStoryboardUID, BakedInStoryboardVariableName } from '../../model/scene-utils' import { TestAppUID, TestSceneUID } from '../../../components/canvas/ui-jsx.test-utils' import { applyPrettier } from 'utopia-vscode-common' import { JSX_CANVAS_LOOKUP_FUNCTION_NAME } from '../../shared/dom-utils' describe('JSX parser', () => { it('should add in uid attributes for elements', () => { const code = applyPrettier( `import * as React from "react"; import { View, Storyboard, Scene } from 'utopia-api'; export var App = props => { return ( <View> {<div />} </View> ) } export var ${BakedInStoryboardVariableName} = (props) => { return ( <Storyboard data-uid='${BakedInStoryboardUID}'> <Scene style={{ height: 200, left: 59, width: 200, top: 79 }} data-uid='${TestSceneUID}' > <App data-uid='${TestAppUID}' style={{ height: '100%', width: '100%' }} title='Hi there!' /> </Scene> </Storyboard> ) }`, false, ).formatted const parseResult = testParseCode(code) foldParsedTextFile( (failure) => { throw new Error(JSON.stringify(failure)) }, (success) => { const firstComponent = success.topLevelElements.find(isUtopiaJSXComponent) if (firstComponent != null) { const view = firstComponent.rootElement if (isJSXElement(view)) { expect(getJSXAttribute(view.props, 'data-uid')).not.toBeNull() const firstChild = view.children[0] if (isJSXArbitraryBlock(firstChild)) { const elementWithin = firstChild.elementsWithin[Object.keys(firstChild.elementsWithin)[0]] expect(getJSXAttribute(elementWithin.props, 'data-uid')).not.toBeNull() } else { throw new Error('First child is not an arbitrary block of code.') } } else { throw new Error('Root element not a JSX element.') } } else { throw new Error('Not a component at the root.') } }, (unparsed) => { throw new Error(JSON.stringify(unparsed)) }, parseResult, ) }) // eslint-disable-next-line jest/expect-expect it('should write updated arbitrary elements back into code', () => { const code = applyPrettier( `import * as React from "react"; import { View, Storyboard, Scene } from 'utopia-api'; export var App = props => { return ( <View data-uid='aaa'> {<div data-uid='bbb' />} </View> ) } export var ${BakedInStoryboardVariableName} = (props) => { return ( <Storyboard data-uid='${BakedInStoryboardUID}'> <Scene style={{ height: 200, left: 59, width: 200, top: 79 }} data-uid='${TestSceneUID}' > <App data-uid='${TestAppUID}' style={{ height: '100%', width: '100%' }} title='Hi there!' /> </Scene> </Storyboard> ) } `, false, ).formatted const expectedCode = applyPrettier( `import * as React from "react"; import { View, Storyboard, Scene } from 'utopia-api'; export var App = props => { return ( <View data-uid="aaa"> {<div data-uid="bbb" style={{ left: 20, top: 300 }} />} </View> ); }; export var ${BakedInStoryboardVariableName} = (props) => { return ( <Storyboard data-uid='${BakedInStoryboardUID}'> <Scene style={{ height: 200, left: 59, width: 200, top: 79 }} data-uid='${TestSceneUID}' > <App data-uid='${TestAppUID}' style={{ height: '100%', width: '100%' }} title='Hi there!' /> </Scene> </Storyboard> ) } `, false, ).formatted testParseModifyPrint('/index.js', code, expectedCode, (success: ParseSuccess) => { const firstComponent = success.topLevelElements.find(isUtopiaJSXComponent) if (firstComponent != null) { const view = firstComponent.rootElement if (isJSXElement(view)) { const firstChild = view.children[0] if (isJSXArbitraryBlock(firstChild)) { const elementWithin = firstChild.elementsWithin['bbb'] const newAttributes = setJSXValueAtPath( elementWithin.props, PP.create(['style']), jsxAttributeValue({ left: 20, top: 300 }, emptyComments), ) forEachRight(newAttributes, (updated) => { elementWithin.props = updated }) } } } return success }) }) it('Supports using top level components inside an arbitrary block', () => { const code = `import React from "react"; import { View } from "utopia-api"; var MyComp = (props) => <div data-uid='abc'/> export var whatever = props => ( <View data-uid='aaa'> {<MyComp data-uid='aab'/>} </View> ) ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const myComp = utopiaJSXComponent( 'MyComp', true, 'var', 'expression', defaultPropsParam, [], jsxElement( 'div', 'abc', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('abc', emptyComments) }), [], ), null, false, emptyComments, ) const codeBlock = jsxArbitraryBlock( `<MyComp data-uid='aab'/>`, `<MyComp data-uid='aab' />;`, `return utopiaCanvasJSXLookup("aab", { callerThis: this });`, ['React', 'MyComp', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'MyComp', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments) }), [], ), }, ) const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments) }), [codeBlock], ) const whatever = utopiaJSXComponent( 'whatever', true, 'var', 'parenthesized-expression', defaultPropsParam, [], view, null, false, emptyComments, ) const topLevelElements = [myComp, whatever].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) it('supports object destructuring in a function param', () => { const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { const arr = [ { n: 1 } ] return ( <View data-uid='aaa'> { arr.map(({ n }) => <View data-uid='aab' thing={n} /> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( ` arr.map(({ n }) => <View data-uid='aab' thing={n} /> ) `, `arr.map(({ n }) => <View data-uid='aab' thing={n} />);`, `return arr.map(function (_ref) { var n = _ref.n; return utopiaCanvasJSXLookup("aab", { n: n, callerThis: this }); });`, ['arr', 'React', 'View', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'View', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), thing: jsxAttributeOtherJavaScript( 'n', 'return n;', ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), }), [], ), }, ), ], ) const jsCode = `const arr = [ { n: 1 } ]` const transpiledJsCode = `var arr = [{ n: 1 }]; return { arr: arr };` const arbitraryBlock = arbitraryJSBlock( jsCode, transpiledJsCode, ['arr'], [JSX_CANVAS_LOOKUP_FUNCTION_NAME], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, arbitraryBlock, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) it('supports nested object destructuring in a function param', () => { const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { const arr = [ { a: { n: 1 } } ] return ( <View data-uid='aaa'> { arr.map(({ a: { n } }) => <View data-uid='aab' thing={n} /> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( ` arr.map(({ a: { n } }) => <View data-uid='aab' thing={n} /> ) `, `arr.map(({ a: { n } }) => <View data-uid='aab' thing={n} />);`, `return arr.map(function (_ref) { var n = _ref.a.n; return utopiaCanvasJSXLookup("aab", { n: n, callerThis: this }); });`, ['arr', 'React', 'View', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'View', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), thing: jsxAttributeOtherJavaScript( 'n', 'return n;', ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), }), [], ), }, ), ], ) const jsCode = `const arr = [ { a: { n: 1 } } ]` const transpiledJsCode = `var arr = [{ a: { n: 1 } }]; return { arr: arr };` const arbitraryBlock = arbitraryJSBlock( jsCode, transpiledJsCode, ['arr'], [JSX_CANVAS_LOOKUP_FUNCTION_NAME], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, arbitraryBlock, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) it('supports array destructuring in a function param', () => { const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { const arr = [ [ 1 ] ] return ( <View data-uid='aaa'> { arr.map(([ n ]) => <View data-uid='aab' thing={n} /> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const originalMapJsCode = ` arr.map(([ n ]) => <View data-uid='aab' thing={n} /> ) ` const mapJsCode = `arr.map(([n]) => <View data-uid='aab' thing={n} />);` const transpiledMapJsCode = `return arr.map(function (_ref) { var _ref2 = babelHelpers.slicedToArray(_ref, 1), n = _ref2[0]; return utopiaCanvasJSXLookup(\"aab\", { n: n, callerThis: this }); });` const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( originalMapJsCode, mapJsCode, transpiledMapJsCode, ['arr', 'React', 'View', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'View', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), thing: jsxAttributeOtherJavaScript( 'n', 'return n;', ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), }), [], ), }, ), ], ) const jsCode = `const arr = [ [ 1 ] ]` const transpiledJsCode = `var arr = [[1]]; return { arr: arr };` const arbitraryBlock = arbitraryJSBlock( jsCode, transpiledJsCode, ['arr'], [JSX_CANVAS_LOOKUP_FUNCTION_NAME], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, arbitraryBlock, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) it('supports passing down the scope to children of components', () => { const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { return ( <View data-uid='aaa'> { [1].map((n) => <div data-uid='aab'><div data-uid='aac'>{n}</div></div> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( ` [1].map((n) => <div data-uid='aab'><div data-uid='aac'>{n}</div></div> ) `, `[1].map((n) => <div data-uid='aab'><div data-uid='aac'>{n}</div></div>);`, `return [1].map(function (n) { return utopiaCanvasJSXLookup("aab", { n: n, callerThis: this }); });`, ['React', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'div', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), }), [ jsxElement( 'div', 'aac', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aac', emptyComments), }), [ jsxArbitraryBlock( `n`, `n;`, `return n;`, ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), ], ), ], ), }, ), ], ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, null, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) xit('supports nested array destructuring in a function param', () => { // FIXME Nested array destructuring doesn't work const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { const arr = [ [ [ 1 ] ] ] return ( <View data-uid='aaa'> { arr.map(([[ n ]]) => <View data-uid='aab' thing={n} /> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const mapJsCode = `arr.map(([[ n ]]) => <View data-uid='aab' thing={n} /> )` const transpiledMapJsCode = `return arr.map(function (_ref) { var _ref2 = babelHelpers.slicedToArray(_ref, 1), _ref2$ = babelHelpers.slicedToArray(_ref2[0], 1), n = _ref2$[0]; return utopiaCanvasJSXLookup(\"aab\", { n: n, callerThis: this }); });` const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( mapJsCode, mapJsCode, transpiledMapJsCode, ['arr', 'React', 'View', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'View', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), thing: jsxAttributeOtherJavaScript( 'n', 'return n;', ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), }), [], ), }, ), ], ) const jsCode = `const arr = [ [ [ 1 ] ] ]` const transpiledJsCode = `var arr = [[[1]]]; return { arr: arr };` const arbitraryBlock = arbitraryJSBlock( jsCode, transpiledJsCode, ['arr'], [JSX_CANVAS_LOOKUP_FUNCTION_NAME], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, arbitraryBlock, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) it('supports passing down the scope to children of components 2', () => { const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { return ( <View data-uid='aaa'> { [1].map((n) => <div data-uid='aab'><div data-uid='aac'>{n}</div></div> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( ` [1].map((n) => <div data-uid='aab'><div data-uid='aac'>{n}</div></div> ) `, `[1].map((n) => <div data-uid='aab'><div data-uid='aac'>{n}</div></div>);`, `return [1].map(function (n) { return utopiaCanvasJSXLookup("aab", { n: n, callerThis: this }); });`, ['React', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'div', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), }), [ jsxElement( 'div', 'aac', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aac', emptyComments), }), [ jsxArbitraryBlock( `n`, `n;`, `return n;`, ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), ], ), ], ), }, ), ], ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, null, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) xit('supports nested array destructuring in a function param 2', () => { // FIXME Nested array destructuring doesn't work const code = `import React from "react"; import { View } from "utopia-api"; export var whatever = (props) => { const arr = [ [ [ 1 ] ] ] return ( <View data-uid='aaa'> { arr.map(([[ n ]]) => <View data-uid='aab' thing={n} /> ) } </View> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const mapJsCode = `arr.map(([[ n ]]) => <View data-uid='aab' thing={n} /> )` const transpiledMapJsCode = `return arr.map(function (_ref) { var _ref2 = babelHelpers.slicedToArray(_ref, 1), _ref2$ = babelHelpers.slicedToArray(_ref2[0], 1), n = _ref2$[0]; return utopiaCanvasJSXLookup(\"aab\", { n: n, callerThis: this }); });` const view = jsxElement( 'View', 'aaa', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aaa', emptyComments), }), [ jsxArbitraryBlock( mapJsCode, mapJsCode, transpiledMapJsCode, ['arr', 'React', 'View', 'utopiaCanvasJSXLookup'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), { aab: jsxElement( 'View', 'aab', jsxAttributesFromMap({ 'data-uid': jsxAttributeValue('aab', emptyComments), thing: jsxAttributeOtherJavaScript( 'n', 'return n;', ['n'], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ), }), [], ), }, ), ], ) const jsCode = `const arr = [ [ [ 1 ] ] ]` const transpiledJsCode = `var arr = [[[1]]]; return { arr: arr };` const arbitraryBlock = arbitraryJSBlock( jsCode, transpiledJsCode, ['arr'], [JSX_CANVAS_LOOKUP_FUNCTION_NAME], expect.objectContaining({ sources: ['code.tsx'], version: 3, file: 'code.tsx', }), {}, ) const exported = utopiaJSXComponent( 'whatever', true, 'var', 'block', defaultPropsParam, [], view, arbitraryBlock, false, emptyComments, ) const topLevelElements = [exported].map(clearTopLevelElementUniqueIDs) const expectedResult = parseSuccess( JustImportViewAndReact, expect.arrayContaining(topLevelElements), expect.objectContaining({}), null, null, [exportFunction('whatever')], ) expect(actualResult).toEqual(expectedResult) }) it('circularly referenced arbitrary blocks parse and produce a combined block', () => { const code = ` import * as React from 'react' import Utopia, { Scene, Storyboard, registerModule, } from 'utopia-api' function a(n) { if (n <= 0) { return 0 } else { return b(n - 1) } } export var App = (props) => { return ( <div data-uid='aaa' style={{ width: '100%', height: '100%', backgroundColor: '#FFFFFF' }} layout={{ layoutSystem: 'pinSystem' }} >{b(5)} - {a(5)}</div> ) } function b(n) { if (n <= 0) { return 0 } else { return a(n - 1) } } export var storyboard = ( <Storyboard data-uid='bbb' layout={{ layoutSystem: 'pinSystem' }}> <Scene data-uid='ccc' style={{ position: 'absolute', left: 0, top: 0, width: 375, height: 812 }} > <App data-uid='app' /> </Scene> </Storyboard> )` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) expect(actualResult).toMatchSnapshot() }) it('Correctly maps elements within arbitrary blocks including combined blocks', () => { const code = ` import * as React from 'react' import Utopia, { Scene, Storyboard, registerModule, } from 'utopia-api' export class RenderPropsFunctionChild extends React.Component { render() { return this.props.children('huha') } } export const ParsedComponentToBreakUpArbitraryBlocks = (props) => { return <div /> } export function getPicker() { class Picker extends React.Component { renderPicker(locale) { return ( <RenderPropsFunctionChild> {(size) => { return ( <div id='nasty-div'> {locale} {size} </div> ) }} </RenderPropsFunctionChild> ) } render() { return <RenderPropsFunctionChild>{this.renderPicker}</RenderPropsFunctionChild> } } return Picker } const Thing = getPicker() export var App = (props) => { return ( <Thing data-uid={'aaa'} /> ) } export var storyboard = ( <Storyboard> <Scene style={{ position: 'absolute', left: 0, top: 0, width: 375, height: 812 }}> <App /> </Scene> </Storyboard> ) ` const parsedResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) if (isParseSuccess(parsedResult)) { const { combinedTopLevelArbitraryBlock, topLevelElements } = parsedResult const getPickerBlock = topLevelElements.find( (e) => isArbitraryJSBlock(e) && e.definedWithin.includes('getPicker'), ) as ArbitraryJSBlock const results = { alone: { elements: Object.keys(getPickerBlock.elementsWithin), js: getPickerBlock?.transpiledJavascript, }, combined: { elements: Object.keys(combinedTopLevelArbitraryBlock!.elementsWithin), js: combinedTopLevelArbitraryBlock!.transpiledJavascript, }, } // The first lookup call should match the first element, the second lookup call should match the second expect(results.alone).toMatchInlineSnapshot(` Object { "elements": Array [ "219", "971", ], "js": "function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = babelHelpers.getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = babelHelpers.getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return babelHelpers.possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === \\"undefined\\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \\"function\\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function getPicker() { var Picker = function (_React$Component) { \\"use strict\\"; babelHelpers.inherits(Picker, _React$Component); var _super = _createSuper(Picker); function Picker() { babelHelpers.classCallCheck(this, Picker); return _super.apply(this, arguments); } babelHelpers.createClass(Picker, [{ key: \\"renderPicker\\", value: function renderPicker(locale) { return utopiaCanvasJSXLookup(\\"971\\", { locale: locale, React: React, utopiaCanvasJSXLookup: utopiaCanvasJSXLookup, callerThis: this }); } }, { key: \\"render\\", value: function render() { return utopiaCanvasJSXLookup(\\"219\\", { callerThis: this }); } }]); return Picker; }(React.Component); return Picker; } return { getPicker: getPicker };", } `) // The first lookup call in getPicker should match the first element, the second lookup call should match the second expect(results.combined).toMatchInlineSnapshot(` Object { "elements": Array [ "833", "65e", ], "js": "function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = babelHelpers.getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = babelHelpers.getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return babelHelpers.possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === \\"undefined\\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \\"function\\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RenderPropsFunctionChild = function (_React$Component) { \\"use strict\\"; babelHelpers.inherits(RenderPropsFunctionChild, _React$Component); var _super = _createSuper(RenderPropsFunctionChild); function RenderPropsFunctionChild() { babelHelpers.classCallCheck(this, RenderPropsFunctionChild); return _super.apply(this, arguments); } babelHelpers.createClass(RenderPropsFunctionChild, [{ key: \\"render\\", value: function render() { return this.props.children('huha'); } }]); return RenderPropsFunctionChild; }(React.Component); function getPicker() { var Picker = function (_React$Component2) { \\"use strict\\"; babelHelpers.inherits(Picker, _React$Component2); var _super2 = _createSuper(Picker); function Picker() { babelHelpers.classCallCheck(this, Picker); return _super2.apply(this, arguments); } babelHelpers.createClass(Picker, [{ key: \\"renderPicker\\", value: function renderPicker(locale) { return utopiaCanvasJSXLookup(\\"833\\", { locale: locale, React: React, utopiaCanvasJSXLookup: utopiaCanvasJSXLookup, callerThis: this }); } }, { key: \\"render\\", value: function render() { return utopiaCanvasJSXLookup(\\"65e\\", { callerThis: this }); } }]); return Picker; }(React.Component); return Picker; } var Thing = getPicker(); return { RenderPropsFunctionChild: RenderPropsFunctionChild, getPicker: getPicker, Thing: Thing };", } `) } else { throw new Error(`Failed to parse code`) } }) it('should not add intrinsic elements to the defined elsewhere of an arbitrary block', () => { const code = `import React from "react"; export var App = (props) => { return ( <div> {[1].map(i => <someIntrinsicElement/>)} </div> ) } ` const actualResult = clearParseResultUniqueIDsAndEmptyBlocks(testParseCode(code)) const rootElement = expect.objectContaining({ name: jsxElementName('div', []), children: [ expect.objectContaining({ originalJavascript: '[1].map(i => <someIntrinsicElement/>)', definedElsewhere: ['React', JSX_CANVAS_LOOKUP_FUNCTION_NAME], }), ], }) const exported = utopiaJSXComponent( 'App', true, 'var', 'block', defaultPropsParam, [], rootElement, null, false, emptyComments, ) const expectedResult = parseSuccess( expect.objectContaining({}), expect.arrayContaining([exported]), expect.objectContaining({}), null, null, expect.objectContaining({}), ) expect(actualResult).toEqual(expectedResult) }) })
the_stack
import * as THREE from "three"; import { Transform } from "./Transform"; /** * @class ViewportCoords * * @classdesc Provides methods for calculating 2D coordinate conversions * as well as 3D projection and unprojection. * * Basic coordinates are 2D coordinates on the [0, 1] interval and * have the origin point, (0, 0), at the top left corner and the * maximum value, (1, 1), at the bottom right corner of the original * image. * * Viewport coordinates are 2D coordinates on the [-1, 1] interval and * have the origin point in the center. The bottom left corner point is * (-1, -1) and the top right corner point is (1, 1). * * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left * corner and the maximum value is (canvasWidth, canvasHeight) is in the * bottom right corner. * * 3D coordinates are in the topocentric world reference frame. */ export class ViewportCoords { private _unprojectDepth: number = 200; /** * Convert basic coordinates to canvas coordinates. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * @param {number} basicX - Basic X coordinate. * @param {number} basicY - Basic Y coordinate. * @param {HTMLElement} container - The viewer container. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D canvas coordinates. */ public basicToCanvas( basicX: number, basicY: number, container: { offsetHeight: number, offsetWidth: number }, transform: Transform, camera: THREE.Camera): number[] { const point3d: number[] = transform.unprojectBasic([basicX, basicY], this._unprojectDepth); const canvas: number[] = this.projectToCanvas(point3d, container, camera); return canvas; } /** * Convert basic coordinates to canvas coordinates safely. If 3D point is * behind camera null will be returned. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * @param {number} basicX - Basic X coordinate. * @param {number} basicY - Basic Y coordinate. * @param {HTMLElement} container - The viewer container. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point * in front of the camera, otherwise null. */ public basicToCanvasSafe( basicX: number, basicY: number, container: { offsetHeight: number, offsetWidth: number }, transform: Transform, camera: THREE.Camera): number[] { const viewport: number[] = this.basicToViewportSafe(basicX, basicY, transform, camera); if (viewport === null) { return null; } const canvas: number[] = this.viewportToCanvas(viewport[0], viewport[1], container); return canvas; } /** * Convert basic coordinates to viewport coordinates. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * @param {number} basicX - Basic X coordinate. * @param {number} basicY - Basic Y coordinate. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D viewport coordinates. */ public basicToViewport( basicX: number, basicY: number, transform: Transform, camera: THREE.Camera): number[] { const point3d: number[] = transform.unprojectBasic([basicX, basicY], this._unprojectDepth); const viewport: number[] = this.projectToViewport(point3d, camera); return viewport; } /** * Convert basic coordinates to viewport coordinates safely. If 3D point is * behind camera null will be returned. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * @param {number} basicX - Basic X coordinate. * @param {number} basicY - Basic Y coordinate. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D viewport coordinates. */ public basicToViewportSafe( basicX: number, basicY: number, transform: Transform, camera: THREE.Camera): number[] { const point3d: number[] = transform.unprojectBasic([basicX, basicY], this._unprojectDepth); const pointCamera: number[] = this.worldToCamera(point3d, camera); if (pointCamera[2] > 0) { return null; } const viewport: number[] = this.projectToViewport(point3d, camera); return viewport; } /** * Convert camera 3D coordinates to viewport coordinates. * * @param {number} pointCamera - 3D point in camera coordinate system. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D viewport coordinates. */ public cameraToViewport( pointCamera: number[], camera: THREE.Camera): number[] { const viewport: THREE.Vector3 = new THREE.Vector3().fromArray(pointCamera) .applyMatrix4(camera.projectionMatrix); return [viewport.x, viewport.y]; } /** * Get canvas pixel position from event. * * @param {Event} event - Event containing clientX and clientY properties. * @param {HTMLElement} element - HTML element. * @returns {Array<number>} 2D canvas coordinates. */ public canvasPosition(event: { clientX: number, clientY: number }, element: HTMLElement): number[] { const clientRect: ClientRect = element.getBoundingClientRect(); const canvasX: number = event.clientX - clientRect.left - element.clientLeft; const canvasY: number = event.clientY - clientRect.top - element.clientTop; return [canvasX, canvasY]; } /** * Convert canvas coordinates to basic coordinates. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * @param {number} canvasX - Canvas X coordinate. * @param {number} canvasY - Canvas Y coordinate. * @param {HTMLElement} container - The viewer container. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D basic coordinates. */ public canvasToBasic( canvasX: number, canvasY: number, container: { offsetHeight: number, offsetWidth: number }, transform: Transform, camera: THREE.Camera): number[] { const point3d: number[] = this.unprojectFromCanvas(canvasX, canvasY, container, camera) .toArray(); const basic: number[] = transform.projectBasic(point3d); return basic; } /** * Convert canvas coordinates to viewport coordinates. * * @param {number} canvasX - Canvas X coordinate. * @param {number} canvasY - Canvas Y coordinate. * @param {HTMLElement} container - The viewer container. * @returns {Array<number>} 2D viewport coordinates. */ public canvasToViewport( canvasX: number, canvasY: number, container: { offsetHeight: number, offsetWidth: number }): number[] { const [canvasWidth, canvasHeight]: number[] = this.containerToCanvas(container); const viewportX: number = 2 * canvasX / canvasWidth - 1; const viewportY: number = 1 - 2 * canvasY / canvasHeight; return [viewportX, viewportY]; } /** * Determines the width and height of the container in canvas coordinates. * * @param {HTMLElement} container - The viewer container. * @returns {Array<number>} 2D canvas coordinates. */ public containerToCanvas(container: { offsetHeight: number, offsetWidth: number }): number[] { return [container.offsetWidth, container.offsetHeight]; } /** * Determine basic distances from image to canvas corners. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * Determines the smallest basic distance for every side of the canvas. * * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} Array of basic distances as [top, right, bottom, left]. */ public getBasicDistances( transform: Transform, camera: THREE.Camera): number[] { const topLeftBasic: number[] = this.viewportToBasic(-1, 1, transform, camera); const topRightBasic: number[] = this.viewportToBasic(1, 1, transform, camera); const bottomRightBasic: number[] = this.viewportToBasic(1, -1, transform, camera); const bottomLeftBasic: number[] = this.viewportToBasic(-1, -1, transform, camera); let topBasicDistance: number = 0; let rightBasicDistance: number = 0; let bottomBasicDistance: number = 0; let leftBasicDistance: number = 0; if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) { topBasicDistance = topLeftBasic[1] > topRightBasic[1] ? -topLeftBasic[1] : -topRightBasic[1]; } if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) { rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ? topRightBasic[0] - 1 : bottomRightBasic[0] - 1; } if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) { bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ? bottomRightBasic[1] - 1 : bottomLeftBasic[1] - 1; } if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) { leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ? -bottomLeftBasic[0] : -topLeftBasic[0]; } return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance]; } /** * Determine pixel distances from image to canvas corners. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * Determines the smallest pixel distance for every side of the canvas. * * @param {HTMLElement} container - The viewer container. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left]. */ public getPixelDistances( container: { offsetHeight: number, offsetWidth: number }, transform: Transform, camera: THREE.Camera): number[] { const topLeftBasic: number[] = this.viewportToBasic(-1, 1, transform, camera); const topRightBasic: number[] = this.viewportToBasic(1, 1, transform, camera); const bottomRightBasic: number[] = this.viewportToBasic(1, -1, transform, camera); const bottomLeftBasic: number[] = this.viewportToBasic(-1, -1, transform, camera); let topPixelDistance: number = 0; let rightPixelDistance: number = 0; let bottomPixelDistance: number = 0; let leftPixelDistance: number = 0; const [canvasWidth, canvasHeight]: number[] = this.containerToCanvas(container); if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) { const basicX: number = topLeftBasic[1] > topRightBasic[1] ? topLeftBasic[0] : topRightBasic[0]; const canvas: number[] = this.basicToCanvas(basicX, 0, container, transform, camera); topPixelDistance = canvas[1] > 0 ? canvas[1] : 0; } if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) { const basicY: number = topRightBasic[0] < bottomRightBasic[0] ? topRightBasic[1] : bottomRightBasic[1]; const canvas: number[] = this.basicToCanvas(1, basicY, container, transform, camera); rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0; } if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) { const basicX: number = bottomRightBasic[1] < bottomLeftBasic[1] ? bottomRightBasic[0] : bottomLeftBasic[0]; const canvas: number[] = this.basicToCanvas(basicX, 1, container, transform, camera); bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0; } if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) { const basicY: number = bottomLeftBasic[0] > topLeftBasic[0] ? bottomLeftBasic[1] : topLeftBasic[1]; const canvas: number[] = this.basicToCanvas(0, basicY, container, transform, camera); leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0; } return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance]; } /** * Determine if an event occured inside an element. * * @param {Event} event - Event containing clientX and clientY properties. * @param {HTMLElement} element - HTML element. * @returns {boolean} Value indicating if the event occured inside the element or not. */ public insideElement(event: { clientX: number, clientY: number }, element: HTMLElement): boolean { const clientRect: ClientRect = element.getBoundingClientRect(); const minX: number = clientRect.left + element.clientLeft; const maxX: number = minX + element.clientWidth; const minY: number = clientRect.top + element.clientTop; const maxY: number = minY + element.clientHeight; return event.clientX > minX && event.clientX < maxX && event.clientY > minY && event.clientY < maxY; } /** * Project 3D world coordinates to canvas coordinates. * * @param {Array<number>} point3D - 3D world coordinates. * @param {HTMLElement} container - The viewer container. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D canvas coordinates. */ public projectToCanvas( point3d: number[], container: { offsetHeight: number, offsetWidth: number }, camera: THREE.Camera): number[] { const viewport: number[] = this.projectToViewport(point3d, camera); const canvas: number[] = this.viewportToCanvas(viewport[0], viewport[1], container); return canvas; } /** * Project 3D world coordinates to canvas coordinates safely. If 3D * point is behind camera null will be returned. * * @param {Array<number>} point3D - 3D world coordinates. * @param {HTMLElement} container - The viewer container. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D canvas coordinates. */ public projectToCanvasSafe( point3d: number[], container: { offsetHeight: number, offsetWidth: number }, camera: THREE.Camera): number[] { const pointCamera: number[] = this.worldToCamera(point3d, camera); if (pointCamera[2] > 0) { return null; } const viewport: number[] = this.projectToViewport(point3d, camera); const canvas: number[] = this.viewportToCanvas(viewport[0], viewport[1], container); return canvas; } /** * Project 3D world coordinates to viewport coordinates. * * @param {Array<number>} point3D - 3D world coordinates. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D viewport coordinates. */ public projectToViewport( point3d: number[], camera: THREE.Camera): number[] { const viewport: THREE.Vector3 = new THREE.Vector3(point3d[0], point3d[1], point3d[2]) .project(camera); return [viewport.x, viewport.y]; } /** * Uproject canvas coordinates to 3D world coordinates. * * @param {number} canvasX - Canvas X coordinate. * @param {number} canvasY - Canvas Y coordinate. * @param {HTMLElement} container - The viewer container. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 3D world coordinates. */ public unprojectFromCanvas( canvasX: number, canvasY: number, container: { offsetHeight: number, offsetWidth: number }, camera: THREE.Camera): THREE.Vector3 { const viewport: number[] = this.canvasToViewport(canvasX, canvasY, container); const point3d: THREE.Vector3 = this.unprojectFromViewport(viewport[0], viewport[1], camera); return point3d; } /** * Unproject viewport coordinates to 3D world coordinates. * * @param {number} viewportX - Viewport X coordinate. * @param {number} viewportY - Viewport Y coordinate. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 3D world coordinates. */ public unprojectFromViewport( viewportX: number, viewportY: number, camera: THREE.Camera): THREE.Vector3 { const point3d: THREE.Vector3 = new THREE.Vector3(viewportX, viewportY, 1) .unproject(camera); return point3d; } /** * Convert viewport coordinates to basic coordinates. * * @description Transform origin and camera position needs to be the * equal for reliable return value. * * @param {number} viewportX - Viewport X coordinate. * @param {number} viewportY - Viewport Y coordinate. * @param {Transform} transform - Transform of the image to unproject from. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 2D basic coordinates. */ public viewportToBasic( viewportX: number, viewportY: number, transform: Transform, camera: THREE.Camera): number[] { const point3d: number[] = new THREE.Vector3(viewportX, viewportY, 1) .unproject(camera) .toArray(); const basic: number[] = transform.projectBasic(point3d); return basic; } /** * Convert viewport coordinates to canvas coordinates. * * @param {number} viewportX - Viewport X coordinate. * @param {number} viewportY - Viewport Y coordinate. * @param {HTMLElement} container - The viewer container. * @returns {Array<number>} 2D canvas coordinates. */ public viewportToCanvas( viewportX: number, viewportY: number, container: { offsetHeight: number, offsetWidth: number }): number[] { const [canvasWidth, canvasHeight]: number[] = this.containerToCanvas(container); const canvasX: number = canvasWidth * (viewportX + 1) / 2; const canvasY: number = -canvasHeight * (viewportY - 1) / 2; return [canvasX, canvasY]; } /** * Convert 3D world coordinates to 3D camera coordinates. * * @param {number} point3D - 3D point in world coordinate system. * @param {THREE.Camera} camera - Camera used in rendering. * @returns {Array<number>} 3D camera coordinates. */ public worldToCamera( point3d: number[], camera: THREE.Camera): number[] { const pointCamera: THREE.Vector3 = new THREE.Vector3(point3d[0], point3d[1], point3d[2]) .applyMatrix4(camera.matrixWorldInverse); return pointCamera.toArray(); } }
the_stack
import { InspectorHost } from '@bfemulator/sdk-client'; import { Splitter } from '@bfemulator/ui-react'; import { IBotConfiguration, IQnAService, ServiceTypes } from 'botframework-config/lib/schema'; import * as React from 'react'; import * as styles from './App.scss'; import AppStateAdapter from './AppStateAdapter'; import { Answer } from './Models/QnAMakerModels'; import { QnAMakerTraceInfo } from './Models/QnAMakerTraceInfo'; import { QnAKbInfo, QnAMakerClient } from './QnAMaker/Client'; import AnswersView from './Views/AnswersView/AnswersView'; import PhrasingsView from './Views/PhrasingsView/PhrasingsView'; import QnAMakerHeader from './Views/QnAMakerHeader/QnAMakerHeader'; const $host: InspectorHost = (window as any).host; const QnAApiBasePath = 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0'; const TrainAccessoryId = 'train'; const PublishAccessoryId = 'publish'; const AccessoryDefaultState = 'default'; const AccessoryWorkingState = 'working'; const persistentStateKey = Symbol('persistentState').toString(); export interface AppState { id: string; traceInfo: QnAMakerTraceInfo; qnaService: IQnAService | null; persistentState: { [key: string]: PersistentAppState }; phrasings: string[]; answers: Answer[]; selectedAnswer: Answer | null; } export interface PersistentAppState { pendingTrain: boolean; pendingPublish: boolean; } export class App extends React.Component<any, AppState> { public client: QnAMakerClient; public static getQnAServiceFromBot(bot: IBotConfiguration, kbId: string): IQnAService | null { if (!bot || !bot.services || !kbId) { return null; } kbId = kbId.toLowerCase(); const qnaServices = bot.services.filter(s => s.type === ServiceTypes.QnA) as IQnAService[]; const qnaService = qnaServices.find(ls => ls.kbId.toLowerCase() === kbId); if (qnaService) { return qnaService; } return null; } constructor(props: any, context: any) { super(props, context); this.state = { id: '', traceInfo: { message: {}, queryResults: [], knowledgeBaseId: '', scoreThreshold: 0.3, top: 1, strictFilters: null, metadataBoost: null, }, qnaService: null, persistentState: this.loadAppPersistentState() || {}, phrasings: [], answers: [], selectedAnswer: null, }; } public componentWillMount() { // Attach a handler to listen on inspect events if (!this.runningDetached()) { $host.on('inspect', async (obj: any) => { const appState = new AppStateAdapter(obj); appState.qnaService = App.getQnAServiceFromBot($host.bot, appState.traceInfo.knowledgeBaseId); appState.persistentState = this.state.persistentState; this.setState(appState); if (appState.qnaService !== null) { this.client = new QnAMakerClient({ kbId: appState.traceInfo.knowledgeBaseId, baseUri: QnAApiBasePath, subscriptionKey: appState.qnaService.subscriptionKey, } as QnAKbInfo); } $host.setInspectorTitle('QnAMaker'); $host.setAccessoryState(TrainAccessoryId, AccessoryDefaultState); $host.setAccessoryState(PublishAccessoryId, AccessoryDefaultState); $host.enableAccessory( TrainAccessoryId, this.state.persistentState[this.state.id] && this.state.persistentState[this.state.id].pendingTrain && this.state.selectedAnswer !== null ); $host.enableAccessory( PublishAccessoryId, this.state.persistentState[this.state.id] && this.state.persistentState[this.state.id].pendingPublish ); }); $host.on('accessory-click', async (id: string) => { switch (id) { case TrainAccessoryId: await this.train(); break; case PublishAccessoryId: await this.publish(); break; default: break; } }); $host.on('bot-updated', (bot: IBotConfiguration) => { this.setState({ qnaService: App.getQnAServiceFromBot(bot, this.state.traceInfo.knowledgeBaseId), }); }); $host.on('theme', async (themeInfo: { themeName: string; themeComponents: string[] }) => { const oldThemeComponents = document.querySelectorAll<HTMLLinkElement>('[data-theme-component="true"]'); const head = document.querySelector<HTMLHeadElement>('head') as HTMLHeadElement; const fragment = document.createDocumentFragment(); const promises: Promise<any>[] = []; // Create the new links for each theme component themeInfo.themeComponents.forEach(themeComponent => { const link = document.createElement<'link'>('link'); promises.push( new Promise(resolve => { link.addEventListener('load', resolve); }) ); link.href = themeComponent; link.rel = 'stylesheet'; link.setAttribute('data-theme-component', 'true'); fragment.appendChild(link); }); head.insertBefore(fragment, head.firstElementChild); // Wait for all the links to load their css await Promise.all(promises); // Remove the old links Array.prototype.forEach.call(oldThemeComponents, (themeComponent: HTMLLinkElement) => { if (themeComponent.parentElement) { themeComponent.parentElement.removeChild(themeComponent); } }); }); } } public render() { if (this.state.qnaService === null) { const text = 'Unable to find a QnA Maker service with Knowledge Base ID ' + this.state.traceInfo.knowledgeBaseId + '. Please add a QnA Maker service to your bot.'; return ( <div className={styles.noService}> <p>{text}</p> </div> ); } return ( <div className={styles.app}> <QnAMakerHeader knowledgeBaseId={this.state.traceInfo.knowledgeBaseId} knowledgeBaseName={this.state.qnaService.name} /> <Splitter orientation={'vertical'} primaryPaneIndex={0} minSizes={{ 0: 306, 1: 306 }} initialSizes={{ 0: 306 }}> <PhrasingsView phrasings={this.state.phrasings} addPhrasing={this.addPhrasing()} removePhrasing={this.removePhrasing()} /> <AnswersView answers={this.state.answers} selectedAnswer={this.state.selectedAnswer} selectAnswer={this.selectAnswer()} addAnswer={this.addAnswer()} /> </Splitter> </div> ); } private async train() { $host.setAccessoryState(TrainAccessoryId, AccessoryWorkingState); let success = false; try { if (this.state.qnaService !== null) { if (this.state.selectedAnswer) { const newQuestion = this.state.selectedAnswer.id === 0; const questions = newQuestion ? this.state.phrasings : { add: this.state.phrasings }; const metadata = newQuestion ? [] : { add: [], delete: [] }; const qnaList = { qnaList: [ { id: this.state.selectedAnswer.id, answer: this.state.selectedAnswer.text, source: 'Editorial', questions, metadata, }, ], }; const body = newQuestion ? { add: qnaList } : { update: qnaList }; const response = await this.client.updateKnowledgebase(this.state.traceInfo.knowledgeBaseId, body); success = response.status === 200; $host.logger.log('Successfully trained Knowledge Base ' + this.state.traceInfo.knowledgeBaseId); $host.trackEvent('qna_trainSuccess'); } else { $host.logger.error('Select an answer before trying to train.'); } } } catch (err) { $host.logger.error(err.message); $host.trackEvent('qna_trainFailure', { error: err.message }); } finally { $host.setAccessoryState(TrainAccessoryId, AccessoryDefaultState); this.setAppPersistentState({ pendingPublish: success, pendingTrain: !success, }); } } private async publish(): Promise<void> { $host.setAccessoryState(PublishAccessoryId, AccessoryWorkingState); let success = false; try { if (this.state.qnaService !== null) { $host.logger.log('Publishing...'); const response = await this.client.publish(this.state.traceInfo.knowledgeBaseId); success = response.status === 204; if (success) { $host.logger.log('Successfully published Knowledge Base ' + this.state.traceInfo.knowledgeBaseId); $host.trackEvent('qna_publishSuccess'); } else { $host.logger.error('Request to QnA Maker failed. ' + response.statusText); $host.trackEvent('qna_publishFailure', { error: response.statusText }); } } } catch (err) { $host.logger.error(err.message); $host.trackEvent('qna_publishFailure', { error: err.message }); } finally { $host.setAccessoryState(PublishAccessoryId, AccessoryDefaultState); } this.setAppPersistentState({ pendingPublish: !success, pendingTrain: false, }); } private runningDetached() { return !$host; } private selectAnswer() { return (newAnswer: Answer) => { this.setState({ selectedAnswer: newAnswer, }); this.setAppPersistentState({ pendingPublish: false, pendingTrain: true, }); }; } private addPhrasing() { return (phrase: string) => { const newPhrases: string[] = this.state.phrasings; newPhrases.push(phrase); this.setState({ phrasings: newPhrases, }); this.setAppPersistentState({ pendingPublish: false, pendingTrain: this.state.selectedAnswer !== null, }); }; } private removePhrasing() { return (phrase: string) => { const newPhrases: string[] = this.state.phrasings; const phrasesIndex = newPhrases.indexOf(phrase); newPhrases.splice(phrasesIndex, 1); this.setState({ phrasings: newPhrases, }); this.setAppPersistentState({ pendingPublish: false, pendingTrain: this.state.selectedAnswer !== null, }); }; } private addAnswer() { return (newAnswer: string) => { const answerObj = { filters: {}, id: 0, score: 0, text: newAnswer, }; const newAnswers: Answer[] = this.state.answers; newAnswers.push(answerObj); this.setState({ answers: newAnswers, selectedAnswer: answerObj, }); this.setAppPersistentState({ pendingPublish: false, pendingTrain: this.state.selectedAnswer !== null, }); }; } private setAppPersistentState(persistentState: PersistentAppState) { // eslint-disable-next-line react/no-direct-mutation-state this.state.persistentState[this.state.id] = persistentState; this.setState({ persistentState: this.state.persistentState }); localStorage.setItem(persistentStateKey, JSON.stringify(this.state.persistentState)); $host.enableAccessory(TrainAccessoryId, persistentState.pendingTrain); $host.enableAccessory(PublishAccessoryId, persistentState.pendingPublish); } private loadAppPersistentState(): { [key: string]: PersistentAppState } { const persisted = localStorage.getItem(persistentStateKey); if (persisted !== null) { return JSON.parse(persisted); } return { '': { pendingPublish: false, pendingTrain: true, }, }; } }
the_stack
// tslint:disable:no-unused-expression max-func-body-length promise-function-async max-line-length no-unnecessary-class // tslint:disable:no-non-null-assertion object-literal-key-quotes variable-name no-constant-condition import * as assert from 'assert'; import { isNullOrUndefined } from 'util'; import { DeploymentTemplateDoc } from "../extension.bundle"; import { newParamValueCompletionLabel } from './support/constants'; import { IDeploymentParametersFile, IDeploymentTemplate } from "./support/diagnostics"; import { parseParametersWithMarkers, parseTemplate } from "./support/parseTemplate"; suite("Parameter file completions", () => { const emptyTemplate: string = `{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [] }`; function createParamsCompletionsTest( testName: string, params: string | Partial<IDeploymentParametersFile>, template: string | Partial<IDeploymentTemplate> | undefined, options: { cursorIndex?: number; tabSize?: number; }, // Can either be an array of completion names, or an array of // [completion name, insert text] tuples expectedNamesAndInsertTexts: ([string, string] | string)[] ): void { const fullName = isNullOrUndefined(options.cursorIndex) ? testName : `${testName}, index=${options.cursorIndex}`; test(fullName, async () => { let dt: DeploymentTemplateDoc | undefined = template ? parseTemplate(template) : undefined; const { dp, markers: { cursor } } = parseParametersWithMarkers(params); // tslint:disable-next-line: strict-boolean-expressions const cursorIndex = !isNullOrUndefined(options.cursorIndex) ? options.cursorIndex : cursor?.index; if (isNullOrUndefined(cursorIndex)) { assert.fail(`Expected either a cursor index in options or a <!cursor!> in the parameters file`); } const pc = dp.getContextFromDocumentCharacterIndex(cursorIndex, dt); const completions = await pc.getCompletionItems("", options.tabSize ?? 4); const completionNames = completions.items.map(c => c.label).sort(); const completionInserts = completions.items.map(c => c.insertText).sort(); const expectedNames = (<unknown[]>expectedNamesAndInsertTexts).map(e => Array.isArray(e) ? <string>e[0] : <string>e).sort(); let expectedInsertTexts: string[] | undefined; if (expectedNamesAndInsertTexts.every((e: [string, string] | string) => Array.isArray(e))) { expectedNamesAndInsertTexts = (<[string, string][]>expectedNamesAndInsertTexts).map(e => e[1]).sort(); } assert.deepStrictEqual(completionNames, expectedNames, "Completion names didn't match"); if (expectedInsertTexts !== undefined) { assert.deepStrictEqual(completionInserts, expectedInsertTexts, "Completion insert texts didn't match"); } }); } // ========================= suite("Completions for new parameters", async () => { suite("Params file with missing parameters section - no completions anywhere", () => { const dpWithNoParametersSection: string = `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0" }`; for (let i = 0; i < dpWithNoParametersSection.length + 1; ++i) { createParamsCompletionsTest( "missing parameters section", dpWithNoParametersSection, undefined, { cursorIndex: i }, []); } }); // NOTE: The canAddPropertyHere test under ParametersPositionContext.test.ts is very // thorough about testing where parameter insertions are allowed, don't need to be // thorough about that here, just the results from the completion list. createParamsCompletionsTest( "No associated template file - no missing param completions", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { <!cursor!> } }`, undefined, {}, [ newParamValueCompletionLabel ]); createParamsCompletionsTest( "Template has no parameters - only new param completions available", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { <!cursor!> } }`, emptyTemplate, {}, [ newParamValueCompletionLabel ]); suite("Offer completions for properties from template that aren't already defined in param file", () => { createParamsCompletionsTest( "2 in template, 0 in params", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { <!cursor!> } }`, { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "parameters": { "p10": { "type": "int" }, "p2": { "type": "string" } } }, {}, [ `"p2"`, `"p10"`, newParamValueCompletionLabel ]); createParamsCompletionsTest( "2 in template, 1 in params", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { "p2": { "value": "string" }, <!cursor!> } }`, { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "parameters": { "p10": { "type": "int" }, "p2": { "type": "string" } } }, {}, [ // p2 already exists in param file `"p10"`, newParamValueCompletionLabel ]); createParamsCompletionsTest( "2 in template, 1 in params, different casing", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { "PARAmeter2": { "value": "string" }, <!cursor!> } }`, { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "parameters": { "Parameter10": { "type": "int" }, "Parameter2": { "type": "string" } } }, {}, [ // parameter2 already exists in param file `"Parameter10"`, // Use casing in template file newParamValueCompletionLabel ]); createParamsCompletionsTest( "3 in template, 1 in params, different casing, cursor between two existing params", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { "Parameter2": { "value": "string" }, <!cursor!> "Parameter10": { "value": "string" } } }`, { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "parameters": { "Parameter10": { "type": "int" }, "Parameter2": { "type": "string" }, "Parameter30": { "type": "string" } } }, {}, [ // parameter2 already exists in param file `"Parameter30"`, newParamValueCompletionLabel ]); createParamsCompletionsTest( "2 in template, all of them in param file already", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { "Parameter2": { "value": "string" }, "Parameter10": { "value": "string" }, <!cursor!> } }`, { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "parameters": { "Parameter10": { "type": "int" }, "Parameter2": { "type": "string" } } }, {}, [ newParamValueCompletionLabel ]); createParamsCompletionsTest( "1 optional, 1 required", `{ $schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", "contentVersion": "1.0.0.0", "parameters": { <!cursor!> } }`, { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "parameters": { "p1optional": { "type": "string", "defaultValue": "a" }, "p2required": { "type": "string" } } }, {}, [ `"p1optional"`, `"p2required"`, newParamValueCompletionLabel ]); }); }); });
the_stack
import { v3, Vec3 } from "../../math/Vec3"; import { DistanceResult } from '../../alg/result'; import { Segment } from './Segment'; import { delta4 } from '../../math/Math'; import { Ray } from './Ray'; import { Triangle } from './Triangle'; import { Polyline } from './Polyline'; import { Plane } from "./Plane"; const _v1 = new Vec3;; export class Line { direction: Vec3; constructor(public origin: Vec3 = v3(), public end: Vec3 = v3()) { this.direction = this.end .clone() .sub(this.origin) .normalize(); } set(origin: Vec3, end: Vec3) { this.origin.copy(origin) this.end.copy(end); return this; } distancePoint(pt: Vec3): DistanceResult { var res: DistanceResult = pt.distanceLine(this)!; // res.closests?.reverse(); // res.parameters?.reverse(); return res; } distanceSegment(segment: Segment): DistanceResult { var result: DistanceResult = { parameters: [], closests: [] }; var segCenter = segment.center; var segDirection = segment.direction; var segExtent = segment.extent * 0.5; var diff = this.origin.clone().sub(segCenter); var a01 = - this.direction.dot(segDirection); var b0 = diff.dot(this.direction); var s0, s1; if (Math.abs(a01) < 1) { // 判断是否平行 var det = 1 - a01 * a01; var extDet = segExtent * det; var b1 = -diff.dot(segDirection); s1 = a01 * b0 - b1; if (s1 >= -extDet) { if (s1 <= extDet) { // Two interior points are closest, one on the this // and one on the segment. s0 = (a01 * b1 - b0) / det; s1 /= det; } else { // The endpoint e1 of the segment and an interior // point of the this are closest. s1 = segExtent; s0 = -(a01 * s1 + b0); } } else { // The endpoint e0 of the segment and an interior point // of the this are closest. s1 = -segExtent; s0 = -(a01 * s1 + b0); } } else { // The this and segment are parallel. Choose the closest pair // so that one point is at segment origin. s1 = 0; s0 = -b0; } result.parameters![0] = s0; result.parameters![1] = s1; result.closests![0] = this.direction.clone().multiplyScalar(s0).add(this.origin); result.closests![1] = segDirection.clone().multiplyScalar(s1).add(segCenter); diff = result.closests![0].clone().sub(result.closests![1]); result.distanceSqr = diff.dot(diff); result.distance = Math.sqrt(result.distanceSqr); return result; } //---距离------------- /** * 直线到直线的距离 * 参数与最近点顺序一致 * @param {Line} line */ distanceLine(line: Line) { var result: DistanceResult = { parameters: [], closests: [] }; var diff = this.origin.clone().sub(line.origin); var a01 = -this.direction.dot(line.direction); var b0 = diff.dot(this.direction); var s0, s1; if (Math.abs(a01) < 1) { var det = 1 - a01 * a01; var b1 = -diff.dot(line.direction); s0 = (a01 * b1 - b0) / det; s1 = (a01 * b0 - b1) / det; } else { s0 = -b0; s1 = 0; } result.parameters![0] = s0; result.parameters![1] = s1; result.closests![0] = this.direction .clone() .multiplyScalar(s0) .add(this.origin); result.closests![1] = line.direction .clone() .multiplyScalar(s1) .add(line.origin); diff = result.closests![0].clone().sub(result.closests![1]); result.distanceSqr = diff.dot(diff); result.distance = Math.sqrt(result.distanceSqr); return result; } /** * 直线与射线的距离 * @param {Ray} ray */ distanceRay(ray: Ray): DistanceResult { const result: DistanceResult = { parameters: [], closests: [] }; var diff = this.origin.clone().sub(ray.origin); var a01 = - this.direction.dot(ray.direction); var b0 = diff.dot(this.direction); var s0, s1; if (Math.abs(a01) < 1) { var b1 = -diff.dot(ray.direction); s1 = a01 * b0 - b1; if (s1 >= 0) { //在最近点在射线上,相当于直线与直线最短距离 var det = 1 - a01 * a01; s0 = (a01 * b1 - b0) / det; s1 /= det; } else { // 射线的起始点是离直线的最近点 s0 = -b0; s1 = 0; } } else { s0 = -b0; s1 = 0; } result.parameters![0] = s0; result.parameters![1] = s1; result.closests![0] = this.direction.clone().multiplyScalar(s0).add(this.origin); result.closests![1] = ray.direction.clone().multiplyScalar(s1).add(ray.origin); diff = result.closests![0].clone().sub(result.closests![1]); result.distanceSqr = diff.dot(diff); result.distance = Math.sqrt(result.distanceSqr); return result; } /** * * @param triangle */ distanceTriangle(triangle: Triangle): DistanceResult { function Orthonormalize(numInputs: any, v: any, robust = false) { if (v && 1 <= numInputs && numInputs <= 3) { var minLength = v[0].length(); v[0].normalize(); for (var i = 1; i < numInputs; ++i) { for (var j = 0; j < i; ++j) { var dot = v[i].dot(v[j]); v[i].sub(v[j].clone().multiplyScalar(dot)); } var length = v[i].length(); v[i].normalize(); if (length < minLength) { minLength = length; } } return minLength; } return 0; } function ComputeOrthogonalComplement(numInputs: any, v: any, robust = false) { if (numInputs === 1) { if (Math.abs(v[0][0]) > Math.abs(v[0][1])) { v[1] = v3(- v[0].z, 0, +v[0].x) } else { v[1] = v3(0, + v[0].z, -v[0].y) }; numInputs = 2; } if (numInputs == 2) { v[2] = v[0].clone().cross(v[1]); return Orthonormalize(3, v, robust); } return 0; } const result: DistanceResult = { closests: [], parameters: [], triangleParameters: [], }; // Test if line intersects triangle. If so, the squared distance // is zero. var edge0 = triangle.p1.clone().sub(triangle.p0); var edge1 = triangle.p2.clone().sub(triangle.p0); var normal = edge0.clone().cross(edge1).normalize(); var NdD = normal.dot(this.direction); if (Math.abs(NdD) >= delta4) { // The line and triangle are not parallel, so the line // intersects/ the plane of the triangle. var diff = this.origin.clone().sub(triangle.p0); var basis = new Array(3); // {D, U, V} basis[0] = this.direction; ComputeOrthogonalComplement(1, basis); var UdE0 = basis[1].dot(edge0); var UdE1 = basis[1].dot(edge1); var UdDiff = basis[1].dot(diff); var VdE0 = basis[2].dot(edge0); var VdE1 = basis[2].dot(edge1); var VdDiff = basis[2].dot(diff); var invDet = 1 / (UdE0 * VdE1 - UdE1 * VdE0); // Barycentric coordinates for the point of intersection. var b1 = (VdE1 * UdDiff - UdE1 * VdDiff) * invDet; var b2 = (UdE0 * VdDiff - VdE0 * UdDiff) * invDet; var b0 = 1 - b1 - b2; if (b0 >= 0 && b1 >= 0 && b2 >= 0) { // Line parameter for the point of intersection. var DdE0 = this.direction.dot(edge0); var DdE1 = this.direction.dot(edge1); var DdDiff = this.direction.dot(diff); result.lineParameter = b1 * DdE0 + b2 * DdE1 - DdDiff; // Barycentric coordinates for the point of intersection. result.triangleParameters![0] = b0; result.triangleParameters![1] = b1; result.triangleParameters![2] = b2; // The intersection point is inside or on the triangle. result.closests![0] = this.direction.clone().multiplyScalar(result.lineParameter).add(this.origin); result.closests![1] = edge0.multiplyScalar(b1).add(edge1.multiplyScalar(b2)).add(triangle.p0); result.distance = 0; result.distanceSqr = 0; return result; } } // Either (1) the line is not parallel to the triangle and the // point of intersection of the line and the plane of the triangle // is outside the triangle or (2) the line and triangle are // parallel. Regardless, the closest point on the triangle is on // an edge of the triangle. Compare the line to all three edges // of the triangle. result.distance = +Infinity; result.distanceSqr = +Infinity; for (var i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { var segCenter = triangle[i0].clone().add(triangle[i1]).multiplyScalar(0.5); var segDirection = triangle[i1].clone().sub(triangle[i0]); var segExtent = 0.5 * segDirection.length(); segDirection.normalize(); var segment = new Segment(triangle[i0], triangle[i1]); var lsResult = this.distanceSegment(segment); if (lsResult.distanceSqr! < result.distanceSqr!) { result.distanceSqr = lsResult.distanceSqr; result.distance = lsResult.distance; result.lineParameter = lsResult.parameters![0]; result.triangleParameters![i0] = 0.5 * (1 - lsResult.parameters![0] / segExtent); result.triangleParameters![i1] = 1 - result.triangleParameters![i0]; result.triangleParameters![3 - i0 - i1] = 0; result.closests![0] = lsResult.closests![0]; result.closests![1] = lsResult.closests![1]; } } return result; } distancePolyline(polyline: Polyline<Vec3> | Vec3[]): DistanceResult { const polyl: any = (polyline as any)._array || polyline as any; let result: DistanceResult | any = null; var maodian: number = -1; for (let i = 0; i < polyl.length - 1; i++) { const segment = new Segment(polyl[i], polyl[i + 1]); var oneres: DistanceResult = this.distanceSegment(segment) as any; if (!result || (result as any).distance < (oneres as any).distance) { result = oneres; } if ((result as any).distance < delta4) { maodian = i; break; } } return { distance: result?.distance, distanceSqr: result?.distanceSqr, parameters: result?.parameters, closests: result?.closests, segmentIndex: maodian, } } //---intersect-------------------------- /** * 线与平面相交 * @param plane * @param result */ intersectPlane(plane: Plane, result?: Vec3): Vec3 | undefined { if (!result) result = new Vec3(); const direction = this.direction; const denominator = plane.normal.dot(direction); if (denominator === 0) { // line is coplanar, return origin if (this.distancePoint(this.origin).distance === 0) { return result.copy(this.origin); } // Unsure if this is the correct method to handle this case. return; } const t = -(this.origin.dot(plane.normal) - plane.w) / denominator; if (t < 0 || t > 1) { return; } return result.copy(direction).multiplyScalar(t).add(this.origin); } } export function line(start?: Vec3, end?: Vec3) { return new Line(start, end); }
the_stack
import * as vscode from 'vscode'; import * as fs from 'fs-extra'; import * as chai from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { version as currentExtensionVersion, dependencies as extDeps } from '../../package.json'; import { ExtensionUtil } from '../../extension/util/ExtensionUtil'; import { DependencyManager } from '../../extension/dependencies/DependencyManager'; import { CommandUtil } from '../../extension/util/CommandUtil'; import { TestUtil } from '../TestUtil'; import { GlobalState, ExtensionData, DEFAULT_EXTENSION_DATA } from '../../extension/util/GlobalState.js'; import { Dependencies, defaultDependencies, DependencyProperties } from '../../extension/dependencies/Dependencies'; import * as semver from 'semver'; import * as OS from 'os'; chai.should(); chai.use(chaiAsPromised); chai.use(sinonChai); const should: Chai.Should = chai.should(); const validDependencies: Dependencies = { docker: { ...defaultDependencies.required.docker, version: '18.1.2', }, systemRequirements: { ...defaultDependencies.required.systemRequirements, complete: true }, node: { ...defaultDependencies.optional.node, version: '10.15.3', }, npm: { ...defaultDependencies.optional.npm, version: '6.4.1', }, go: { ...defaultDependencies.optional.go, version: '2.0.0', }, goExtension: { ...defaultDependencies.optional.goExtension, version: '1.0.0' }, java: { ...defaultDependencies.optional.java, version: '1.8.0', }, javaLanguageExtension: { ...defaultDependencies.optional.javaLanguageExtension, version: '1.0.0' }, javaDebuggerExtension: { ...defaultDependencies.optional.javaDebuggerExtension, version: '1.0.0' }, javaTestRunnerExtension: { ...defaultDependencies.optional.javaTestRunnerExtension, version: '1.0.0' }, nodeTestRunnerExtension: { ...defaultDependencies.optional.nodeTestRunnerExtension, version: '1.0.0' }, ibmCloudAccountExtension: { ...defaultDependencies.optional.ibmCloudAccountExtension, version: '1.0.0', }, }; // tslint:disable no-unused-expression describe('DependencyManager Tests', () => { const mySandBox: sinon.SinonSandbox = sinon.createSandbox(); let getExtensionLocalFabricSetting: sinon.SinonStub; beforeEach(async () => { getExtensionLocalFabricSetting = mySandBox.stub(ExtensionUtil, 'getExtensionLocalFabricSetting').returns(true); }); afterEach(async () => { mySandBox.restore(); }); describe('isValidDependency', () => { let semverSatisfiesStub: sinon.SinonStub; let dependencyManager: DependencyManager; beforeEach(async () => { mySandBox.stub(process, 'platform').value('linux'); // We don't have any Linux only prereqs, so this is okay. dependencyManager = DependencyManager.instance(); getExtensionLocalFabricSetting.returns(false); semverSatisfiesStub = mySandBox.stub(semver, 'satisfies').returns(false); }); it(`should return false when dependency version is incorrect, absent or incomplete`, async () => { const dependenciesWithoutVersions: object = [defaultDependencies.required, defaultDependencies.optional]; const dependenciesKeys: string[] = Object.getOwnPropertyNames(dependenciesWithoutVersions); for (let i: number = 0; i < dependenciesKeys.length; i++) { const result: boolean = dependencyManager.isValidDependency(dependenciesWithoutVersions[dependenciesKeys[i]]); try { result.should.equal(false); } catch (error) { throw new Error(`Dependency ${dependenciesKeys[i]} should not be valid - ${error.message}`); } } }); it(`should return true when dependency version is correct, present or complete`, async () => { semverSatisfiesStub.returns(true); const dependenciesKeys: string[] = Object.getOwnPropertyNames(validDependencies); for (let i: number = 0; i < dependenciesKeys.length; i++) { const result: boolean = dependencyManager.isValidDependency(validDependencies[dependenciesKeys[i]]); try { result.should.equal(true); } catch (error) { throw new Error(`Dependency ${dependenciesKeys[i]} should be valid - ${error.message}`); } } }); it(`should be able to handle unknown dependencies`, async () => { const dependencies: any = { docker: { name: 'some_dependency', version: '0.0.1', } }; const result: boolean = dependencyManager.isValidDependency(dependencies); result.should.equal(false); }); }); describe('hasPreReqsInstalled', () => { let getPreReqVersionsStub: sinon.SinonStub; beforeEach(async () => { getPreReqVersionsStub = mySandBox.stub(DependencyManager.prototype, 'getPreReqVersions'); }); it(`should return false if there's no Docker version`, async () => { const dependencies: Dependencies = { ...validDependencies, docker: { ...defaultDependencies.required.docker, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if Docker version is less than required version`, async () => { const dependencies: Dependencies = { ...validDependencies, docker: { ...defaultDependencies.required.docker, version: '16.0.0', } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if they haven't confirmed to have system requirements`, async () => { const dependencies: Dependencies = { ...validDependencies, systemRequirements: { ...defaultDependencies.required.systemRequirements, complete: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return true if all prereqs have been met`, async () => { mySandBox.stub(process, 'platform').value('linux'); // We don't have any Linux only prereqs, so this is okay. const dependencies: any = { docker: { ...defaultDependencies.required.docker, version: '18.1.2', }, systemRequirements: { ...defaultDependencies.required.systemRequirements, complete: true } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return true if all non-local fabric prereqs have been met`, async () => { getExtensionLocalFabricSetting.returns(false); mySandBox.stub(process, 'platform').value('linux'); // We don't have any Linux only prereqs, so this is okay. const dependencies: any = { systemRequirements: { name: 'System Requirements', complete: true } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should be able to pass dependencies to the function`, async () => { getExtensionLocalFabricSetting.returns(false); mySandBox.stub(process, 'platform').value('linux'); // We don't have any Linux only prereqs, so this is okay. const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(validDependencies); result.should.equal(true); getPreReqVersionsStub.should.not.have.been.called; }); describe('Windows', () => { it(`should return false if the user hasn't confirmed the Docker for Windows setup (Windows)`, async () => { mySandBox.stub(process, 'platform').value('win32'); const dependencies: Dependencies = { ...validDependencies, dockerForWindows: { ...defaultDependencies.required.dockerForWindows, complete: undefined } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return true if all Windows prereqs have been met (Windows)`, async () => { mySandBox.stub(process, 'platform').value('win32'); const dependencies: any = { docker: { ...defaultDependencies.required.docker, version: '18.1.2', }, systemRequirements: { ...defaultDependencies.required.systemRequirements, complete: true }, dockerForWindows: { ...defaultDependencies.required.dockerForWindows, complete: true } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return true if all non-local fabric Windows prereqs have been met (Windows)`, async () => { getExtensionLocalFabricSetting.returns(false); mySandBox.stub(process, 'platform').value('win32'); const dependencies: any = { }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); }); describe('Mac', () => { it(`should return true if all Mac prereqs have been met (Mac)`, async () => { mySandBox.stub(process, 'platform').value('darwin'); const dependencies: any = { docker: { ...defaultDependencies.required.docker, version: '18.1.2', }, systemRequirements: { ...defaultDependencies.required.systemRequirements, complete: true } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); }); describe('optional dependencies', () => { it(`should return false the optional Node dependency hasn't been installed`, async () => { const dependencies: Dependencies = { ...validDependencies, node: { ...defaultDependencies.optional.node, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if wrong Node version`, async () => { const dependencies: Dependencies = { ...validDependencies, node: { ...defaultDependencies.optional.node, version: '8.12.0', } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const resultNode8: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); resultNode8.should.equal(false); dependencies.node.version = '10.15.2'; const resultNode10low: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); resultNode10low.should.equal(false); dependencies.node.version = '11.1.1'; const resultNode11: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); resultNode11.should.equal(false); dependencies.node.version = '12.13.0'; const resultNode12low: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); resultNode12low.should.equal(false); dependencies.node.version = '13.0.0'; const resultNode13: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); resultNode13.should.equal(false); getPreReqVersionsStub.callCount.should.equal(5); }); it(`should return false if the optional npm dependency hasn't been installed`, async () => { const dependencies: Dependencies = { ...validDependencies, npm: { ...defaultDependencies.optional.npm, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional npm dependency version is less than required version`, async () => { const dependencies: Dependencies = { ...validDependencies, npm: { ...defaultDependencies.optional.npm, version: '4.0.0', } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if openssl not detected (on Windows)`, async () => { mySandBox.stub(process, 'platform').value('win32'); const dependencies: Dependencies = { ...validDependencies, openssl: { ...defaultDependencies.optional.openssl, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should ignore openssl if not using Windows`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, openssl: { ...defaultDependencies.optional.openssl, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Go dependency hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, go: { ...defaultDependencies.optional.go, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Go dependency isn't greater than the required version`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, go: { ...defaultDependencies.optional.go, version: '1.0.0', } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Go Extension hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, goExtension: { ...defaultDependencies.optional.goExtension, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Java dependency hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, java: { ...defaultDependencies.optional.java, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Java dependency doesn't satisfy the required version`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, java: { ...defaultDependencies.optional.java, version: '1.7.1', } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Java Language Support Extension hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, javaLanguageExtension: { ...defaultDependencies.optional.javaLanguageExtension, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Java Debugger Extension hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, javaDebuggerExtension: { ...defaultDependencies.optional.javaDebuggerExtension, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Java Test Runner Extension hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, javaTestRunnerExtension: { ...defaultDependencies.optional.javaTestRunnerExtension, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return false if the optional Node Test Runner Extension hasn't been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); const dependencies: Dependencies = { ...validDependencies, nodeTestRunnerExtension: { ...defaultDependencies.optional.nodeTestRunnerExtension, version: undefined, } }; getPreReqVersionsStub.resolves(dependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(false); getPreReqVersionsStub.should.have.been.calledOnce; }); it(`should return true if all the optional prereqs have been installed`, async () => { mySandBox.stub(process, 'platform').value('linux'); getPreReqVersionsStub.resolves(validDependencies); const dependencyManager: DependencyManager = DependencyManager.instance(); const result: boolean = await dependencyManager.hasPreReqsInstalled(undefined, true); result.should.equal(true); getPreReqVersionsStub.should.have.been.calledOnce; }); }); }); describe('getPreReqVersions', () => { let sendCommandStub: sinon.SinonStub; let extensionData: ExtensionData; let dependencyManager: DependencyManager; let totalmemStub: sinon.SinonStub; before(async () => { await TestUtil.setupTests(mySandBox); }); beforeEach(async () => { extensionData = DEFAULT_EXTENSION_DATA; extensionData.preReqPageShown = true; extensionData.dockerForWindows = false; extensionData.version = currentExtensionVersion; extensionData.generatorVersion = extDeps['generator-fabric']; totalmemStub = mySandBox.stub(OS, 'totalmem'); totalmemStub.returns(4294967296); await GlobalState.update(extensionData); dependencyManager = DependencyManager.instance(); sendCommandStub = mySandBox.stub(CommandUtil, 'sendCommand'); sendCommandStub.resolves(); }); it('should get extension context if not passed to dependency manager', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('node -v').resolves('v10.15.3'); const _dependencyManager: DependencyManager = DependencyManager.instance(); const result: Dependencies = await _dependencyManager.getPreReqVersions(); result.node.version.should.equal('10.15.3'); totalmemStub.should.have.been.calledOnce; }); it('should get version of node', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('node -v').resolves('v10.15.3'); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.node.version.should.equal('10.15.3'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of node if command not found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('node -v').resolves('-bash: node: command not found'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.node.version); totalmemStub.should.have.been.calledOnce; }); it('should not get version of node if unexpected format is returned', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('node -v').resolves('something v1.2.3'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.node.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of npm', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('npm -v').resolves('6.4.1'); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.npm.version.should.equal('6.4.1'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of npm if command not found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('npm -v').resolves('-bash: npm: command not found'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.npm.version); totalmemStub.should.have.been.calledOnce; }); it('should not get version of npm if unexpected format is returned', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('npm -v').resolves('something v1.2.3'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.npm.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Docker', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('docker -v').resolves('Docker version 18.06.1-ce, build e68fc7a'); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.docker.version.should.equal('18.6.1'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Docker if command not found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('docker -v').resolves('-bash: /usr/local/bin/docker: No such file or directory'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.docker.version); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Docker if unexpected format is returned', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('docker -v').resolves('version 1-2-3, community edition'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.docker.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Go', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('go version').resolves('go version go1.12.7 darwin/amd64'); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.go.version.should.equal('1.12.7'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Go if command not found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('go version').resolves('-bash: go: command not found'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.go.version); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Go if unexpected format is returned', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('go version').resolves('go version go-version-one.two.three x64'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.go.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Go Extension', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.GO_LANGUAGE_EXTENSION).returns({ packageJSON: { version: '1.0.0' } }); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.goExtension.version.should.equal('1.0.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Go Extension if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.GO_LANGUAGE_EXTENSION).returns(undefined); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.goExtension.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Java', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('java -version 2>&1').resolves('openjdk version "1.8.0_212"'); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.java.version.should.equal('1.8.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Java if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('java -version 2>&1').resolves('command not found'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.java.version); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Java if unexpected format is returned', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); sendCommandStub.withArgs('java -version 2>&1').resolves('openjdk version "version one.two.three"'); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.java.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Java Language Extension', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.JAVA_LANGUAGE_EXTENSION).returns({ packageJSON: { version: '2.0.0' } }); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.javaLanguageExtension.version.should.equal('2.0.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Java Language Extension if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.JAVA_LANGUAGE_EXTENSION).returns(undefined); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.javaLanguageExtension.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Java Debugger Extension', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.JAVA_DEBUG_EXTENSION).returns({ packageJSON: { version: '3.0.0' } }); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.javaDebuggerExtension.version.should.equal('3.0.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Java Debugger Extension if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.JAVA_DEBUG_EXTENSION).returns(undefined); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.javaDebuggerExtension.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Java Test Runner Extension', async () => { const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.JAVA_TEST_RUNNER_EXTENSION).returns({ packageJSON: { version: '2.0.0' } }); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.javaTestRunnerExtension.version.should.equal('2.0.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Java Test Runner Extension if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.JAVA_TEST_RUNNER_EXTENSION).returns(undefined); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.javaTestRunnerExtension.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of Node Test Runner Extension', async () => { const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.NODEJS_TEST_RUNNER_EXTENSION).returns({ packageJSON: { version: '2.0.0' } }); const result: any = await dependencyManager.getPreReqVersions(); result.nodeTestRunnerExtension.version.should.equal('2.0.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of Node Test Runner Extension if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.NODEJS_TEST_RUNNER_EXTENSION).returns(undefined); const result: any = await dependencyManager.getPreReqVersions(); should.not.exist(result.nodeTestRunnerExtension.version); totalmemStub.should.have.been.calledOnce; }); it('should get version of IBM Cloud Account Extension', async () => { const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.IBM_CLOUD_ACCOUNT_EXTENSION).returns({ packageJSON: { version: '2.0.0' } }); const result: any = await dependencyManager.getPreReqVersions(); result.ibmCloudAccountExtension.version.should.equal('2.0.0'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of IBM Cloud Account Extension if it cannot be found', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const getExtensionStub: sinon.SinonStub = mySandBox.stub(vscode.extensions, 'getExtension'); getExtensionStub.withArgs(DependencyProperties.IBM_CLOUD_ACCOUNT_EXTENSION).returns(undefined); const result: any = await dependencyManager.getPreReqVersions(); should.not.exist(result.ibmCloudAccountExtension.version); totalmemStub.should.have.been.calledOnce; }); it('should return true if the computer resources meet the system requirements', async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); const newExtensionData: ExtensionData = DEFAULT_EXTENSION_DATA; newExtensionData.preReqPageShown = true; newExtensionData.dockerForWindows = false; newExtensionData.version = currentExtensionVersion; newExtensionData.generatorVersion = extDeps['generator-fabric']; await GlobalState.update(newExtensionData); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.systemRequirements.complete.should.equal(true); totalmemStub.should.have.been.calledOnce; }); it(`should return false if the computer resources doesn't meet the system requirements`, async () => { mySandBox.stub(process, 'platform').value('some_other_platform'); totalmemStub.returns(4294967295); const newExtensionData: ExtensionData = DEFAULT_EXTENSION_DATA; newExtensionData.preReqPageShown = true; newExtensionData.dockerForWindows = false; newExtensionData.version = currentExtensionVersion; newExtensionData.generatorVersion = extDeps['generator-fabric']; await GlobalState.update(newExtensionData); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.systemRequirements.complete.should.equal(false); totalmemStub.should.have.been.calledOnce; }); it('should only get non-local fabric versions', async () => { getExtensionLocalFabricSetting.returns(false); mySandBox.stub(process, 'platform').value('some_other_platform'); await dependencyManager.getPreReqVersions(); sendCommandStub.should.not.have.been.calledWith('docker -v'); }); describe('Windows', () => { let existsStub: sinon.SinonStub; beforeEach(async () => { existsStub = mySandBox.stub(fs, 'pathExists'); }); it('should check if OpenSSL is installed / if libeay32.lib is found', async () => { mySandBox.stub(process, 'platform').value('win32'); existsStub.withArgs(`C:\\OpenSSL-Win64\\lib\\libeay32.lib`).resolves(true); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.openssl.version.should.equal('1.0.2'); totalmemStub.should.have.been.calledOnce; }); it('should not get version of OpenSSL if not installed / if libeay32.lib is not found', async () => { mySandBox.stub(process, 'platform').value('win32'); existsStub.withArgs(`C:\\OpenSSL-Win64\\lib\\libeay32.lib`).resolves(false); const result: Dependencies = await dependencyManager.getPreReqVersions(); should.not.exist(result.openssl.version); totalmemStub.should.have.been.calledOnce; }); it('should return true if user has agreed to Docker setup', async () => { mySandBox.stub(process, 'platform').value('win32'); const newExtensionData: ExtensionData = DEFAULT_EXTENSION_DATA; newExtensionData.preReqPageShown = true; newExtensionData.dockerForWindows = true; newExtensionData.version = currentExtensionVersion; newExtensionData.generatorVersion = extDeps['generator-fabric']; await GlobalState.update(newExtensionData); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.dockerForWindows.complete.should.equal(true); totalmemStub.should.have.been.calledOnce; }); it(`should return false if user hasn't agreed to Docker setup`, async () => { mySandBox.stub(process, 'platform').value('win32'); const newExtensionData: ExtensionData = DEFAULT_EXTENSION_DATA; newExtensionData.preReqPageShown = true; newExtensionData.dockerForWindows = false; newExtensionData.version = currentExtensionVersion; newExtensionData.generatorVersion = extDeps['generator-fabric']; await GlobalState.update(newExtensionData); const result: Dependencies = await dependencyManager.getPreReqVersions(); result.dockerForWindows.complete.should.equal(false); totalmemStub.should.have.been.calledOnce; }); it('should only get non-local fabric versions for Windows', async () => { getExtensionLocalFabricSetting.returns(false); mySandBox.stub(process, 'platform').value('win32'); await dependencyManager.getPreReqVersions(); sendCommandStub.should.not.have.been.calledWith('docker -v'); sendCommandStub.should.not.have.been.calledWith('openssl version -v'); }); }); describe('Mac', () => { it('should continue to get version if Java path exists', async () => { // Test for issue #1657 fix mySandBox.stub(process, 'platform').value('darwin'); const pathExistsStub: sinon.SinonStub = mySandBox.stub(fs, 'pathExists').withArgs('/Library/Java/JavaVirtualMachines').resolves(true); sendCommandStub.withArgs('java -version 2>&1').resolves('openjdk version "1.8.0_212"'); const result: Dependencies = await dependencyManager.getPreReqVersions(); pathExistsStub.should.have.been.calledOnce; result.java.version.should.equal('1.8.0'); totalmemStub.should.have.been.calledOnce; }); it('should not continue to get version if Java path doesnt exist', async () => { // Test for issue #1657 fix mySandBox.stub(process, 'platform').value('darwin'); const pathExistsStub: sinon.SinonStub = mySandBox.stub(fs, 'pathExists').withArgs('/Library/Java/JavaVirtualMachines').resolves(false); sendCommandStub.withArgs('java -version 2>&1'); const result: Dependencies = await dependencyManager.getPreReqVersions(); pathExistsStub.should.have.been.calledOnce; sendCommandStub.should.not.have.been.calledWith('java -version 2>&1'); should.not.exist(result.java.version); totalmemStub.should.have.been.calledOnce; }); }); }); describe('getPackageJsonPath', () => { afterEach(async () => { mySandBox.restore(); }); it('should get package json path', async () => { const getExtensionPathStub: sinon.SinonStub = mySandBox.stub(ExtensionUtil, 'getExtensionPath').returns('./test/dir/'); const dependencyManager: DependencyManager = DependencyManager.instance(); const packagePath: string = dependencyManager.getPackageJsonPath(); getExtensionPathStub.should.have.been.calledOnce; packagePath.includes('/test/dir/package.json').should.equal(true); }); }); describe('getRawPackageJson', () => { afterEach(async () => { mySandBox.restore(); }); it('should get raw package json', async () => { const dependencyManager: DependencyManager = DependencyManager.instance(); const getPackageJsonPathStub: sinon.SinonStub = mySandBox.stub(dependencyManager, 'getPackageJsonPath').returns('/some/path'); const readFileStub: sinon.SinonStub = mySandBox.stub(fs, 'readFile').resolves('{"some":"json"}'); const rawJson: Dependencies = await dependencyManager.getRawPackageJson(); getPackageJsonPathStub.should.have.been.calledOnce; readFileStub.should.have.been.calledOnceWithExactly('/some/path', 'utf8'); rawJson.should.deep.equal({ some: 'json' }); }); }); describe('writePackageJson', () => { afterEach(async () => { mySandBox.restore(); }); it('should write package json', async () => { const dependencyManager: DependencyManager = DependencyManager.instance(); const getPackageJsonPathStub: sinon.SinonStub = mySandBox.stub(dependencyManager, 'getPackageJsonPath').returns('/some/path'); const writeFileStub: sinon.SinonStub = mySandBox.stub(fs, 'writeFile').resolves(); await dependencyManager.writePackageJson({ some: 'json' }); getPackageJsonPathStub.should.have.been.calledOnce; const expectedJson: any = JSON.stringify({ some: 'json' }, null, 4); writeFileStub.should.have.been.calledOnceWithExactly('/some/path', expectedJson, 'utf8'); }); }); describe('clearExtensionCache', () => { afterEach(async () => { mySandBox.restore(); }); it('should clear extension cache', async () => { const dependencyManager: DependencyManager = DependencyManager.instance(); const getExtensionPathStub: sinon.SinonStub = mySandBox.stub(ExtensionUtil, 'getExtensionPath').returns('/some/path'); const utimesStub: sinon.SinonStub = mySandBox.stub(fs, 'utimes').resolves(); await dependencyManager.clearExtensionCache(); getExtensionPathStub.should.have.been.calledOnce; utimesStub.should.have.been.calledOnce; }); }); });
the_stack
import * as React from "react" import makeStyles from "@material-ui/core/styles/makeStyles" import Typography from "@material-ui/core/Typography" import { RequestStatus } from "@/types" import { Url, StorageKey } from "@/constants" import ExternalLink from "@/components/ExternalLink" import LabeledCheckbox from "@/components/LabeledCheckbox" import { MetricsPicker, DimensionsPicker } from "@/components/GA4Pickers" import WithHelpText from "@/components/WithHelpText" import LinkedTextField from "@/components/LinkedTextField" import { PAB } from "@/components/Buttons" import PrettyJson from "@/components/PrettyJson" import OrderBys from "../OrderBys" import MetricAggregations from "../MetricAggregations" import DateRanges from "../DateRanges" import { FilterType } from "../Filter" import CohortSpec from "../CohortSpec" import Filter from "../Filter" import Response from "../Response" import useMakeRequest from "./useMakeRequest" import useInputs from "./useInputs" import useFormStyles from "@/hooks/useFormStyles" import StreamPicker from "../../StreamPicker" import useAccountProperty from "../../StreamPicker/useAccountProperty" import { DimensionsAndMetricsRequestCtx, useDimensionsAndMetrics, } from "../../DimensionsMetricsExplorer/useDimensionsAndMetrics" const useStyles = makeStyles(theme => ({ showRequestJSON: { marginLeft: theme.spacing(1), }, requestJSON: { marginTop: theme.spacing(2), }, })) const shouldCollapseRequest = ({ namespace }: any) => { // The number 4 refers to the number of levels to show by default, this value // was gotten to mostly by trial an error, but concretely it's the number of // unique "keys" in "object" that we want to show by default. // { // // "reportRequests" is namespace.length === 1 // "reportRequests": [ // // "0" is namespace.length === 2 // { // // "viewId" is namespace.length === 3 // "viewId": "viewIdString", // // "dateRanges" is namespace.length === 3 // "dateRanges": [...] // }] // } if (namespace.length < 4) { return false } return true } const dimensionsLink = ( <ExternalLink href={Url.ga4RequestComposerBasicDimensions}> dimensions </ExternalLink> ) const metricsLink = ( <ExternalLink href={Url.ga4RequestComposerBasicMetrics}>metrics</ExternalLink> ) const keepEmptyRowsLink = ( <ExternalLink href={Url.ga4RequestComposerBasicKeepEmptyRows}> keepEmptyRows </ExternalLink> ) const runReportLink = ( <ExternalLink href={Url.ga4RequestComposerBasicRunReport}> properties.runReport </ExternalLink> ) const dimensionFiltersLink = ( <ExternalLink href={Url.ga4RequestComposerBasicRunReportDimensionFilter}> dimensionFilter </ExternalLink> ) const metricFiltersLink = ( <ExternalLink href={Url.ga4RequestComposerBasicRunReportMetricFilter}> metricFilter </ExternalLink> ) export const ShowAdvancedCtx = React.createContext(false) export enum QueryParam { Account = "a", Property = "b", Stream = "c", Dimensions = "d", Metrics = "e", } const BasicReport = () => { const classes = useStyles() const formClasses = useFormStyles() const aps = useAccountProperty(StorageKey.ga4QueryExplorerAPS, QueryParam) const dimensionsAndMetricsRequest = useDimensionsAndMetrics(aps) const { property } = aps const { dateRanges, setDateRanges, dimensions, setDimensionIDs, metrics, setMetricIDs, showRequestJSON, setShowRequestJSON, dimensionFilter, setDimensionFilter, metricFilter, setMetricFilter, offset, setOffset, limit, setLimit, orderBys, setOrderBys, cohortSpec, setCohortSpec, keepEmptyRows, setKeepEmptyRows, metricAggregations, setMetricAggregations, addFirstSessionDate, removeDateRanges, showAdvanced, setShowAdvanced, } = useInputs(dimensionsAndMetricsRequest) const useMake = useMakeRequest({ metricAggregations, property, dimensionFilter, offset, limit, metricFilter, dateRanges, dimensions, metrics, orderBys, cohortSpec, keepEmptyRows, showAdvanced, }) const { validRequest, makeRequest, request, response, status: requestStatus, } = useMake const metricOrDimensionSelected = React.useMemo(() => { return !!( (metrics !== undefined && metrics.length > 0) || (dimensions !== undefined && dimensions.length > 0) ) }, [metrics, dimensions]) return ( <DimensionsAndMetricsRequestCtx.Provider value={dimensionsAndMetricsRequest} > <ShowAdvancedCtx.Provider value={showAdvanced}> <Typography> Returns a customized report of your Google Analytics event data. Reports contain statistics derived from data collected by the Google Analytics measurement code. Basic Report uses the {runReportLink} API endpoint. </Typography> <section className={formClasses.form}> <Typography variant="h3">Select property</Typography> <StreamPicker autoFill {...aps} /> <Typography variant="h3">Set parameters</Typography> <LabeledCheckbox checked={showAdvanced} setChecked={setShowAdvanced}> Show advanced options </LabeledCheckbox> <DateRanges setDateRanges={setDateRanges} dateRanges={dateRanges} showAdvanced={showAdvanced} /> <MetricsPicker required={!metricOrDimensionSelected} setMetricIDs={setMetricIDs} metrics={metrics} helperText={ <> The metrics to include in the request. See {metricsLink} on devsite. </> } /> <DimensionsPicker required={!metricOrDimensionSelected} setDimensionIDs={setDimensionIDs} dimensions={dimensions} helperText={ <> The dimensions to include in the request. See {dimensionsLink}{" "} on devsite. </> } /> <OrderBys metric metricOptions={metrics} dimension dimensionOptions={dimensions} orderBys={orderBys} setOrderBys={setOrderBys} /> <MetricAggregations metricAggregations={metricAggregations} setMetricAggregations={setMetricAggregations} /> <WithHelpText notched={!showAdvanced} label={showAdvanced ? "dimension filters" : "dimension filter"} helpText={ <> The {showAdvanced ? "filters" : "filter"} to use for the dimensions in the request. See {dimensionFiltersLink} on devsite. </> } > <Filter showAdvanced={showAdvanced} storageKey={StorageKey.ga4RequestComposerBasicDimensionFilter} type={FilterType.Dimension} fields={dimensions} setFilterExpression={setDimensionFilter} /> </WithHelpText> <WithHelpText notched={!showAdvanced} label={showAdvanced ? "metric filters" : "metric filter"} helpText={ <> The {showAdvanced ? "filters" : "filter"} to use for the metrics in the request. See {metricFiltersLink} on devsite. </> } > <Filter showAdvanced={showAdvanced} storageKey={StorageKey.ga4RequestComposerBasicMetricFilter} type={FilterType.Metric} fields={metrics} setFilterExpression={setMetricFilter} /> </WithHelpText> <LinkedTextField href={Url.ga4RequestComposerBasicRunReportLimit} linkTitle="See limit on devsite." label="limit" value={limit} helperText="The maximum number of rows to return." onChange={setLimit} /> {showAdvanced && ( <LinkedTextField href={Url.ga4RequestComposerBasicRunReportOffset} linkTitle="See offset on devsite." label="offset" value={offset} helperText="The row count of the start row. The first row is row 0." onChange={setOffset} /> )} {showAdvanced && ( <CohortSpec cohortSpec={cohortSpec} setCohortSpec={setCohortSpec} dimensions={dimensions} addFirstSessionDate={addFirstSessionDate} dateRanges={dateRanges} removeDateRanges={removeDateRanges} /> )} <WithHelpText helpText={ <> Return rows with all metrics equal to 0 separately. See{" "} {keepEmptyRowsLink} on devsite. </> } > <LabeledCheckbox checked={keepEmptyRows} setChecked={setKeepEmptyRows} > keep empty rows. </LabeledCheckbox> </WithHelpText> <PAB onClick={makeRequest} disabled={!validRequest}> Make Request </PAB> <LabeledCheckbox className={classes.showRequestJSON} checked={showRequestJSON} setChecked={setShowRequestJSON} > Show request JSON </LabeledCheckbox> </section> {showRequestJSON && ( <PrettyJson tooltipText="copy request" className={classes.requestJSON} object={request} shouldCollapse={shouldCollapseRequest} /> )} <Response response={response} error={ useMake.status === RequestStatus.Failed ? useMake.error : undefined } requestStatus={requestStatus} shouldCollapse={shouldCollapseRequest} /> </ShowAdvancedCtx.Provider> </DimensionsAndMetricsRequestCtx.Provider> ) } export default BasicReport
the_stack
import BrowserEmulator from '@secret-agent/default-browser-emulator'; import Log from '@secret-agent/commons/Logger'; import { IPuppetPage } from '@secret-agent/interfaces/IPuppetPage'; import IPuppetContext from '@secret-agent/interfaces/IPuppetContext'; import Core from '@secret-agent/core'; import CorePlugins from '@secret-agent/core/lib/CorePlugins'; import { IBoundLog } from '@secret-agent/interfaces/ILog'; import { TestServer } from './server'; import Puppet from '../index'; import { capturePuppetContextLogs, createTestPage, ITestPage } from './TestPage'; import CustomBrowserEmulator from './_CustomBrowserEmulator'; const { log } = Log(module); const browserEmulatorId = CustomBrowserEmulator.id; describe('Frames', () => { let server: TestServer; let page: ITestPage; let puppet: Puppet; let context: IPuppetContext; beforeAll(async () => { Core.use(CustomBrowserEmulator); const { browserEngine } = CustomBrowserEmulator.selectBrowserMeta(); const plugins = new CorePlugins({ browserEmulatorId }, log as IBoundLog); server = await TestServer.create(0); puppet = new Puppet(browserEngine); await puppet.start(); context = await puppet.newContext(plugins, log); capturePuppetContextLogs(context, `${browserEngine.fullVersion}-Frames-test`); }); afterEach(async () => { await page.close().catch(() => null); server.reset(); }); beforeEach(async () => { page = createTestPage(await context.newPage()); }); afterAll(async () => { await server.stop(); await context.close().catch(() => null); await puppet.close(); }); function getContexts(puppetPage: IPuppetPage) { const { browserEngine } = BrowserEmulator.selectBrowserMeta(); if (browserEngine.name === 'chrome') { const rawPage = puppetPage; // @ts-ignore return rawPage.framesManager.activeContextIds.size; } return null; } describe('basic', () => { it('should have different execution contexts', async () => { await page.goto(server.emptyPage); await page.attachFrame('frame1', server.emptyPage); expect(page.frames.length).toBe(2); await page.frames[0].evaluate(`(window.FOO = 'foo')`); await page.frames[1].evaluate(`(window.FOO = 'bar')`); expect(await page.frames[0].evaluate('window.FOO')).toBe('foo'); expect(await page.frames[1].evaluate('window.FOO')).toBe('bar'); }); it('should have correct execution contexts', async () => { await page.goto(`${server.baseUrl}/frames/one-frame.html`); expect(page.frames.length).toBe(2); expect(await page.frames[0].evaluate('document.body.textContent.trim()')).toBe(''); expect(await page.frames[1].evaluate('document.body.textContent.trim()')).toBe( `Hi, I'm frame`, ); }); it('should dispose context on navigation', async () => { await page.goto(`${server.baseUrl}/frames/one-frame.html`); expect(page.frames.length).toBe(2); expect(getContexts(page)).toBe(4); await page.goto(server.emptyPage); // isolated context might or might not be loaded expect(getContexts(page)).toBeLessThanOrEqual(2); }); it('should dispose context on cross-origin navigation', async () => { await page.goto(`${server.baseUrl}/frames/one-frame.html`); expect(page.frames.length).toBe(2); expect(getContexts(page)).toBe(4); await page.goto(`${server.crossProcessBaseUrl}/empty.html`); // isolated context might or might not be loaded expect(getContexts(page)).toBeLessThanOrEqual(2); }); it('should execute after cross-site navigation', async () => { await page.goto(server.emptyPage); const mainFrame = page.mainFrame; expect(await mainFrame.evaluate('window.location.href')).toContain('localhost'); await page.goto(`${server.crossProcessBaseUrl}/empty.html`); expect(await mainFrame.evaluate('window.location.href')).toContain('127'); }); it('should be isolated between frames', async () => { await page.goto(server.emptyPage); await page.attachFrame('frame1', server.emptyPage); expect(page.frames.length).toBe(2); const [frame1, frame2] = page.frames; expect(frame1 !== frame2).toBeTruthy(); await Promise.all([frame1.evaluate('(window.a = 1)'), frame2.evaluate('(window.a = 2)')]); const [a1, a2] = await Promise.all([ frame1.evaluate('window.a'), frame2.evaluate('window.a'), ]); expect(a1).toBe(1); expect(a2).toBe(2); }); it('should work in iframes that failed initial navigation', async () => { // - Firefox does not report domcontentloaded for the iframe. // - Chromium and Firefox report empty url. // - Chromium does not report main/utility worlds for the iframe. await page.setContent( `<meta http-equiv="Content-Security-Policy" content="script-src 'none';"> <iframe src='javascript:""'></iframe>`, ); // Note: Chromium/Firefox never report 'load' event for the iframe. await page.evaluate(`(() => { const iframe = document.querySelector('iframe'); const div = iframe.contentDocument.createElement('div'); iframe.contentDocument.body.appendChild(div); })()`); expect(page.frames[1].url).toBe(undefined); // Main world should work. expect(await page.frames[1].evaluate('window.location.href')).toBe('about:blank'); }); it('should work in iframes that interrupted initial javascript url navigation', async () => { // Chromium does not report isolated world for the iframe. await page.goto(server.emptyPage); await page.evaluate(`(() => { const iframe = document.createElement('iframe'); iframe.src = 'javascript:""'; document.body.appendChild(iframe); iframe.contentDocument.open(); iframe.contentDocument.write('<div>hello</div>'); iframe.contentDocument.close(); })()`); expect(await page.frames[1].evaluate('window.top.location.href')).toBe(server.emptyPage); }); }); describe('hierarchy', () => { it('should handle nested frames', async () => { await page.goto(`${server.baseUrl}/frames/nested-frames.html`); expect(page.frames).toHaveLength(5); const mainFrame = page.mainFrame; expect(mainFrame.url).toMatch('nested-frames.html'); const secondChildren = page.frames.filter(x => x.parentId === mainFrame.id); expect(secondChildren).toHaveLength(2); expect(secondChildren.map(x => x.url).sort()).toStrictEqual([ `${server.baseUrl}/frames/frame.html`, `${server.baseUrl}/frames/two-frames.html`, ]); const secondParent = secondChildren.find(x => x.url.includes('two-frames')); const thirdTier = page.frames.filter(x => x.parentId === secondParent.id); expect(thirdTier).toHaveLength(2); await thirdTier[0].waitForLoader(); expect(thirdTier[0].url).toMatch('frame.html'); await thirdTier[1].waitForLoader(); expect(thirdTier[1].url).toMatch('frame.html'); }); it('should send events when frames are manipulated dynamically', async () => { await page.goto(server.emptyPage); // validate framenavigated events const navigatedFrames = []; page.on('frame-created', ({ frame }) => { frame.on('frame-navigated', () => { navigatedFrames.push({ frame }); }); }); await page.attachFrame('frame1', './assets/frame.html'); expect(page.frames.length).toBe(2); expect(page.frames[1].url).toContain('/assets/frame.html'); await page.evaluate(`(async () => { const frame = document.getElementById('frame1'); frame.src = './empty.html'; await new Promise(x => (frame.onload = x)); })()`); expect(navigatedFrames.length).toBe(2); expect(navigatedFrames[1].frame.url).toBe(server.emptyPage); // validate framedetached events await page.detachFrame('frame1'); expect(page.frames.length).toBe(1); }); it('should send "frameNavigated" when navigating on anchor URLs', async () => { await page.goto(server.emptyPage); const frameNavigated = page.mainFrame.waitOn('frame-navigated'); await page.goto(`${server.emptyPage}#foo`); expect(page.mainFrame.url).toBe(`${server.emptyPage}#foo`); await expect(frameNavigated).resolves.toBeTruthy(); }); it('should persist mainFrame on cross-process navigation', async () => { await page.goto(server.emptyPage); const mainFrame = page.mainFrame; await page.goto(`${server.crossProcessBaseUrl}/empty.html`); expect(page.mainFrame === mainFrame).toBeTruthy(); }); it('should detach child frames on navigation', async () => { let navigatedFrames = []; page.mainFrame.on('frame-navigated', ev => navigatedFrames.push(ev)); page.on('frame-created', ({ frame }) => { frame.on('frame-navigated', () => { navigatedFrames.push(frame); }); }); await page.goto(`${server.baseUrl}/frames/nested-frames.html`); expect(page.frames.length).toBe(5); for (const frame of page.frames) await frame.waitForLoader(); expect(navigatedFrames.length).toBe(5); navigatedFrames = []; await page.goto(server.emptyPage); expect(page.frames.length).toBe(1); expect(navigatedFrames.length).toBe(1); }); it('should support framesets', async () => { let navigatedFrames = []; page.mainFrame.on('frame-navigated', ev => navigatedFrames.push(ev)); page.on('frame-created', ({ frame }) => { frame.on('frame-navigated', () => { navigatedFrames.push(frame); }); }); await page.goto(`${server.baseUrl}/frames/frameset.html`); expect(page.frames.length).toBe(5); for (const frame of page.frames) await frame.waitForLoader(); expect(navigatedFrames.length).toBe(5); navigatedFrames = []; await page.goto(server.emptyPage); expect(page.frames.length).toBe(1); expect(navigatedFrames.length).toBe(1); }); it('should report frame from-inside shadow DOM', async () => { await page.goto(`${server.baseUrl}/shadow.html`); await page.evaluate(`(async (url) => { const frame = document.createElement('iframe'); frame.src = url; document.body.shadowRoot.appendChild(frame); await new Promise(x => (frame.onload = x)); })('${server.emptyPage}')`); expect(page.frames.length).toBe(2); expect(page.frames[1].url).toBe(server.emptyPage); }); it('should report frame.name', async () => { await page.attachFrame('theFrameId', server.emptyPage); await page.evaluate(`((url) => { const frame = document.createElement('iframe'); frame.name = 'theFrameName'; frame.src = url; document.body.appendChild(frame); return new Promise(x => (frame.onload = x)); })('${server.emptyPage}')`); expect(page.frames[0].name).toBe(''); expect(page.frames[1].name).toBe('theFrameId'); expect(page.frames[2].name).toBe('theFrameName'); }); it('should report frame.parentId', async () => { await page.attachFrame('frame1', server.emptyPage); await page.attachFrame('frame2', server.emptyPage); expect(page.frames[0].parentId).not.toBeTruthy(); expect(page.frames[1].parentId).toBe(page.mainFrame.id); expect(page.frames[2].parentId).toBe(page.mainFrame.id); }); it('should report different frame instance when frame re-attaches', async () => { const frame1 = await page.attachFrame('frame1', server.emptyPage); expect(page.frames.length).toBe(2); await page.evaluate(`(() => { window.frame = document.querySelector('#frame1'); window.frame.remove(); })()`); // should have remove frame expect(page.frames.filter(x => x.id === frame1.id)).toHaveLength(0); const frame2Promise = page.waitOn('frame-created'); await Promise.all([frame2Promise, page.evaluate('document.body.appendChild(window.frame)')]); expect((await frame2Promise).frame.id).not.toBe(frame1.id); }); it('should refuse to display x-frame-options:deny iframe', async () => { server.setRoute('/x-frame-options-deny.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Frame-Options', 'DENY'); res.end( `<!DOCTYPE html><html><head><title>login</title></head><body style="background-color: red;"><p>dangerous login page</p></body></html>`, ); }); await page.goto(server.emptyPage); await page.setContent( `<iframe src="${server.crossProcessBaseUrl}/x-frame-options-deny.html"></iframe>`, ); expect(page.frames).toHaveLength(2); await page.frames[1].waitForLoader(); // CHROME redirects to chrome-error://chromewebdata/, not sure about other browsers expect(page.frames[1].url).not.toMatch('/x-frame-options-deny.html'); }); }); describe('waiting', () => { it('should await navigation when clicking anchor', async () => { server.setRoute('/empty.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); await page.setContent(`<a href="${server.emptyPage}">empty.html</a>`); await page.mainFrame.waitForLoader(); const navigate = page.mainFrame.waitOn('frame-navigated'); await page.click('a'); await expect(navigate).resolves.toBeTruthy(); }); it('should await cross-process navigation when clicking anchor', async () => { server.setRoute('/empty.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); await page.setContent(`<a href="${server.crossProcessBaseUrl}/empty.html">empty.html</a>`); const navigate = page.mainFrame.waitOn('frame-navigated'); await page.click('a'); await expect(navigate).resolves.toBeTruthy(); }); it('should await form-get on click', async () => { server.setRoute('/empty.html?foo=bar', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); await page.setContent(` <form action="${server.emptyPage}" method="get"> <input name="foo" value="bar"> <input type="submit" value="Submit"> </form>`); const navigate = page.mainFrame.waitOn('frame-navigated'); await page.click('input[type=submit]'); await expect(navigate).resolves.toBeTruthy(); }); it('should await form-post on click', async () => { server.setRoute('/empty.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); await page.setContent(` <form action="${server.emptyPage}" method="post"> <input name="foo" value="bar"> <input type="submit" value="Submit"> </form>`); const navigate = page.mainFrame.waitOn('frame-navigated'); await page.click('input[type=submit]'); await expect(navigate).resolves.toBeTruthy(); }); it('should await navigation when assigning location', async () => { server.setRoute('/empty.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); const navigate = page.mainFrame.waitOn('frame-navigated'); await page.evaluate(`window.location.href = "${server.emptyPage}"`); await expect(navigate).resolves.toBeTruthy(); }); it('should await navigation when assigning location twice', async () => { const messages = []; server.setRoute('/empty.html?cancel', async (req, res) => { res.end('done'); }); server.setRoute('/empty.html?override', async (req, res) => { messages.push('routeoverride'); res.end('done'); }); const navigatedEvent = page.mainFrame.waitOn('frame-navigated'); await page.evaluate(` window.location.href = "${server.emptyPage}?cancel"; window.location.href = "${server.emptyPage}?override"; `); expect((await navigatedEvent).frame.url).toBe(`${server.emptyPage}?override`); }); it('should await navigation when evaluating reload', async () => { await page.goto(server.emptyPage); server.setRoute('/empty.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); const navigate = page.mainFrame.waitOn('frame-navigated'); await page.evaluate(`window.location.reload()`); await expect(navigate).resolves.toBeTruthy(); }); it('should await navigating specified target', async () => { server.setRoute('/empty.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`<link rel='stylesheet' href='./one-style.css'>`); }); await page.setContent(` <a href="${server.emptyPage}" target=target>empty.html</a> <iframe name=target></iframe> `); const frame = page.frames.find(x => x.name === 'target'); const nav = frame.waitOn('frame-navigated'); await page.click('a'); await nav; expect(frame.url).toBe(server.emptyPage); }); it('should be able to navigate directly following click', async () => { server.setRoute('/login.html', async (req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(`You are logged in`); }); await page.setContent(` <form action="${server.baseUrl}/login.html" method="get"> <input type="text"> <input type="submit" value="Submit"> </form>`); await page.click('input[type=text]'); await page.type('admin'); await page.click('input[type=submit]'); // when the process gets busy, it will schedule the empty page navigation but then get interrupted by the click // ... ideally we could force it to always overlap, but in interim, just check for either condition try { const result = await page.navigate(server.emptyPage); expect(result.loaderId).toBeTruthy(); } catch (error) { // eslint-disable-next-line jest/no-try-expect expect(String(error)).toMatch(/Navigation canceled/); } }); }); });
the_stack
import { IdleTransaction, Span, Transaction } from '@sentry/tracing'; import { Measurements } from '@sentry/types'; import { logger, timestampInSeconds } from '@sentry/utils'; export interface StallMeasurements extends Measurements { 'stall_count': { value: number, unit: string }; 'stall_total_time': { value: number, unit: string }; 'stall_longest_time': { value: number, unit: string }; } export type StallTrackingOptions = { /** * How long in milliseconds an event loop iteration can be delayed for before being considered a "stall." * @default 100 */ minimumStallThreshold: number; }; /** Margin of error of 20ms */ const MARGIN_OF_ERROR_SECONDS = 0.02; /** How long between each iteration in the event loop tracker timeout */ const LOOP_TIMEOUT_INTERVAL_MS = 50; /** Limit for how many transactions the stall tracker will track at a time to prevent leaks due to transactions not being finished */ const MAX_RUNNING_TRANSACTIONS = 10; /** * Stall measurement tracker inspired by the `JSEventLoopWatchdog` used internally in React Native: * https://github.com/facebook/react-native/blob/006f5afe120c290a37cf6ff896748fbc062bf7ed/Libraries/Interaction/JSEventLoopWatchdog.js * * However, we modified the interval implementation to instead have a fixed loop timeout interval of `LOOP_TIMEOUT_INTERVAL_MS`. * We then would consider that iteration a stall when the total time for that interval to run is greater than `LOOP_TIMEOUT_INTERVAL_MS + minimumStallThreshold` */ export class StallTrackingInstrumentation { public isTracking: boolean = false; private _minimumStallThreshold: number; /** Total amount of time of all stalls that occurred during the current tracking session */ private _totalStallTime: number = 0; /** Total number of stalls that occurred during the current tracking session */ private _stallCount: number = 0; /** The last timestamp the iteration ran in milliseconds */ private _lastIntervalMs: number = 0; private _timeout: ReturnType<typeof setTimeout> | null = null; private _statsByTransaction: Map< Transaction, { longestStallTime: number; atStart: StallMeasurements; atTimestamp: { timestamp: number; stats: StallMeasurements; } | null; } > = new Map(); public constructor( options: StallTrackingOptions = { minimumStallThreshold: 50 } ) { this._minimumStallThreshold = options.minimumStallThreshold; } /** * @inheritDoc * Not used for this integration. Instead call `registerTransactionStart` to start tracking. */ public setupOnce(): void { // Do nothing. } /** * Register a transaction as started. Starts stall tracking if not already running. * @returns A finish method that returns the stall measurements. */ public onTransactionStart(transaction: Transaction): void { if (this._statsByTransaction.has(transaction)) { logger.error( '[StallTracking] Tried to start stall tracking on a transaction already being tracked. Measurements might be lost.' ); return; } this._startTracking(); this._statsByTransaction.set(transaction, { longestStallTime: 0, atTimestamp: null, atStart: this._getCurrentStats(transaction), }); this._flushLeakedTransactions(); if (transaction.spanRecorder) { // eslint-disable-next-line @typescript-eslint/unbound-method const originalAdd = transaction.spanRecorder.add; transaction.spanRecorder.add = (span: Span): void => { originalAdd.apply(transaction.spanRecorder, [span]); // eslint-disable-next-line @typescript-eslint/unbound-method const originalSpanFinish = span.finish; span.finish = (endTimestamp?: number) => { // We let the span determine its own end timestamp as well in case anything gets changed upstream originalSpanFinish.apply(span, [endTimestamp]); // The span should set a timestamp, so this would be defined. if (span.endTimestamp) { this._markSpanFinish(transaction, span.endTimestamp); } }; }; } } /** * Logs a transaction as finished. * Stops stall tracking if no more transactions are running. * @returns The stall measurements */ public onTransactionFinish( transaction: Transaction | IdleTransaction, passedEndTimestamp?: number ): void { const transactionStats = this._statsByTransaction.get(transaction); if (!transactionStats) { // Transaction has been flushed out somehow, we return null. logger.log( '[StallTracking] Stall measurements were not added to transaction due to exceeding the max count.' ); this._statsByTransaction.delete(transaction); this._shouldStopTracking(); return; } const endTimestamp = passedEndTimestamp ?? transaction.endTimestamp; const spans = transaction.spanRecorder ? transaction.spanRecorder.spans : []; const finishedSpanCount = spans.reduce( (count, s) => (s !== transaction && s.endTimestamp ? count + 1 : count), 0 ); const trimEnd = transaction.toContext().trimEnd; const endWillBeTrimmed = trimEnd && finishedSpanCount > 0; /* This is not safe in the case that something changes upstream, but if we're planning to move this over to @sentry/javascript anyways, we can have this temporarily for now. */ const isIdleTransaction = 'activities' in transaction; let statsOnFinish: StallMeasurements | undefined; if (endTimestamp && isIdleTransaction) { /* There is different behavior regarding child spans in a normal transaction and an idle transaction. In normal transactions, the child spans that aren't finished will be dumped, while in an idle transaction they're cancelled and finished. Note: `endTimestamp` will always be defined if this is called on an idle transaction finish. This is because we only instrument idle transactions inside `ReactNativeTracing`, which will pass an `endTimestamp`. */ // There will be cancelled spans, which means that the end won't be trimmed const spansWillBeCancelled = spans.some( (s) => s !== transaction && s.startTimestamp < endTimestamp && !s.endTimestamp ); if (endWillBeTrimmed && !spansWillBeCancelled) { // the last span's timestamp will be used. if (transactionStats.atTimestamp) { statsOnFinish = transactionStats.atTimestamp.stats; } } else { // this endTimestamp will be used. statsOnFinish = this._getCurrentStats(transaction); } } else if (endWillBeTrimmed) { // If `trimEnd` is used, and there is a span to trim to. If there isn't, then the transaction should use `endTimestamp` or generate one. if (transactionStats.atTimestamp) { statsOnFinish = transactionStats.atTimestamp.stats; } } else if (!endTimestamp) { statsOnFinish = this._getCurrentStats(transaction); } this._statsByTransaction.delete(transaction); this._shouldStopTracking(); if (!statsOnFinish) { if (typeof endTimestamp !== 'undefined') { logger.log( '[StallTracking] Stall measurements not added due to `endTimestamp` being set.' ); } else if (trimEnd) { logger.log( '[StallTracking] Stall measurements not added due to `trimEnd` being set but we could not determine the stall measurements at that time.' ); } return; } transaction.setMeasurement('stall_count', statsOnFinish.stall_count.value - transactionStats.atStart.stall_count.value); transaction.setMeasurement('stall_total_time', statsOnFinish.stall_total_time.value - transactionStats.atStart.stall_total_time.value); transaction.setMeasurement('stall_longest_time', statsOnFinish.stall_longest_time.value); } /** * Logs the finish time of the span for use in `trimEnd: true` transactions. */ private _markSpanFinish( transaction: Transaction, spanEndTimestamp: number ): void { const previousStats = this._statsByTransaction.get(transaction); if (previousStats) { if ( Math.abs(timestampInSeconds() - spanEndTimestamp) > MARGIN_OF_ERROR_SECONDS ) { logger.log( '[StallTracking] Span end not logged due to end timestamp being outside the margin of error from now.' ); if ( previousStats.atTimestamp && previousStats.atTimestamp.timestamp < spanEndTimestamp ) { // We also need to delete the stat for the last span, as the transaction would be trimmed to this span not the last one. this._statsByTransaction.set(transaction, { ...previousStats, atTimestamp: null, }); } } else { this._statsByTransaction.set(transaction, { ...previousStats, atTimestamp: { timestamp: spanEndTimestamp, stats: this._getCurrentStats(transaction), }, }); } } } /** * Get the current stats for a transaction at a given time. */ private _getCurrentStats(transaction: Transaction): StallMeasurements { return { stall_count: { value: this._stallCount, unit: '' }, stall_total_time: { value: this._totalStallTime, unit: '' }, stall_longest_time: { value: this._statsByTransaction.get(transaction)?.longestStallTime ?? 0, unit: '' }, }; } /** * Start tracking stalls */ private _startTracking(): void { if (!this.isTracking) { this.isTracking = true; this._lastIntervalMs = Math.floor(timestampInSeconds() * 1000); this._iteration(); } } /** * Stops the stall tracking interval and calls reset(). */ private _stopTracking(): void { this.isTracking = false; if (this._timeout !== null) { clearTimeout(this._timeout); this._timeout = null; } this._reset(); } /** * Will stop tracking if there are no more transactions. */ private _shouldStopTracking(): void { if (this._statsByTransaction.size === 0) { this._stopTracking(); } } /** * Clears all the collected stats */ private _reset(): void { this._stallCount = 0; this._totalStallTime = 0; this._lastIntervalMs = 0; this._statsByTransaction.clear(); } /** * Iteration of the stall tracking interval. Measures how long the timer strayed from its expected time of running, and how * long the stall is for. */ private _iteration(): void { const now = timestampInSeconds() * 1000; const totalTimeTaken = now - this._lastIntervalMs; if ( totalTimeTaken >= LOOP_TIMEOUT_INTERVAL_MS + this._minimumStallThreshold ) { const stallTime = totalTimeTaken - LOOP_TIMEOUT_INTERVAL_MS; this._stallCount += 1; this._totalStallTime += stallTime; for (const [transaction, value] of this._statsByTransaction.entries()) { const longestStallTime = Math.max( value.longestStallTime ?? 0, stallTime ); this._statsByTransaction.set(transaction, { ...value, longestStallTime, }); } } this._lastIntervalMs = now; if (this.isTracking) { this._timeout = setTimeout( this._iteration.bind(this), LOOP_TIMEOUT_INTERVAL_MS ); } } /** * Deletes leaked transactions (Earliest transactions when we have more than MAX_RUNNING_TRANSACTIONS transactions.) */ private _flushLeakedTransactions(): void { if (this._statsByTransaction.size > MAX_RUNNING_TRANSACTIONS) { let counter = 0; const len = this._statsByTransaction.size - MAX_RUNNING_TRANSACTIONS; const transactions = this._statsByTransaction.keys(); for (const t of transactions) { if (counter >= len) break; counter += 1; this._statsByTransaction.delete(t); } } } }
the_stack
import { deepNormalizeScriptCov, normalizeFunctionCov, normalizeProcessCov, normalizeRangeTree, normalizeScriptCov, } from "./normalize"; import { RangeTree } from "./range-tree"; import { FunctionCov, ProcessCov, Range, RangeCov, ScriptCov } from "./types"; /** * Merges a list of process coverages. * * The result is normalized. * The input values may be mutated, it is not safe to use them after passing * them to this function. * The computation is synchronous. * * @param processCovs Process coverages to merge. * @return Merged process coverage. */ export function mergeProcessCovs(processCovs: ReadonlyArray<ProcessCov>): ProcessCov { if (processCovs.length === 0) { return {result: []}; } const urlToScripts: Map<string, ScriptCov[]> = new Map(); for (const processCov of processCovs) { for (const scriptCov of processCov.result) { let scriptCovs: ScriptCov[] | undefined = urlToScripts.get(scriptCov.url); if (scriptCovs === undefined) { scriptCovs = []; urlToScripts.set(scriptCov.url, scriptCovs); } scriptCovs.push(scriptCov); } } const result: ScriptCov[] = []; for (const scripts of urlToScripts.values()) { // assert: `scripts.length > 0` result.push(mergeScriptCovs(scripts)!); } const merged: ProcessCov = {result}; normalizeProcessCov(merged); return merged; } /** * Merges a list of matching script coverages. * * Scripts are matching if they have the same `url`. * The result is normalized. * The input values may be mutated, it is not safe to use them after passing * them to this function. * The computation is synchronous. * * @param scriptCovs Process coverages to merge. * @return Merged script coverage, or `undefined` if the input list was empty. */ export function mergeScriptCovs(scriptCovs: ReadonlyArray<ScriptCov>): ScriptCov | undefined { if (scriptCovs.length === 0) { return undefined; } else if (scriptCovs.length === 1) { const merged: ScriptCov = scriptCovs[0]; deepNormalizeScriptCov(merged); return merged; } const first: ScriptCov = scriptCovs[0]; const scriptId: string = first.scriptId; const url: string = first.url; const rangeToFuncs: Map<string, FunctionCov[]> = new Map(); for (const scriptCov of scriptCovs) { for (const funcCov of scriptCov.functions) { const rootRange: string = stringifyFunctionRootRange(funcCov); let funcCovs: FunctionCov[] | undefined = rangeToFuncs.get(rootRange); if (funcCovs === undefined || // if the entry in rangeToFuncs is function-level granularity and // the new coverage is block-level, prefer block-level. (!funcCovs[0].isBlockCoverage && funcCov.isBlockCoverage)) { funcCovs = []; rangeToFuncs.set(rootRange, funcCovs); } else if (funcCovs[0].isBlockCoverage && !funcCov.isBlockCoverage) { // if the entry in rangeToFuncs is block-level granularity, we should // not append function level granularity. continue; } funcCovs.push(funcCov); } } const functions: FunctionCov[] = []; for (const funcCovs of rangeToFuncs.values()) { // assert: `funcCovs.length > 0` functions.push(mergeFunctionCovs(funcCovs)!); } const merged: ScriptCov = {scriptId, url, functions}; normalizeScriptCov(merged); return merged; } /** * Returns a string representation of the root range of the function. * * This string can be used to match function with same root range. * The string is derived from the start and end offsets of the root range of * the function. * This assumes that `ranges` is non-empty (true for valid function coverages). * * @param funcCov Function coverage with the range to stringify * @internal */ function stringifyFunctionRootRange(funcCov: Readonly<FunctionCov>): string { const rootRange: RangeCov = funcCov.ranges[0]; return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`; } /** * Merges a list of matching function coverages. * * Functions are matching if their root ranges have the same span. * The result is normalized. * The input values may be mutated, it is not safe to use them after passing * them to this function. * The computation is synchronous. * * @param funcCovs Function coverages to merge. * @return Merged function coverage, or `undefined` if the input list was empty. */ export function mergeFunctionCovs(funcCovs: ReadonlyArray<FunctionCov>): FunctionCov | undefined { if (funcCovs.length === 0) { return undefined; } else if (funcCovs.length === 1) { const merged: FunctionCov = funcCovs[0]; normalizeFunctionCov(merged); return merged; } const functionName: string = funcCovs[0].functionName; const trees: RangeTree[] = []; for (const funcCov of funcCovs) { // assert: `fn.ranges.length > 0` // assert: `fn.ranges` is sorted trees.push(RangeTree.fromSortedRanges(funcCov.ranges)!); } // assert: `trees.length > 0` const mergedTree: RangeTree = mergeRangeTrees(trees)!; normalizeRangeTree(mergedTree); const ranges: RangeCov[] = mergedTree.toRanges(); const isBlockCoverage: boolean = !(ranges.length === 1 && ranges[0].count === 0); const merged: FunctionCov = {functionName, ranges, isBlockCoverage}; // assert: `merged` is normalized return merged; } /** * @precondition Same `start` and `end` for all the trees */ function mergeRangeTrees(trees: ReadonlyArray<RangeTree>): RangeTree | undefined { if (trees.length <= 1) { return trees[0]; } const first: RangeTree = trees[0]; let delta: number = 0; for (const tree of trees) { delta += tree.delta; } const children: RangeTree[] = mergeRangeTreeChildren(trees); return new RangeTree(first.start, first.end, delta, children); } class RangeTreeWithParent { readonly parentIndex: number; readonly tree: RangeTree; constructor(parentIndex: number, tree: RangeTree) { this.parentIndex = parentIndex; this.tree = tree; } } class StartEvent { readonly offset: number; readonly trees: RangeTreeWithParent[]; constructor(offset: number, trees: RangeTreeWithParent[]) { this.offset = offset; this.trees = trees; } static compare(a: StartEvent, b: StartEvent): number { return a.offset - b.offset; } } class StartEventQueue { private readonly queue: StartEvent[]; private nextIndex: number; private pendingOffset: number; private pendingTrees: RangeTreeWithParent[] | undefined; private constructor(queue: StartEvent[]) { this.queue = queue; this.nextIndex = 0; this.pendingOffset = 0; this.pendingTrees = undefined; } static fromParentTrees(parentTrees: ReadonlyArray<RangeTree>): StartEventQueue { const startToTrees: Map<number, RangeTreeWithParent[]> = new Map(); for (const [parentIndex, parentTree] of parentTrees.entries()) { for (const child of parentTree.children) { let trees: RangeTreeWithParent[] | undefined = startToTrees.get(child.start); if (trees === undefined) { trees = []; startToTrees.set(child.start, trees); } trees.push(new RangeTreeWithParent(parentIndex, child)); } } const queue: StartEvent[] = []; for (const [startOffset, trees] of startToTrees) { queue.push(new StartEvent(startOffset, trees)); } queue.sort(StartEvent.compare); return new StartEventQueue(queue); } setPendingOffset(offset: number): void { this.pendingOffset = offset; } pushPendingTree(tree: RangeTreeWithParent): void { if (this.pendingTrees === undefined) { this.pendingTrees = []; } this.pendingTrees.push(tree); } next(): StartEvent | undefined { const pendingTrees: RangeTreeWithParent[] | undefined = this.pendingTrees; const nextEvent: StartEvent | undefined = this.queue[this.nextIndex]; if (pendingTrees === undefined) { this.nextIndex++; return nextEvent; } else if (nextEvent === undefined) { this.pendingTrees = undefined; return new StartEvent(this.pendingOffset, pendingTrees); } else { if (this.pendingOffset < nextEvent.offset) { this.pendingTrees = undefined; return new StartEvent(this.pendingOffset, pendingTrees); } else { if (this.pendingOffset === nextEvent.offset) { this.pendingTrees = undefined; for (const tree of pendingTrees) { nextEvent.trees.push(tree); } } this.nextIndex++; return nextEvent; } } } } function mergeRangeTreeChildren(parentTrees: ReadonlyArray<RangeTree>): RangeTree[] { const result: RangeTree[] = []; const startEventQueue: StartEventQueue = StartEventQueue.fromParentTrees(parentTrees); const parentToNested: Map<number, RangeTree[]> = new Map(); let openRange: Range | undefined; while (true) { const event: StartEvent | undefined = startEventQueue.next(); if (event === undefined) { break; } if (openRange !== undefined && openRange.end <= event.offset) { result.push(nextChild(openRange, parentToNested)); openRange = undefined; } if (openRange === undefined) { let openRangeEnd: number = event.offset + 1; for (const {parentIndex, tree} of event.trees) { openRangeEnd = Math.max(openRangeEnd, tree.end); insertChild(parentToNested, parentIndex, tree); } startEventQueue.setPendingOffset(openRangeEnd); openRange = {start: event.offset, end: openRangeEnd}; } else { for (const {parentIndex, tree} of event.trees) { if (tree.end > openRange.end) { const right: RangeTree = tree.split(openRange.end); startEventQueue.pushPendingTree(new RangeTreeWithParent(parentIndex, right)); } insertChild(parentToNested, parentIndex, tree); } } } if (openRange !== undefined) { result.push(nextChild(openRange, parentToNested)); } return result; } function insertChild(parentToNested: Map<number, RangeTree[]>, parentIndex: number, tree: RangeTree): void { let nested: RangeTree[] | undefined = parentToNested.get(parentIndex); if (nested === undefined) { nested = []; parentToNested.set(parentIndex, nested); } nested.push(tree); } function nextChild(openRange: Range, parentToNested: Map<number, RangeTree[]>): RangeTree { const matchingTrees: RangeTree[] = []; for (const nested of parentToNested.values()) { if (nested.length === 1 && nested[0].start === openRange.start && nested[0].end === openRange.end) { matchingTrees.push(nested[0]); } else { matchingTrees.push(new RangeTree( openRange.start, openRange.end, 0, nested, )); } } parentToNested.clear(); return mergeRangeTrees(matchingTrees)!; }
the_stack
import { InternalSchema, SchemaModel, ModelField, PersistentModel, isGraphQLScalarType, QueryOne, PredicatesGroup, isPredicateObj, SortPredicatesGroup, PredicateObject, isPredicateGroup, isModelFieldType, isTargetNameAssociation, isModelAttributeAuth, ModelAttributeAuth, ModelAuthRule, utils, } from '@aws-amplify/datastore'; import { getSQLiteType } from './types'; const { USER, isNonModelConstructor, isModelConstructor } = utils; export type ParameterizedStatement = [string, any[]]; const keysFromModel = model => Object.keys(model) .map(k => `"${k}"`) .join(', '); const valuesFromModel = (model): [string, any[]] => { const values = Object.values(model).map(prepareValueForDML); const paramaterized = values.map(() => '?').join(', '); return [paramaterized, values]; }; const updateSet: (model: any) => [any, any] = model => { const values = []; const paramaterized = Object.entries(model) .filter(([k]) => k !== 'id') .map(([k, v]) => { values.push(prepareValueForDML(v)); return `"${k}"=?`; }) .join(', '); return [paramaterized, values]; }; function prepareValueForDML(value: unknown): any { const scalarTypes = ['string', 'number', 'boolean']; const isScalarType = value === null || value === undefined || scalarTypes.includes(typeof value); if (isScalarType) { return value; } const isObjectType = typeof value === 'object' && (Object.getPrototypeOf(value).constructor === Object || isNonModelConstructor(Object.getPrototypeOf(value).constructor) || isModelConstructor(Object.getPrototypeOf(value).constructor)); if (Array.isArray(value) || isObjectType) { return JSON.stringify(value); } return `${value}`; } export function generateSchemaStatements(schema: InternalSchema): string[] { return Object.keys(schema.namespaces).flatMap(namespaceName => { const namespace = schema.namespaces[namespaceName]; const isUserModel = namespaceName === USER; return Object.values(namespace.models).map(model => modelCreateTableStatement(model, isUserModel) ); }); } export const implicitAuthFieldsForModel: (model: SchemaModel) => string[] = ( model: SchemaModel ) => { if (!model.attributes || !model.attributes.length) { return []; } const authRules: ModelAttributeAuth = model.attributes.find( isModelAttributeAuth ); if (!authRules) { return []; } const authFieldsForModel = authRules.properties.rules .filter((rule: ModelAuthRule) => rule.ownerField || rule.groupsField) .map((rule: ModelAuthRule) => rule.ownerField || rule.groupsField); return authFieldsForModel.filter((authField: string) => { const authFieldExplicitlyDefined = Object.values(model.fields).find( (f: ModelField) => f.name === authField ); return !authFieldExplicitlyDefined; }); }; export function modelCreateTableStatement( model: SchemaModel, userModel: boolean = false ): string { // implicitly defined auth fields, e.g., `owner`, `groupsField`, etc. const implicitAuthFields = implicitAuthFieldsForModel(model); let fields = Object.values(model.fields).reduce((acc, field: ModelField) => { if (isGraphQLScalarType(field.type)) { if (field.name === 'id') { return acc + '"id" PRIMARY KEY NOT NULL'; } let columnParam = `"${field.name}" ${getSQLiteType(field.type)}`; if (field.isRequired) { columnParam += ' NOT NULL'; } return acc + `, ${columnParam}`; } if (isModelFieldType(field.type)) { // add targetName as well as field name for BELONGS_TO relations if (isTargetNameAssociation(field.association)) { const required = field.isRequired ? ' NOT NULL' : ''; let columnParam = `"${field.name}" TEXT`; // check if this field has been explicitly defined in the model const fkDefinedInModel = Object.values(model.fields).find( (f: ModelField) => f.name === field.association.targetName ); // only add auto-generate it if not if (!fkDefinedInModel) { columnParam += `, "${field.association.targetName}" TEXT${required}`; } return acc + `, ${columnParam}`; } } // default to TEXT let columnParam = `"${field.name}" TEXT`; if (field.isRequired) { columnParam += ' NOT NULL'; } return acc + `, ${columnParam}`; }, ''); implicitAuthFields.forEach((authField: string) => { fields += `, ${authField} TEXT`; }); if (userModel) { fields += ', "_version" INTEGER, "_lastChangedAt" INTEGER, "_deleted" INTEGER'; } const createTableStatement = `CREATE TABLE IF NOT EXISTS "${model.name}" (${fields});`; return createTableStatement; } export function modelInsertStatement( model: PersistentModel, tableName: string ): ParameterizedStatement { const keys = keysFromModel(model); const [paramaterized, values] = valuesFromModel(model); const insertStatement = `INSERT INTO "${tableName}" (${keys}) VALUES (${paramaterized})`; return [insertStatement, values]; } export function modelUpdateStatement( model: PersistentModel, tableName: string ): ParameterizedStatement { const [paramaterized, values] = updateSet(model); const updateStatement = `UPDATE "${tableName}" SET ${paramaterized} WHERE id=?`; return [updateStatement, [...values, model.id]]; } export function queryByIdStatement( id: string, tableName: string ): ParameterizedStatement { return [`SELECT * FROM "${tableName}" WHERE "id" = ?`, [id]]; } /* Predicates supported by DataStore: Strings: eq | ne | le | lt | ge | gt | contains | notContains | beginsWith | between Numbers: eq | ne | le | lt | ge | gt | between Lists: contains | notContains */ const comparisonOperatorMap = { eq: '=', ne: '!=', le: '<=', lt: '<', ge: '>=', gt: '>', }; const logicalOperatorMap = { beginsWith: 'LIKE', contains: 'LIKE', notContains: 'NOT LIKE', between: 'BETWEEN', }; const whereConditionFromPredicateObject = ({ field, operator, operand, }: { field: string; operator: | keyof typeof logicalOperatorMap | keyof typeof comparisonOperatorMap; operand: any; }): ParameterizedStatement => { const comparisonOperator = comparisonOperatorMap[operator]; if (comparisonOperator) { return [`"${field}" ${comparisonOperator} ?`, [operand]]; } const logicalOperatorKey = <keyof typeof logicalOperatorMap>operator; const logicalOperator = logicalOperatorMap[logicalOperatorKey]; if (logicalOperator) { let rightExp = []; switch (logicalOperatorKey) { case 'between': rightExp = operand; // operand is a 2-tuple break; case 'beginsWith': rightExp = [`${operand}%`]; break; case 'contains': case 'notContains': rightExp = [`%${operand}%`]; break; default: const _: never = logicalOperatorKey; // Incorrect WHERE clause can result in data loss throw new Error('Cannot map predicate to a valid WHERE clause'); } return [ `"${field}" ${logicalOperator} ${rightExp.map(_ => '?').join(' AND ')}`, rightExp, ]; } }; export function whereClauseFromPredicate<T extends PersistentModel>( predicate: PredicatesGroup<T> ): ParameterizedStatement { const result = []; const params = []; recurse(predicate, result, params); const whereClause = `WHERE ${result.join(' ')}`; return [whereClause, params]; function recurse( predicate: PredicatesGroup<T> | PredicateObject<T>, result = [], params = [] ): void { if (isPredicateGroup(predicate)) { const { type: groupType, predicates: groupPredicates } = predicate; let filterType: string = ''; let isNegation = false; switch (groupType) { case 'not': isNegation = true; break; case 'and': filterType = 'AND'; break; case 'or': filterType = 'OR'; break; default: const _: never = groupType; throw new Error(`Invalid ${groupType}`); } const groupResult = []; for (const p of groupPredicates) { recurse(p, groupResult, params); } result.push( `${isNegation ? 'NOT' : ''}(${groupResult.join(` ${filterType} `)})` ); } else if (isPredicateObj(predicate)) { const [condition, conditionParams] = whereConditionFromPredicateObject( predicate ); result.push(condition); params.push(...conditionParams); } } } const sortDirectionMap = { ASCENDING: 'ASC', DESCENDING: 'DESC', }; export function orderByClauseFromSort<T extends PersistentModel>( sortPredicate: SortPredicatesGroup<T> = [] ): string { const orderByParts = sortPredicate.map( ({ field, sortDirection }) => `"${field}" ${sortDirectionMap[sortDirection]}` ); // We always sort by _rowid_ last orderByParts.push(`_rowid_ ${sortDirectionMap.ASCENDING}`); return `ORDER BY ${orderByParts.join(', ')}`; } export function limitClauseFromPagination( limit: number, page: number = 0 ): ParameterizedStatement { const params = [limit]; let clause = 'LIMIT ?'; if (page) { const offset = limit * page; params.push(offset); clause += ' OFFSET ?'; } return [clause, params]; } export function queryAllStatement<T extends PersistentModel>( tableName: string, predicate?: PredicatesGroup<T>, sort?: SortPredicatesGroup<T>, limit?: number, page?: number ): ParameterizedStatement { let statement = `SELECT * FROM "${tableName}"`; const params = []; if (predicate && predicate.predicates.length) { const [whereClause, whereParams] = whereClauseFromPredicate(predicate); statement += ` ${whereClause}`; params.push(...whereParams); } const orderByClause = orderByClauseFromSort(sort); statement += ` ${orderByClause}`; if (limit) { const [limitClause, limitParams] = limitClauseFromPagination(limit, page); statement += ` ${limitClause}`; params.push(...limitParams); } return [statement, params]; } export function queryOneStatement( firstOrLast, tableName: string ): ParameterizedStatement { if (firstOrLast === QueryOne.FIRST) { // ORDER BY rowid will no longer work as expected if a customer has // a field by that name in their schema. We may want to enforce it // as a reserved keyword in Codegen return [`SELECT * FROM ${tableName} ORDER BY _rowid_ LIMIT 1`, []]; } else { return [`SELECT * FROM ${tableName} ORDER BY _rowid_ DESC LIMIT 1`, []]; } } export function deleteByIdStatement( id: string, tableName: string ): ParameterizedStatement { const deleteStatement = `DELETE FROM "${tableName}" WHERE "id"=?`; return [deleteStatement, [id]]; } export function deleteByPredicateStatement<T extends PersistentModel>( tableName: string, predicate?: PredicatesGroup<T> ): ParameterizedStatement { let statement = `DELETE FROM "${tableName}"`; const params = []; if (predicate && predicate.predicates.length) { const [whereClause, whereParams] = whereClauseFromPredicate(predicate); statement += ` ${whereClause}`; params.push(...whereParams); } return [statement, params]; }
the_stack
import { delay, all, call, CallEffect } from "redux-saga/effects"; import { reduceCollection, addResourcesWithVolumeUpdates } from "./utils"; import { log, SECOND } from "@opstrace/utils"; import { find, K8sResource, Nodes, Ingresses, StorageClasses, PersistentVolumeClaims, ServiceAccounts, PersistentVolumes, StatefulSets, Services, Secrets, RoleBindings, Roles, Namespaces, Deployments, CustomResourceDefinitions, ConfigMaps, ClusterRoleBindings, DaemonSets, ClusterRoles, PodSecurityPolicies, ApiServices, ResourceCollection } from "../kinds"; import { createResource, updateResource, deleteResource } from "../api"; import { V1AlertmanagerResources, V1PodmonitorResources, V1PrometheusResources, V1PrometheusruleResources, V1ServicemonitorResources, V1CertificateResources, V1CertificaterequestResources, V1ChallengeResources, V1ClusterissuerResources, V1IssuerResources, V1OrderResources, V1Alpha1CortexResources } from "../custom-resources"; import { haveLabelsChanged, hasStatefulSetChanged, hasServiceChanged, hasSecretChanged, hasDeploymentChanged, hasDaemonSetChanged, hasConfigMapChanged, hasPrometheusRuleChanged, hasServiceMonitorChanged, hasIngressChanged, hasAlertManagerChanged, hasPrometheusChanged, hasCertificateChanged, hasClusterRoleChanged, hasCustomResourceDefinitionChanged, hasCortexSpecChanged } from "../equality"; import { entries } from "@opstrace/utils"; export type ReconcileResourceTypes = { Nodes: Nodes; Ingresses: Ingresses; StorageClasses: StorageClasses; PersistentVolumes: PersistentVolumes; PersistentVolumeClaims: PersistentVolumeClaims; StatefulSets: StatefulSets; ServiceAccounts: ServiceAccounts; Services: Services; Secrets: Secrets; RoleBindings: RoleBindings; Roles: Roles; Namespaces: Namespaces; Deployments: Deployments; DaemonSets: DaemonSets; CustomResourceDefinitions: CustomResourceDefinitions; ConfigMaps: ConfigMaps; ClusterRoleBindings: ClusterRoleBindings; ClusterRoles: ClusterRoles; PodSecurityPolicies: PodSecurityPolicies; ApiServices: ApiServices; Alertmanagers: V1AlertmanagerResources; PodMonitors: V1PodmonitorResources; Prometheuses: V1PrometheusResources; PrometheusRules: V1PrometheusruleResources; ServiceMonitors: V1ServicemonitorResources; Certificates: V1CertificateResources; CertificateRequests: V1CertificaterequestResources; Challenges: V1ChallengeResources; ClusterIssuers: V1ClusterissuerResources; Issuers: V1IssuerResources; Orders: V1OrderResources; Cortices: V1Alpha1CortexResources; }; // Keep track of the last time we logged about missing 'opstrace' annotations. // This avoids flooding logs when something is being ignored by the controller, // while still ensuring that it's consistently reported and visible. const NOT_OURS_LOG_TTL_MILLIS = 5 * 60 * 1000; // 5 minutes let notOursLastLogMillis = 0; export function* reconcile( desired: ResourceCollection, actual: Partial<ReconcileResourceTypes>, isDestroyingCluster: boolean ): Generator<CallEffect, void, unknown> { const actualState: ReconcileResourceTypes = { Nodes: [], Ingresses: [], StorageClasses: [], PersistentVolumes: [], PersistentVolumeClaims: [], StatefulSets: [], ServiceAccounts: [], Services: [], Secrets: [], RoleBindings: [], Roles: [], Namespaces: [], Deployments: [], DaemonSets: [], CustomResourceDefinitions: [], ConfigMaps: [], ClusterRoleBindings: [], ClusterRoles: [], PodSecurityPolicies: [], ApiServices: [], Alertmanagers: [], PodMonitors: [], Prometheuses: [], PrometheusRules: [], ServiceMonitors: [], Certificates: [], CertificateRequests: [], Challenges: [], ClusterIssuers: [], Issuers: [], Orders: [], Cortices: [], ...actual }; try { const createCollection: K8sResource[] = []; const deleteCollection: K8sResource[] = []; const updateCollection: K8sResource[] = []; const notOursCollection: K8sResource[] = []; const desiredState = reduceCollection(desired.get()); // Add an annotation with the controller version. This is used to check if // the CRD requires an update since typescript fails at comparing the CRD // schemas. desiredState.CustomResourceDefinitions.map(e => { e.setManagementVersion(); }); // First thing is to ensure CRDs are reconciled otherwise we might end up // trying to create resources (ex Prometheus ServiceMonitor objects) when // the CRD doesn't exist yet. reconcileResourceType( desiredState.CustomResourceDefinitions, actualState.CustomResourceDefinitions, hasCustomResourceDefinitionChanged, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Ingresses, actualState.Ingresses, (desired, existing) => hasIngressChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.StorageClasses, actualState.StorageClasses, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.PersistentVolumeClaims, actualState.PersistentVolumeClaims, null, // Operators may create their own PVCs, which sometimes do not get cleaned up automatically. // Specifically, this is observed with this prometheus-operator PVC in tenant namespaces: // 'prometheus-system-prometheus-db-prometheus-system-prometheus-0' // Although prometheus-operator allows customizing PVC annotations, during normal operation // we do not want them labeled as owned by us since we aren't managing them, but during // destroy we want to ensure that they are all cleanly torn down. isDestroyingCluster ? _pvc => true // during cluster destroy, delete all PVCs regardless of attributes : null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.StatefulSets, actualState.StatefulSets, (desired, existing) => hasStatefulSetChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ServiceAccounts, actualState.ServiceAccounts, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Services, actualState.Services, (desired, existing) => hasServiceChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Secrets, actualState.Secrets, (desired, existing) => hasSecretChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.RoleBindings, actualState.RoleBindings, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Roles, actualState.Roles, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Namespaces, actualState.Namespaces, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Deployments, actualState.Deployments, (desired, existing) => hasDeploymentChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.DaemonSets, actualState.DaemonSets, (desired, existing) => hasDaemonSetChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ConfigMaps, actualState.ConfigMaps, (desired, existing) => hasConfigMapChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ClusterRoleBindings, actualState.ClusterRoleBindings, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ClusterRoles, actualState.ClusterRoles, (desired, existing) => hasClusterRoleChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.PodSecurityPolicies, actualState.PodSecurityPolicies, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ApiServices, actualState.ApiServices, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Alertmanagers, actualState.Alertmanagers, (desired, existing) => hasAlertManagerChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.PodMonitors, actualState.PodMonitors, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Prometheuses, actualState.Prometheuses, (desired, existing) => hasPrometheusChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.PrometheusRules, actualState.PrometheusRules, (desired, existing) => hasPrometheusRuleChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ServiceMonitors, actualState.ServiceMonitors, (desired, existing) => hasServiceMonitorChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Certificates, actualState.Certificates, (desired, existing) => hasCertificateChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.CertificateRequests, actualState.CertificateRequests, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Challenges, actualState.Challenges, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.ClusterIssuers, actualState.ClusterIssuers, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Issuers, actualState.Issuers, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Orders, actualState.Orders, null, null, createCollection, deleteCollection, updateCollection, notOursCollection ); reconcileResourceType( desiredState.Cortices, actualState.Cortices, (desired, existing) => hasCortexSpecChanged(desired, existing), null, createCollection, deleteCollection, updateCollection, notOursCollection ); if (notOursCollection.length !== 0) { const nowMillis = new Date().getTime(); if (nowMillis - notOursLastLogMillis >= NOT_OURS_LOG_TTL_MILLIS) { // Could log on a single line, but in practice there should only be a few of these at any time notOursCollection.forEach(r => { log.notice( `Leaving existing ${r.constructor.name} ${r.namespace}/${r.name} as-is (missing 'opstrace' annotation)` ); }); notOursLastLogMillis = nowMillis; } } const toUpdate = addResourcesWithVolumeUpdates( reduceCollection(updateCollection), desiredState ); // Create a new updateCollection since we've possibly added items to toUpdate with addResourcesWithVolumeUpdates const comprehensiveUpdateCollection = entries(toUpdate).reduce< K8sResource[] // eslint-disable-next-line @typescript-eslint/no-unused-vars >((acc, [_, resources]) => acc.concat(resources), []); yield call(applyRateLimitedApiRequests, createCollection, "create"); yield call(applyRateLimitedApiRequests, deleteCollection, "delete"); yield call( applyRateLimitedApiRequests, comprehensiveUpdateCollection, "update" ); } catch (e: any) { log.error(`Error in reconcile loop: ${e}`); } } function reconcileResourceType<T extends K8sResource>( desiredResources: T[], actualResources: T[], customHasChanged: null | ((desired: T, existing: T) => boolean), customCanDelete: null | ((resource: T) => boolean), createCollection: K8sResource[], deleteCollection: K8sResource[], updateCollection: K8sResource[], notOursCollection: K8sResource[] ) { desiredResources.forEach(r => { const existing = find(r, actualResources); if (!existing) { createCollection.push(r); return; } if (!r.isImmutable()) { if ( // Default: In all cases, changing labels means an update should be performed haveLabelsChanged(r, existing) || // Custom: Additional type-specific checks for detecting changes (customHasChanged != null && customHasChanged(r, existing)) ) { // If the resource has had its opstrace annotation removed, do not modify it. // This allows us to manually make changes to resources without the controller stepping on them. if (existing.isOurs()) { updateCollection.push(r); } else { notOursCollection.push(existing); } } } }); actualResources.forEach(r => { const isDesired = find(r, desiredResources); if ( // Default: Only delete things that are owned by us and aren't special in some way (!isDesired && r.isOurs() && !r.isTerminating() && !r.isProtected() && !r.isImmutable()) || // Custom: In certain circumstances, some types should be deleted even if not owned by us (customCanDelete != null && customCanDelete(r)) ) { deleteCollection.push(r); } }); } function* applyRateLimitedApiRequests<T extends K8sResource>( resources: T[], method: "create" | "delete" | "update" ) { // call method on resources in chunks so we don't get rate limited const chunkSize = 10; let index = 0; while (index < resources.length) { const slice = resources.slice(index, index + chunkSize); log.info( `API ${method} request ${index / chunkSize + 1} of ${Math.ceil( resources.length / chunkSize )}` ); if (method === "create") { entries(reduceCollection(slice)).forEach(([name, resources]) => { if (resources.length) { log.info(`Creating ${resources.length} ${name}:`); resources.forEach((r: K8sResource) => log.info(`Creating ${name}: ${r.namespace}/${r.name}`) ); } }); yield all([slice.map(createResource)]); } if (method === "update") { entries(reduceCollection(slice)).forEach(([name, resources]) => { if (resources.length) { log.info(`Updating ${resources.length} ${name}:`); resources.forEach((r: K8sResource) => log.info(`Updating ${name}: ${r.namespace}/${r.name}`) ); } }); yield all([slice.map(updateResource)]); } if (method === "delete") { entries(reduceCollection(slice)).forEach(([name, resources]) => { if (name === "Namespaces") { return; } if (resources.length) { log.info(`Deleting ${resources.length} ${name}:`); resources.forEach((r: K8sResource) => log.info(`Deleting ${name}: ${r.namespace}/${r.name}`) ); } }); yield all([slice.map(deleteResource)]); } yield delay(1 * SECOND); index += chunkSize; } }
the_stack
import addon from '../utils/addon'; import { NodeLayout } from './QLayout'; import { NativeElement } from '../core/Component'; import { FlexLayout } from '../core/FlexLayout'; import { WidgetAttribute, WindowType, ContextMenuPolicy, FocusReason, FocusPolicy } from '../QtEnums'; import { QIcon } from '../QtGui/QIcon'; import { QCursor } from '../QtGui/QCursor'; import { CursorShape, WindowState } from '../QtEnums'; import { StyleSheet, prepareInlineStyleSheet } from '../core/Style/StyleSheet'; import { checkIfNativeElement } from '../utils/helpers'; import { YogaWidget } from '../core/YogaWidget'; import { QPoint } from '../QtCore/QPoint'; import { QSize } from '../QtCore/QSize'; import { QRect } from '../QtCore/QRect'; import { QObjectSignals } from '../QtCore/QObject'; import { QFont } from '../QtGui/QFont'; import { QAction } from './QAction'; import memoizeOne from 'memoize-one'; import { QGraphicsEffect } from './QGraphicsEffect'; import { wrapperCache } from '../core/WrapperCache'; import { QSizePolicyPolicy } from './QSizePolicy'; import { QStyle } from '../QtGui/QStyle'; import { QWindow } from '../QtGui/QWindow'; /** > Abstract class to add functionalities common to all Widgets. **This class implements all methods, properties of Qt's [QWidget class](https://doc.qt.io/qt-5/qwidget.html) so that it can be inherited by all widgets** `NodeWidget` is an abstract class and hence no instances of the same should be created. It exists so that we can add similar functionalities to all widget's easily. Additionally it helps in type checking process. If you wish to create a `div` like widget use [QWidget](QWidget.md) instead. **NodeWidget is the base class for all widgets.** ### Example ```javascript const { NodeWidget, QPushButton, QWidget, QRadioButton } = require("@nodegui/nodegui"); // showWidget can accept any widget since it expects NodeWidget const showWidget = (widget: NodeWidget) => { widget.show(); }; showWidget(new QPushButton()); showWidget(new QWidget()); showWidget(new QRadioButton()); ``` All Widgets should extend from NodeWidget Implement all native QWidget methods here so that all widgets get access to those aswell */ export abstract class NodeWidget<Signals extends QWidgetSignals> extends YogaWidget<Signals> { _layout?: NodeLayout<Signals>; _rawInlineStyle = ''; type = 'widget'; private _effect?: QGraphicsEffect<any> | null; constructor(native: NativeElement) { super(native); this.setStyleSheet = memoizeOne(this.setStyleSheet); this.setInlineStyle = memoizeOne(this.setInlineStyle); this.setObjectName = memoizeOne(this.setObjectName); } get layout(): NodeLayout<Signals> | undefined { return this._layout; } set layout(l: NodeLayout<Signals> | undefined) { this._layout = l; } // *** Public Functions *** acceptDrops(): boolean { return this.property('acceptDrops').toBool(); } accessibleDescription(): string { return this.property('accessibleDescription').toString(); } accessibleName(): string { return this.property('accessibleName').toString(); } // TODO: QList<QAction *> actions() const activateWindow(): void { this.native.activateWindow(); } addAction(action: QAction | string): QAction { if (typeof action === 'string') { const qaction = new QAction(); qaction.setText(action); this.native.addAction(qaction.native); return qaction; } this.native.addAction(action.native); return action; } // TODO: void addActions(QList<QAction *> actions) adjustSize(): void { this.native.adjustSize(); } autoFillBackground(): boolean { return this.property('autoFillBackground').toBool(); } // CLASS: QWidget // TODO: QPalette::ColorRole backgroundRole() const // TODO: QBackingStore * backingStore() const baseSize(): QSize { return QSize.fromQVariant(this.property('baseSize')); } // TODO: QWidget * childAt(int x, int y) const // TODO: QWidget * childAt(const QPoint &p) const childrenRect(): QRect { return QRect.fromQVariant(this.property('childrenRect')); } // TODO: QRegion childrenRegion() const clearFocus(): void { this.native.clearFocus(); } clearMask(): void { this.native.clearMask(); } // TODO: QMargins contentsMargins() const // TODO: QRect contentsRect() const contextMenuPolicy(): ContextMenuPolicy { return this.property('contextMenuPolicy').toInt(); } // TODO: QCursor cursor() const // TODO: WId effectiveWinId() const ensurePolished(): void { this.native.ensurePolished(); } // TODO: Qt::FocusPolicy focusPolicy() const // TODO: QWidget * focusProxy() const // TODO: QWidget * focusWidget() const font(): QFont { return QFont.fromQVariant(this.property('font')); } // TODO: QFontInfo fontInfo() const // TODO: QFontMetrics fontMetrics() const // TODO: QPalette::ColorRole foregroundRole() const frameGeometry(): QRect { return QRect.fromQVariant(this.property('frameGeometry')); } frameSize(): QSize { return QSize.fromQVariant(this.property('frameSize')); } geometry(): QRect { return QRect.fromQVariant(this.property('geometry')); } // TODO: QPixmap grab(const QRect &rectangle = QRect(QPoint(0, 0), QSize(-1, -1))) // TODO: void grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags = Qt::GestureFlags()) grabKeyboard(): void { this.native.grabKeyboard(); } grabMouse(): void { this.native.grabMouse(); } // TODO: void grabMouse(const QCursor &cursor) // TODO: int grabShortcut(const QKeySequence &key, Qt::ShortcutContext context = Qt::WindowShortcut) // TODO: QGraphicsEffect * graphicsEffect() const // TODO: QGraphicsProxyWidget * graphicsProxyWidget() const hasFocus(): boolean { return this.property('focus').toBool(); } hasHeightForWidth(): boolean { return this.native.hasHeightForWidth(); } hasMouseTracking(): boolean { return this.property('mouseTracking').toBool(); } hasTabletTracking(): boolean { return this.property('tabletTracking').toBool(); } height(): number { return this.property('height').toInt(); } heightForWidth(w: number): number { return this.native.heightForWidth(w); } // TODO: Qt::InputMethodHints inputMethodHints() const // TODO: virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const // TODO: void insertAction(QAction *before, QAction *action) // TODO: void insertActions(QAction *before, QList<QAction *> actions) isActiveWindow(): boolean { return this.property('isActiveWindow').toBool(); } // TODO: bool isAncestorOf(const QWidget *child) const isEnabled(): boolean { return this.property('enabled').toBool(); } // TODO: bool isEnabledTo(const QWidget *ancestor) const isFullScreen(): boolean { return this.property('fullScreen').toBool(); } isHidden(): boolean { return !this.property('visible').toBool(); } isMaximized(): boolean { return this.property('maximized').toBool(); } isMinimized(): boolean { return this.property('minimized').toBool(); } isModal(): boolean { return this.property('modal').toBool(); } isVisible(): boolean { return this.property('visible').toBool(); } // TODO: bool isVisibleTo(const QWidget *ancestor) const isWindow(): boolean { return this.native.isWindow(); } isWindowModified(): boolean { return this.native.isWindowModified(); } // TODO: QLayout * layout() const // TODO: Qt::LayoutDirection layoutDirection() const // TODO: QLocale locale() const // TODO: QPoint mapFrom(const QWidget *parent, const QPoint &pos) const mapFromGlobal(pos: QPoint): QPoint { return new QPoint(this.native.mapFromGlobal(pos.native)); } mapFromParent(pos: QPoint): QPoint { return new QPoint(this.native.mapFromParent(pos.native)); } // TODO: QPoint mapTo(const QWidget *parent, const QPoint &pos) const mapToGlobal(pos: QPoint): QPoint { return new QPoint(this.native.mapToGlobal(pos.native)); } mapToParent(pos: QPoint): QPoint { return new QPoint(this.native.mapToParent(pos.native)); } // TODO: QRegion mask() const maximumHeight(): number { return this.property('maximumHeight').toInt(); } maximumSize(): QSize { return QSize.fromQVariant(this.property('maximumSize')); } maximumWidth(): number { return this.property('maximumWidth').toInt(); } minimumHeight(): number { return this.property('minimumHeight').toInt(); } minimumSize(): QSize { return QSize.fromQVariant(this.property('minimumSize')); } minimumSizeHint(): QSize { return new QSize(this.native.minimumSizeHint()); } minimumWidth(): number { return this.property('minimumWidth').toInt(); } // TODO: void move(const QPoint &) move(x: number, y: number): void { this.native.move(x, y); } // TODO: QWidget * nativeParentWidget() const // TODO: QWidget * nextInFocusChain() const normalGeometry(): QRect { return QRect.fromQVariant(this.property('normalGeometry')); } // TODO: void overrideWindowFlags(Qt::WindowFlags flags) // TODO: const QPalette & palette() const // TODO: QWidget * parentWidget() const // PROP: QWidget pos(): { x: number; y: number } { return this.native.pos(); } // TODO: QWidget * previousInFocusChain() const rect(): QRect { return QRect.fromQVariant(this.property('rect')); } releaseKeyboard(): void { this.native.releaseKeyboard(); } releaseMouse(): void { this.native.releaseMouse(); } releaseShortcut(id: number): void { this.native.releaseShortcut(id); } removeAction(action: QAction): void { this.native.removeAction(action.native); } // TODO: void render(QPaintDevice *target, const QPoint &targetOffset = QPoint(), const QRegion &sourceRegion = QRegion(), QWidget::RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren)) // TODO: void render(QPainter *painter, const QPoint &targetOffset = QPoint(), const QRegion &sourceRegion = QRegion(), QWidget::RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren)) // TODO: void repaint(int x, int y, int w, int h) // TODO: void repaint(const QRect &rect) // TODO: void repaint(const QRegion &rgn) repolish(): void { this.native.repolish(); } // TODO: void resize(const QSize &) resize(width: number, height: number): void { this.native.resize(width, height); } // TODO: QScreen *QWidget::screen() const setAcceptDrops(on: boolean): void { this.setProperty('acceptDrops', on); } setAccessibleDescription(description: string): void { this.setProperty('accessibleDescription', description); } setAccessibleName(name: string): void { this.setProperty('accessibleName', name); } setAttribute(attribute: WidgetAttribute, switchOn: boolean): void { // react:⛔️ return this.native.setAttribute(attribute, switchOn); } setAutoFillBackground(enabled: boolean): void { this.setProperty('autoFillBackground', enabled); } // TODO: void setBackgroundRole(QPalette::ColorRole role) setBaseSize(size: QSize): void { this.setProperty('baseSize', size.native); } // TODO: void setBaseSize(int basew, int baseh) setContentsMargins(left: number, top: number, right: number, bottom: number): void { this.native.setContentsMargins(left, top, right, bottom); } // TODO: void setContentsMargins(const QMargins &margins) setContextMenuPolicy(contextMenuPolicy: ContextMenuPolicy): void { this.setProperty('contextMenuPolicy', contextMenuPolicy); } // PROP: QWidget setCursor(cursor: CursorShape | QCursor): void { if (typeof cursor === 'number') { this.native.setCursor(cursor); } else { this.native.setCursor(cursor.native); } } // Embedded only: void setEditFocus(bool enable) setFixedHeight(h: number): void { this.native.setFixedHeight(h); } // TODO: void setFixedSize(const QSize &s) setFixedSize(width: number, height: number): void { this.native.setFixedSize(width, height); } setFixedWidth(w: number): void { this.native.setFixedWidth(w); } setFocusPolicy(policy: FocusPolicy): void { this.setProperty('focusPolicy', policy); } // TODO: void setFocusProxy(QWidget *w) setFont(font: QFont): void { this.native.setProperty('font', font.native); } // TODO: void setForegroundRole(QPalette::ColorRole role) // TODO: void setGeometry(const QRect &) setGeometry(x: number, y: number, w: number, h: number): void { this.native.setGeometry(x, y, w, h); } setGraphicsEffect(effect: QGraphicsEffect<any>): void { this._effect = effect; this.native.setGraphicsEffect(effect.native); } // TODO: void setInputMethodHints(Qt::InputMethodHints hints) setInlineStyle(style: string): void { this._rawInlineStyle = style; const preparedSheet = prepareInlineStyleSheet(this, style); this.native.setStyleSheet(preparedSheet); } setLayout(parentLayout: NodeLayout<Signals>): void { const flexLayout = parentLayout as FlexLayout; this.native.setLayout(parentLayout.native); if (flexLayout.setFlexNode) { //if flex layout set the flexnode flexLayout.setFlexNode(this.getFlexNode()); } this._layout = parentLayout; } // TODO: void setLayoutDirection(Qt::LayoutDirection direction) // TODO: void setLocale(const QLocale &locale) // TODO: void setMask(const QBitmap &bitmap) // TODO: void setMask(const QRegion &region) setMaximumHeight(maxh: number): void { this.setProperty('maximumHeight', maxh); } // PROP: QWidget // TODO: void setMaximumSize(const QSize &) setMaximumSize(maxw: number, maxh: number): void { this.native.setMaximumSize(maxw, maxh); } setMaximumWidth(maxw: number): void { this.setProperty('maximumWidth', maxw); } // PROP: QWidget // TODO: void setMinimumSize(const QSize &size) setMinimumHeight(minh: number): void { this.setProperty('minimumHeight', minh); } setMinimumSize(minw: number, minh: number): void { this.native.setMinimumSize(minw, minh); } setMinimumWidth(minw: number): void { this.setProperty('minimumWidth', minw); } setMouseTracking(isMouseTracked: boolean): void { this.setProperty('mouseTracking', isMouseTracked); } setObjectName(objectName: string): void { super.setObjectName(objectName); if (this._rawInlineStyle) { this.setInlineStyle(this._rawInlineStyle); } this.repolish(); } // TODO: void setPalette(const QPalette &) // TODO: void setParent(QWidget *parent) // TODO: void setParent(QWidget *parent, Qt::WindowFlags f) setShortcutAutoRepeat(id: number, enable = true): void { this.native.setShortcutAutoRepeat(id, enable); } setShortcutEnabled(id: number, enable = true): void { this.native.setShortcutEnabled(id, enable); } setSizeIncrement(w_or_size: QSize | number, h = 0): void { if (typeof w_or_size === 'number') { this.native.setSizeIncrement(w_or_size, h); } else { this.setProperty('sizeIncrement', w_or_size.native); } } // TODO: void setSizePolicy(QSizePolicy) setSizePolicy(horizontal: QSizePolicyPolicy, vertical: QSizePolicyPolicy): void { this.native.setSizePolicy(horizontal, vertical); } setStatusTip(statusTip: string): void { this.setProperty('statusTip', statusTip); } // TODO: void setStyle(QStyle *style) setTabletTracking(enable: boolean): void { this.setProperty('tabletTracking', enable); } setToolTip(text: string): void { this.native.setProperty('toolTip', text); } setToolTipDuration(msec: number): void { this.setProperty('toolTipDuration', msec); } setUpdatesEnabled(enable: boolean): void { this.native.setProperty('updatesEnabled', enable); } setWhatsThis(whatsThis: string): void { this.setProperty('whatsThis', whatsThis); } setWindowFilePath(filePath: string): void { this.setProperty('windowFilePath', filePath); } setWindowFlag(windowType: WindowType, switchOn: boolean): void { // react:⛔️ return this.native.setWindowFlag(windowType, switchOn); } // PROP: QWidget // TODO: void setWindowFlags(Qt::WindowFlags type) setWindowIcon(icon: QIcon): void { this.native.setWindowIcon(icon.native); } // PROP: QWidget // TODO: void setWindowModality(Qt::WindowModality windowModality) setWindowOpacity(opacity: number): void { this.native.setWindowOpacity(opacity); } setWindowRole(role: string): void { this.native.setWindowRole(role); } setWindowState(state: WindowState): void { return this.native.setWindowState(state); } size(): QSize { return new QSize(this.native.size()); } sizeHint(): QSize { return QSize.fromQVariant(this.property('sizeHint')); } sizeIncrement(): QSize { return QSize.fromQVariant(this.property('sizeIncrement')); } // PROP: QWidget // TODO: QSizePolicy sizePolicy() const // TODO: void stackUnder(QWidget *w) statusTip(): string { return this.property('statusTip').toString(); } style(): QStyle { return new QStyle(this.native.style()); } styleSheet(): string { return this.native.styleSheet(); } testAttribute(attribute: WidgetAttribute): boolean { // react:⛔️ return this.native.testAttribute(attribute); } toolTip(): string { return this.property('toolTip').toString(); } toolTipDuration(): number { return this.property('toolTipDuration').toInt(); } // TODO: void ungrabGesture(Qt::GestureType gesture) underMouse(): boolean { return this.native.underMouse(); } unsetCursor(): void { this.native.unsetCursor(); } unsetLayoutDirection(): void { this.native.unsetLayoutDirection(); } unsetLocale(): void { this.native.unsetLocale(); } // TODO: void update(int x, int y, int w, int h) // TODO: void update(const QRect &rect) // TODO: void update(const QRegion &rgn) updateGeometry(): void { // react:⛔️ this.native.updateGeometry(); } updatesEnabled(): boolean { return this.property('updatesEnabled').toBool(); } // TODO: QRegion visibleRegion() const whatsThis(): string { return this.property('whatsThis').toString(); } width(): number { return this.property('width').toInt(); } // TODO: WId winId() const // TODO: QWidget * window() const windowFilePath(): string { return this.property('windowFilePath').toString(); } // PROP: QWidget // TODO: Qt::WindowFlags windowFlags() const windowHandle(): QWindow | null { const handle = this.native.windowHandle(); if (handle != null) { return wrapperCache.get<QWindow>(QWindow, handle); } return null; } windowIcon(): QIcon { return QIcon.fromQVariant(this.property('windowIcon')); } // PROP: QWidget // TODO: Qt::WindowModality windowModality() const windowOpacity(): number { return this.native.windowOpacity(); } windowRole(): string { return this.native.windowRole(); } windowState(): number { return this.native.windowState(); } windowTitle(): string { return this.native.windowTitle(); } // TODO: Qt::WindowType windowType() const x(): number { return this.property('x').toInt(); } y(): number { return this.property('y').toInt(); } // *** Public Slots *** close(): boolean { return this.native.close(); } hide(): void { this.native.hide(); } lower(): void { this.native.lower(); } raise(): void { this.native.raise(); } repaint(): void { // react:⛔️ this.native.repaint(); } setDisabled(disable: boolean): void { this.setEnabled(!disable); } setEnabled(enabled: boolean): void { this.setProperty('enabled', enabled); } setFocus(reason = FocusReason.OtherFocusReason): void { this.native.setFocus(reason); } setHidden(hidden: boolean): void { this.native.setHidden(hidden); } setStyleSheet(styleSheet: string): void { const preparedSheet = StyleSheet.create(styleSheet); this.native.setStyleSheet(preparedSheet); } setVisible(visible: boolean): void { this.native.setVisible(visible); } setWindowModified(modified: boolean): void { this.native.setWindowModified(modified); } setWindowTitle(title: string): void { return this.native.setWindowTitle(title); } show(): void { this.native.show(); } showFullScreen(): void { this.native.showFullScreen(); } showMaximized(): void { this.native.showMaximized(); } showMinimized(): void { this.native.showMinimized(); } showNormal(): void { this.native.showNormal(); } update(): void { // react:⛔️ this.native.update(); } } export interface QWidgetSignals extends QObjectSignals { windowTitleChanged: (title: string) => void; windowIconChanged: (iconNative: NativeElement) => void; customContextMenuRequested: (pos: { x: number; y: number }) => void; } /** > Create and control views. * **This class is a JS wrapper around Qt's [QWidget class](https://doc.qt.io/qt-5/qwidget.html)** A `QWidget` can be used to encapsulate other widgets and provide structure. It functions similar to a `div` in the web world. ### Example ```javascript const { QWidget } = require("@nodegui/nodegui"); const view = new QWidget(); view.setObjectName("container"); //Similar to setting `id` on the web view.setLayout(new FlexLayout()); ``` */ export class QWidget extends NodeWidget<QWidgetSignals> { native: NativeElement; constructor(arg?: NodeWidget<QWidgetSignals> | NativeElement) { let native; let parent; if (checkIfNativeElement(arg)) { native = arg as NativeElement; } else if (arg as NodeWidget<QWidgetSignals>) { parent = arg as NodeWidget<QWidgetSignals>; native = new addon.QWidget(parent.native); } else { native = new addon.QWidget(); } super(native); this.setNodeParent(parent); this.native = native; } }
the_stack
import { fireEvent, render, screen, waitForElementToBeRemoved } from 'src/utils/test-utils' import Field from '../forms/Field' import TextField from '../forms/TextField' import StepperForm, { StepFormElement } from './StepperForm' describe('<StepperForm>', () => { it('Renders StepperForm component', () => { const onSubmitSpy = jest.fn() const stepOneValidationsSpy = jest.fn() const finalStepValidationsSpy = jest.fn() const { container } = render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) const formNode = container.querySelector('form') expect(formNode).toBeInTheDocument() expect(screen.getByTestId('stepper-form-test')).toBeInTheDocument() }) it('Initial values in the form', () => { const onSubmitSpy = jest.fn() const stepOneValidationsSpy = jest.fn() const finalStepValidationsSpy = jest.fn() const initialValues = { stepOneTextfield: 'initial value of stepOneTextfield', stepTwoTextfield: 'initial value of stepTwoTextfield', } render( <StepperForm initialValues={initialValues} onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) const stepOneInputNode = screen.getByTestId('stepOneTextfield-field') as HTMLInputElement expect(stepOneInputNode).toBeInTheDocument() expect(stepOneInputNode.value).toBe('initial value of stepOneTextfield') }) it('renders <StepFormElement>', () => { render( <StepFormElement label={'Step form label'}> <div>Step form content</div> </StepFormElement>, ) expect(screen.getByText('Step form content')).toBeInTheDocument() }) describe('Form navigation', () => { it('Renders next form step when clicks on next button', async () => { const onSubmitSpy = jest.fn() const stepOneValidationsSpy = jest.fn() const finalStepValidationsSpy = jest.fn() render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) // Form Step 1 const formStepOneNode = screen.getByText('Step 1 content') expect(formStepOneNode).toBeInTheDocument() const stepOneInputNode = screen.getByTestId('stepOneTextfield-field') expect(stepOneInputNode).toBeInTheDocument() // Form Step 2 fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content')) const formStepTwoNode = screen.getByText('Step 2 content') expect(formStepTwoNode).toBeInTheDocument() const stepTwoInputNode = screen.getByTestId('stepTwoTextfield-field') expect(stepTwoInputNode).toBeInTheDocument() // Final Form Step fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content')) const finalFormStepNode = screen.getByText('Final step label') expect(finalFormStepNode).toBeInTheDocument() }) }) describe('Form validations', () => { it('Triggers validations when clicks on next button', async () => { const onSubmitSpy = jest.fn() const stepOneValidationsSpy = jest.fn() const finalStepValidationsSpy = jest.fn() render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) fireEvent.click(screen.getByText('Next')) expect(stepOneValidationsSpy).toHaveBeenCalled() expect(finalStepValidationsSpy).not.toHaveBeenCalled() await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content')) expect(finalStepValidationsSpy).not.toHaveBeenCalled() fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content')) expect(finalStepValidationsSpy).toHaveBeenCalled() }) it('If errors are present in the form you can not go to the next step', () => { const onSubmitSpy = jest.fn() const stepOneValidationsWithErrorsSpy = jest.fn(() => ({ stepOneTextfield: 'this field has an error', })) const finalStepValidationsSpy = jest.fn() render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsWithErrorsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) // we try to go next fireEvent.click(screen.getByText('Next')) expect(stepOneValidationsWithErrorsSpy).toHaveBeenCalled() expect(screen.queryByText('Step 2 content')).not.toBeInTheDocument() }) it('Shows the form errors', () => { const onSubmitSpy = jest.fn() const stepOneValidationsWithErrorsSpy = jest.fn(() => ({ stepOneTextfield: 'this field has an error', })) const finalStepValidationsSpy = jest.fn() render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsWithErrorsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) // we try to go next fireEvent.click(screen.getByText('Next')) expect(screen.queryByText('this field has an error')).toBeInTheDocument() }) }) it('Performs onSubmit in the final form step', async () => { const onSubmitSpy = jest.fn() const stepOneValidations = jest.fn() const finalStepValidationsSpy = jest.fn() render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidations}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) // we go to the final step fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content')) fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content')) expect(onSubmitSpy).not.toHaveBeenCalled() fireEvent.click(screen.getByText('Next')) expect(onSubmitSpy).toHaveBeenCalled() }) it('If errors are present, the form is not Submitted', async () => { const onSubmitSpy = jest.fn() const stepOneValidationsSpy = jest.fn() const finalStepValidationsWithErrorsSpy = jest.fn(() => ({ error: 'this a final step error', })) render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement label={'Step 1 label'} validate={stepOneValidationsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsWithErrorsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) // we go to the final step fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content')) fireEvent.click(screen.getByText('Next')) await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content')) expect(onSubmitSpy).not.toHaveBeenCalled() fireEvent.click(screen.getByText('Next')) expect(onSubmitSpy).not.toHaveBeenCalled() }) it('Disables Next step button', () => { const onSubmitSpy = jest.fn() const stepOneValidationsSpy = jest.fn() const finalStepValidationsSpy = jest.fn() const { container } = render( <StepperForm onSubmit={onSubmitSpy} testId={'stepper-form-test'}> <StepFormElement disableNextButton label={'Step 1 label'} validate={stepOneValidationsSpy}> <div> <div>Step 1 content</div> <Field component={TextField} name={'stepOneTextfield'} type="text" testId="stepOneTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Step 2 label'}> <div> <div>Step 2 content</div> <Field component={TextField} name={'stepTwoTextfield'} type="text" testId="stepTwoTextfield-field" /> </div> </StepFormElement> <StepFormElement label={'Final step label'} validate={finalStepValidationsSpy}> <div>Final step content</div> </StepFormElement> </StepperForm>, ) // Next button disabled expect(container.querySelector('button[type=submit]')).toBeDisabled() // Back button NOT disabled expect(container.querySelector('button[type=button]')).not.toBeDisabled() // stay at Step 1 even if we click on the disabled Next button fireEvent.click(screen.getByText('Next')) expect(screen.getByText('Step 1 content')).toBeInTheDocument() expect(screen.queryByText('Step 2 content')).not.toBeInTheDocument() }) })
the_stack
* 讯飞错误代码 * * @export * @interface IResponseMessage */ export interface IResponseCode { /** * 错误代码 * * @type {string} * @memberof IResponseCode */ Code: string; /** * 描述(中文) * * @type {string} * @memberof IResponseCode */ DescriptionCN: string; /** * 描述(英文) * * @type {string} * @memberof IResponseCode */ DescriptionEN: string; /** * 可能的解决方案 * * @type {(string | undefined)} * @memberof IResponseCode */ Resolve: string | undefined; } /** * 讯飞的WebAPI通用返回接口 * * @export * @interface ICommonResponseBody */ export interface ICommonResponseBody { /** * 返回结果码 * * @type {string} * @memberof ICommonResponseBody */ code?: string; /** * 返回数据,根据不同的接口其具体结构不同 * * @type {string | IISECompleteResult | IISEPlainResult} * @memberof ICommonResponseBody */ data?: string | IISECompleteResult | IISEPlainResult; /** * 描述 * * @type {string} * @memberof ICommonResponseBody */ desc?: string; /** * 回话ID * * @type {string} * @memberof ICommonResponseBody */ sid?: string; } /** * TTS引擎请求成功时的返回 * * @export * @interface ITTSResponseBody */ export interface ITTSResponseBody extends ICommonResponseBody { /** * 音频数据 * * @type {*} * @memberof ITTSResponseBody */ audio?: Buffer; } export declare const ResponseCodes: IResponseCode[]; /** * 句子评测的精简结果 * @export * @interface IISEPlainResult */ export interface IISEPlainResult { /** * 0 则正常 * @type {IValue} * @memberof IISEPlainResult */ ret?: IValue; /** * 总分 * @type {IValue} * @memberof IISEPlainResult */ total_score?: IValue; } /** * 评测详细结果。 data里的总数据 * * @export * @interface IISECompleteResult */ export interface IISECompleteResult { /** * 句子 * * @type {IISEResultMain} * @memberof IISECompleteResult */ read_sentence?: IISEResultMain; /** * 章节 * * @type {IISEResultMain} * @memberof IISECompleteResult */ read_chapter?: IISEResultMain; /** * 单词 * * @type {IISEResultMain} * @memberof IISECompleteResult */ read_word?: IISEResultMain; /** * 单字 * * @type {IISEResultMain} * @memberof IISECompleteResult */ read_syllable?: IISEResultMain; } /** * 哎。。。。都对讯飞这该死的返回结构无语了。。。。太特么扯淡了 * * @export * @interface IISEResultMain */ export interface IISEResultMain { /** * 语言 * * @type {string} * @memberof IReadSentenceResult */ lan?: string; /** * 类型 * * @type {string} * @memberof IReadSentenceResult */ type?: string; /** * 引擎版本 * * @type {string} * @memberof IReadSentenceResult */ version?: string; /** * 评测结果 * * @type {IRecPaper} * @memberof IReadSentenceResult */ rec_paper?: IRecPaper; /** * 我也不知道这干毛线用的,反正讯飞文档里面没有写,但是某些时候会出现。 * * @type {IRecPaper} * @memberof IReadSentenceResult */ rec_tree?: IRecPaper; } /** * 评测结果 * * @export * @interface IRecPaper */ export interface IRecPaper { /** * 单字朗读评测,汉语专有 * * @type {IISEResultSummary} * @memberof IRecPaper */ read_syllable?: IISEResultSummary; /** * 句子朗读评测 * * @type {IISEResultSummary} * @memberof IRecPaper */ read_sentence?: IISEResultSummary; /** * 章节朗读评测。 * 但是,注意!!!!!!!!!! * 不知道为毛线讯飞在评测英语的句子的时候是用这个结构返回的数据!!!!!! * @type {IISEResultSummary} * @memberof IRecPaper */ read_chapter?: IISEResultSummary; /** * 单词朗读评测 * * @type {IISEResultSummary} * @memberof IRecPaper */ read_word?: IISEResultSummary; } /** * 通用数据 * * @export * @interface IISECommonSection */ export interface IISECommonSection { /** * 开始时间(帧,每帧10ms) * * @type {string} * @memberof IISECommonSection */ beg_pos?: string; /** * 截止时间(帧,每帧10ms) * * @type {string} * @memberof IISECommonSection */ end_pos?: string; /** * 内容 * * @type {string} * @memberof IISECommonSection */ content?: string; /** * 时间长度(帧,每帧10ms) * * @type {string} * @memberof IISECommonSection */ time_len?: string; } /** * 评测结果总览 * * @export * @interface IISEResultSummary * @extends {IISECommonSection} */ export interface IISEResultSummary extends IISECommonSection { /** * 总分 * * @type {string} * @memberof IISEResultSummary */ total_score?: string; /** * 声韵分(需开通多维度评分权限) * * @type {string} * @memberof IISEResultSummary */ phone_score?: string; /** * 流畅度(需开通多维度评分权限) * * @type {string} * @memberof IISEResultSummary */ fluency_score?: string; /** * 调型分(需开通多维度评分权限) * * @type {string} * @memberof IISEResultSummary */ tone_score?: string; /** * 完整度分(需开通多维度评分权限) * * @type {string} * @memberof IISEResultSummary */ integrity_score?: string; /** * 异常信息 * * @type {EXCEPT_INFO} * @memberof IISEResultSummary */ except_info?: EXCEPT_INFO; /** * 是否被拒 * * @type {string} * @memberof IISEResultSummary */ is_rejected?: string; sentence?: ISentence | ISentence[]; /** * 全部单词数量 * * @type {string} * @memberof IISEResultSummary */ word_count?: string; /** * 准确度评分(需开通多维度评测权限) * * @type {string} * @memberof IISEResultSummary */ accuracy_score?: string; /** * 标准度评分,评测发音是否地道(预留分暂不生效) * * @type {string} * @memberof IISEResultSummary */ standard_score?: string; } /** * 句子 * * @export * @interface ISentence * @extends {IISECommonSection} */ export interface ISentence extends IISECommonSection { /** * 总分 * * @type {string} * @memberof ISentence */ total_score?: string; /** * 声韵分(需开通多维度评分权限) * * @type {string} * @memberof ISentence */ phone_score?: string; /** * 流畅度分(需开通多维度评分权限) * * @type {string} * @memberof ISentence */ fluency_score?: string; /** * 调型分(需开通多维度权限) * * @type {string} * @memberof ISentence */ tone_score?: string; /** * 单词 * * @type {(IWord[] | IWord)} * @memberof ISentence */ word?: IWord[] | IWord; /** * 句子索引 * * @type {string} * @memberof ISentence */ index?: string; /** * 准确度评分(需开通多维度评分权限) * * @type {string} * @memberof ISentence */ accuracy_score?: string; /** * 标准度评分,评测发音是否地道(预留字段暂不生效) * * @type {string} * @memberof ISentence */ standard_score?: string; /** * 句子中单词数量 * * @type {string} * @memberof ISentence */ word_count?: string; } /** * 单词 * * @export * @interface IWord * @extends {IISECommonSection} */ export interface IWord extends IISECommonSection { /** * 拼音:数字代表声调,5和5以上表示轻声 * * @type {string} * @memberof IWord */ symbol?: string; /** * 单词在全篇章中的索引 * * @type {string} * @memberof IWord */ global_index?: string; /** * 单词在句子里的索引 * * @type {string} * @memberof IWord */ index?: string; /** * 单词属性(半句,重读,关键字等) * * @type {string} * @memberof IWord */ property?: string; syll?: ISyll[] | ISyll; /** * 单词总分 * * @type {string} * @memberof IWord */ total_score?: string; } /** * 音节,单词发音的组成部分。对于汉语,一个音节对应一个字的发音。 * * @export * @interface ISyll * @extends {IISECommonSection} */ export interface ISyll extends IISECommonSection { /** * 拼音:数字代表声调,5和5以上表示轻声 * * @type {string} * @memberof ISyll */ symbol?: string; /** * paper(试卷内容),sil(非试卷内容) * * @type {string} * @memberof ISyll */ rec_node_type?: string; /** * 增漏读信息 * * @type {DP_MESSAGE} * @memberof ISyll */ dp_message?: DP_MESSAGE; /** * 音素 * * @type {(IPhone[] | IPhone)} * @memberof ISyll */ phone?: IPhone[] | IPhone; /** * 音节重读标记 * * @type {string} * @memberof ISyll */ syll_accent?: string; /** * 音节得分 * * @type {string} * @memberof ISyll */ syll_score: string; } /** * 音素,基本发音单元,音节的组成部分 * * @export * @interface IPhone * @extends {IISECommonSection} */ export interface IPhone extends IISECommonSection { /** * 增漏读信息 * * @type {DP_MESSAGE} * @memberof IPhone */ dp_message?: DP_MESSAGE; /** * paper(试卷内容),sil(非试卷内容) * * @type {string} * @memberof IPhone */ rec_node_type?: string; /** * 是否是韵母 * * @type {string} * @memberof IPhone */ is_yun?: string; /** * 文本调型信息:TONE1(一声) TONE2(二声) TONE3(三声) TONE4(四声) * * @type {string} * @memberof IPhone */ mono_tone?: string; } export interface IValue { value: string; } /** * 增漏读说明 * * @export * @enum {number} */ export declare enum DP_MESSAGE { /** * 引擎认为该单元读了,但是不一定朗读正确 */ Normal = "0", /** * 漏读,该单元没有读 */ Miss = "16", /** * 增读,该单元是多度的文本内的内容 */ Extra = "32", /** * 回读,该单元是重复读的相邻文本的内容 */ Repeat = "64", /** * 替换,该单元读成了文本内其他的内容 */ Replace = "128", } /** * 异常信息 * * @export * @enum {number} */ export declare enum EXCEPT_INFO { /** * 无异常 */ Normal = "0", /** * 无语音输入或者音量太小 */ VolumeOutOfRange = "28673", /** * 检测到语音为乱说类型 */ Nonsense = "28676", /** * 音频的信噪比太低 */ LowSignalNoseRatio = "28680", /** * 音频数据出现截幅 */ AmpTruncated = "28690", }
the_stack
import React, {useState, useContext, useEffect} from "react"; import {Modal, Table} from "antd"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {faPencilAlt, faFileExport, faTrashAlt, faTimes} from "@fortawesome/free-solid-svg-icons"; import {UserContext} from "../../../../util/user-context"; import {queryDateConverter} from "../../../../util/date-conversion"; import EditQueryDialog from "../edit-query-dialog/edit-query-dialog"; import {SearchContext} from "../../../../util/search-context"; import styles from "./manage-query.module.scss"; import {fetchQueries, removeQuery} from "../../../../api/queries"; import axios from "axios"; import {getSavedQueryPreview} from "../../../../api/queries"; import ExportQueryModal from "../../../query-export/query-export-modal/query-export-modal"; import {getExportPreview} from "../../../query-export/export-preview/export-preview"; import {QueryOptions} from "../../../../types/query-types"; import {useHistory, useLocation} from "react-router-dom"; const QueryModal = (props) => { const { applySaveQuery, searchOptions, clearAllGreyFacets, setSavedQueries } = useContext(SearchContext); const {handleError} = useContext(UserContext); const [editModalVisibility, setEditModalVisibility] = useState(false); const [deleteModalVisibility, setDeleteModalVisibility] = useState(false); const [exportModalVisibility, setExportModalVisibility] = useState(false); const [recordID, setRecordID] = useState(); const [tableColumns, setTableColumns] = useState<Object[]>(); const [tableData, setTableData] = useState<Object[]>(); const [query, setQuery] = useState({}); const [hasStructured, setStructured] = useState<boolean>(false); const [data, setData] = useState<any[]>([]); const [queries, setQueries] = useState<any>([]); const [currentQueryDescription, setCurrentQueryDescription] = useState(""); const [currentQueryName, setCurrentQueryName] = useState(""); const history: any = useHistory(); const location: any = useLocation(); useEffect(() => { getQueries(); }, []); useEffect(() => { updateTableData(); }, [queries]); const getQueries = async () => { try { const response = await fetchQueries(); if (response["data"]) { setQueries(response["data"]); setSavedQueries(response["data"]); } } catch (error) { handleError(error); } }; const editQuery = async (query) => { const response = await axios.put(`/api/entitySearch/savedQueries`, query); if (response.data) { setQueries(response.data); setSavedQueries(response.data); return {code: response.status}; } }; const deleteQuery = async (query) => { try { await removeQuery(query); } catch (error) { handleError(error); } getQueries(); }; const onEdit = () => { setEditModalVisibility(true); }; const onDelete = (row) => { setCurrentQueryName(row.name); setCurrentQueryDescription(row.description); setDeleteModalVisibility(true); }; const onClose = () => { props.setManageQueryModal(false); }; const onOk = (query) => { deleteQuery(query); setDeleteModalVisibility(false); clearAllGreyFacets(); let options: QueryOptions = { searchText: "", entityTypeIds: searchOptions.entityTypeIds, selectedFacets: {}, selectedQuery: "select a query", propertiesToDisplay: [], zeroState: searchOptions.zeroState, sortOrder: [], database: searchOptions.database, }; applySaveQuery(options); setCurrentQueryDescription(""); }; const onCancel = () => { setDeleteModalVisibility(false); }; const onApply = (e) => { if (location && location.hasOwnProperty("pathname") && location.pathname === "/tiles/explore/detail") { queries && queries.length > 0 && queries.forEach(query => { if (e.currentTarget.dataset.id === query["savedQuery"]["name"]) { history.push({ pathname: "/tiles/explore", state: { savedQuery: query["savedQuery"] } }); } }); } else { queries && queries.length > 0 && queries.forEach(query => { if (e.currentTarget.dataset.id === query["savedQuery"]["name"]) { let options: QueryOptions = { searchText: query["savedQuery"]["query"]["searchText"], entityTypeIds: query["savedQuery"]["query"]["entityTypeIds"], selectedFacets: query["savedQuery"]["query"]["selectedFacets"], selectedQuery: query["savedQuery"]["name"], propertiesToDisplay: query.savedQuery.propertiesToDisplay, zeroState: false, sortOrder: query.savedQuery.sortOrder, database: searchOptions.database, }; applySaveQuery(options); setCurrentQueryDescription(query["savedQuery"]["description"]); } }); } props.setManageQueryModal(false); }; const displayExportModal = (id) => { setRecordID(id); let query; queries.forEach((selectedQuery) => { if (selectedQuery["savedQuery"]["id"] === id) { query = selectedQuery; } }); let arrayProperties : any[] = []; props.entityDefArray && props.entityDefArray.forEach(entity => { if (entity.name === query.savedQuery.query.entityTypeIds[0]) { entity.properties && entity.properties.forEach(prop => { if (prop.ref.length === 0 && prop.datatype === "array") { arrayProperties.push(prop.name); } }); } }); let hasArray = query.savedQuery.propertiesToDisplay.length > 0 && arrayProperties.length > 0 && query.savedQuery.propertiesToDisplay.some((prop => arrayProperties.includes(prop))); let isStructured = query && query.savedQuery.propertiesToDisplay && query.savedQuery.propertiesToDisplay.some(column => column.includes(".")); setStructured(hasArray || isStructured); (hasArray || isStructured) && getPreview(id); setExportModalVisibility(true); }; const columns: any = [ { title: "Name", dataIndex: "name", key: "name", sorter: (a, b) => a.name.localeCompare(b.name), width: 200, sortDirections: ["ascend", "descend", "ascend"], defaultSortOrder: "ascend", render: text => <a data-id={text} data-testid={text} className={styles.name} onClick={onApply}>{text}</a>, }, { title: "Description", dataIndex: "description", key: "description", sorter: (a, b) => a.name.localeCompare(b.name), sortDirections: ["ascend", "descend", "ascend"], width: 200, render: text => <div className={styles.cell}>{text}</div>, }, { title: "Edited", dataIndex: "edited", key: "edited", sortDirections: ["ascend", "descend", "ascend"], sorter: (a, b) => a.edited.localeCompare(b.edited), width: 200, render: text => <div className={styles.cell}>{text}</div>, } ]; const editObj = { title: "Edit", dataIndex: "edit", key: "edit", align: "center" as "center", render: text => <a data-testid={"edit"} onClick={onEdit}>{text}</a>, width: 75 }; // TODO: Uncomment once link for query is implemented // const linkObj = { // title: 'Link', // dataIndex: 'link', // key: 'link', // align: 'center' as 'center', // width: 75, // render: text => <a data-testid={'link'}>{text}</a> // }; const deleteObj = { title: "Delete", dataIndex: "delete", key: "delete", align: "center" as "center", render: (text, row) => <a data-testid={"delete"} onClick={() => onDelete(row)}>{text}</a>, width: 75 }; const exportObj = { title: "Export", dataIndex: "export", key: "export", align: "center" as "center", render: text => <a data-testid={"export"} >{text}</a>, onCell: record => { return { onClick: () => { displayExportModal(record.key); } }; }, width: 75 }; if (props.isSavedQueryUser) { columns.push(editObj); } if (props.canExportQuery) { columns.push(exportObj); } if (props.isSavedQueryUser) { // TODO: Uncomment once link for query is implemented // columns.push(linkObj); columns.push(deleteObj); } const updateTableData = () => { let data : any[] = []; queries && queries.length > 0 && queries.forEach(query => { data.push( { key: query["savedQuery"]["id"], name: query["savedQuery"]["name"], description: query["savedQuery"]["description"], edited: queryDateConverter(query["savedQuery"]["systemMetadata"]["lastUpdatedDateTime"]), edit: <FontAwesomeIcon icon={faPencilAlt} color="#5B69AF" size="lg" className={styles.manageQueryIconsHover}/>, export: <FontAwesomeIcon icon={faFileExport} color="#5B69AF" size="lg" className={styles.manageQueryIconsHover}/>, // TODO: Uncomment once link for query is implemented // link: <FontAwesomeIcon icon={faLink} color='#5B69AF' size='lg' />, delete: <FontAwesomeIcon icon={faTrashAlt} color="#B32424" size="lg" className={styles.manageQueryIconsHover}/> } ); }); setData(data); }; const deleteConfirmation = <Modal visible={deleteModalVisibility} okText="Yes" cancelText="No" onOk={() => onOk(query)} onCancel={() => onCancel()} width={400} maskClosable={false} > <span style={{fontSize: "16px", position: "relative", top: "10px"}} data-testid="deleteConfirmationText"> Are you sure you would like to delete the <b>{currentQueryName}</b> query? This action cannot be undone. </span> </Modal>; const getPreview = async (id) => { try { const response = await getSavedQueryPreview(id, searchOptions.database); if (response.data) { const preview = getExportPreview(response.data); const header = preview[0]; const body = preview[1]; setTableColumns(header); setTableData(body); } else { setTableColumns([]); setTableData([]); } } catch (error) { handleError(error); } }; return ( <div> <ExportQueryModal hasStructured={hasStructured} queries={queries} tableColumns={tableColumns} tableData={tableData} recordID={recordID} exportModalVisibility={exportModalVisibility} setExportModalVisibility={setExportModalVisibility} /> <Modal title={null} visible={props.modalVisibility} onCancel={onClose} width={1000} footer={null} maskClosable={false} closeIcon={<FontAwesomeIcon icon={faTimes} className={"manage-modal-close-icon"} />} destroyOnClose={true} > <p className={styles.title} data-testid="manage-queries-modal">{"Manage Queries"}</p> <Table columns={columns} dataSource={data} onRow={(record) => { return { onClick: () => { queries.forEach((query) => { if (query["savedQuery"]["id"] === record.key) { setQuery(query); setCurrentQueryName(record.name); } }); } }; }} > </Table> </Modal> <EditQueryDialog currentQueryName={currentQueryName} setCurrentQueryName={setCurrentQueryName} currentQueryDescription={currentQueryDescription} setCurrentQueryDescription={setCurrentQueryDescription} query={query} editQuery={editQuery} getQueries={getQueries} editModalVisibility={editModalVisibility} setEditModalVisibility={setEditModalVisibility} /> {deleteConfirmation} </div> ); }; export default QueryModal;
the_stack
import React, { useState, useEffect } from 'react'; import { message, Form, Input, Icon, Button, Select, Transfer, Upload, Divider, Modal, Tag, Tooltip, } from 'antd'; import { UploadProps } from 'antd/lib/upload/interface'; import { FormComponentProps } from 'antd/lib/form'; import { useDispatch, useSelector, useStore } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { History } from 'history'; import { Article, Meta, randHex } from '@tuture/core'; import { CollectionStep } from '@tuture/local-server'; /** @jsx jsx */ import { css, jsx } from '@emotion/core'; import { EDIT_ARTICLE } from 'utils/constants'; import { IMAGE_HOSTING_URL } from 'utils/image'; import { RootState, Store, Dispatch } from 'store'; const { Option } = Select; const { confirm } = Modal; function showDeleteConfirm( name: string, dispatch: Dispatch, articleId: string, nowArticleId: string, history: History, ) { confirm({ title: `确定要删除 ${name}`, okText: '确定', okType: 'danger', cancelText: '取消', onOk() { dispatch.drawer.setChildrenVisible(false); // If nowEditArticle is nowSelectedArticle, then need re-select nowArticle // and jump to the first article or collection page if (articleId === nowArticleId) { dispatch.collection.setNowArticle(''); history.push('/'); } dispatch.collection.deleteArticle(articleId); }, }); } type CreateEditArticleValueType = { cover: UploadProps; name: string; topics: string[]; steps: string[]; categories: string[]; }; interface CreateEditArticleProps extends FormComponentProps<CreateEditArticleValueType> { childrenDrawerType: string; } function CreateEditArticle(props: CreateEditArticleProps) { const store = useStore() as Store; const dispatch = useDispatch<Dispatch>(); const [selectedKeys, setSelectedKeys] = useState<string[]>([]); const [collectionSteps, setCollectionSteps] = useState<CollectionStep[]>([]); // get router history && first article id for delete jump const history = useHistory(); // get editArticle Commits const { editArticleId, nowArticleId } = useSelector( (state: RootState) => state.collection, ); const [initialTargetKeys, setInitialTargetKeys] = useState<string[]>([]); const [targetKeys, setTargetKeys] = useState<string[]>([]); useEffect(() => { fetch('/api/collection-steps') .then((res) => res.json()) .then((data) => { setCollectionSteps(data); // set TargetKeys const targetKeys = props.childrenDrawerType === EDIT_ARTICLE ? (data as CollectionStep[]) .filter((step) => step.articleId === editArticleId) .map((step) => step.key) : []; setTargetKeys(targetKeys); setInitialTargetKeys(targetKeys); }); }, [editArticleId, props.childrenDrawerType]); // get nowArticle Meta const meta: Meta = useSelector( store.select.collection.getArticleMetaById({ id: editArticleId }), ); const articleMeta: Partial<Meta> = props.childrenDrawerType === EDIT_ARTICLE ? meta : {}; const initialTopics = articleMeta?.topics || []; const initialCategories = articleMeta?.categories || []; const initialCover = articleMeta?.cover ? [ { url: articleMeta?.cover, uid: '-1', name: articleMeta?.cover.split('/').slice(-1)[0], status: 'done', }, ] : []; const initialName = articleMeta?.name || ''; const coverProps: Partial<UploadProps> = { action: IMAGE_HOSTING_URL, listType: 'picture', defaultFileList: [], }; const [fileList, setFileList] = useState(initialCover); const { getFieldDecorator, setFieldsValue, getFieldValue } = props.form; function handleSubmit(e: React.FormEvent) { e.preventDefault(); props.form.validateFields((err, values) => { if (!err) { const { cover, name, topics, steps, categories } = values; const article = { name } as Article; if (topics) { article.topics = topics; } if (categories) { article.categories = categories; } if (cover) { let url = Array.isArray(cover?.fileList) && cover?.fileList.length > 0 ? cover?.fileList[0].url || cover?.fileList[0].response.data : ''; if (!url && Array.isArray(cover) && cover.length > 0) { url = cover[0].url; } article.cover = url; } if (props.childrenDrawerType === EDIT_ARTICLE) { dispatch.collection.editArticle(article); let newlyAddedStepsId: string[] = []; // If released, set articleId null collectionSteps.forEach((step, index) => { if (initialTargetKeys.includes(String(index)) && !step.articleId) { // Remove this step from currently edited article. dispatch.collection.setStepById({ stepId: step.id, stepProps: { articleId: null }, }); } if ( steps.includes(String(index)) && !initialTargetKeys.includes(String(index)) ) { // if newly steps newlyAddedStepsId.push(step.id); } }); dispatch.collection.save({ keys: ['articles', 'fragment'] }); // If exists newly addSteps, then update collection if (newlyAddedStepsId.length > 0) { dispatch.collection.updateSteps({ articleId: editArticleId as string, updatedStepsId: newlyAddedStepsId, }); } message.success('保存成功'); } else { // Create new article. article.id = randHex(8); // Update articleId field for selected steps. const updatedStepsId: string[] = []; collectionSteps.forEach((step, index) => { if (steps.includes(String(index))) { updatedStepsId.push(step.id); } }); dispatch.collection.createArticle(article); dispatch.collection.save({ keys: ['articles'] }); dispatch.collection.updateSteps({ articleId: article.id, updatedStepsId, }); history.push(`/articles/${article.id}`); } dispatch.drawer.setChildrenVisible(false); dispatch.drawer.setVisible(false); } }); } function handleTargetChange(nextTargetKeys: string[]) { const sortedNextTargetKeys: string[] = nextTargetKeys.sort((prev, post) => { if (prev > post) { return 1; } if (prev < post) { return -1; } return 0; }); // check nowTargetKeys status const newCollectionSteps = collectionSteps.map((step) => { if (targetKeys.includes(step.key) && !nextTargetKeys.includes(step.key)) { return { ...step, articleId: '', articleIndex: 0, articleName: '' }; } return step; }); setCollectionSteps(newCollectionSteps); setTargetKeys(sortedNextTargetKeys); } function handleSelectChange( sourceSelectedKeys: string[], targetSelectedKeys: string[], ) { setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]); } function filterOption(inputValue: string, option: any) { return option.description.indexOf(inputValue) > -1; } function handleCoverChange({ fileList }: any) { let resultFileList = [...fileList]; // 1. Limit the number of uploaded files // Only to show two recent uploaded files, and old ones will be replaced by the new resultFileList = resultFileList.slice(-1); // 2. Read from response and show file link resultFileList = resultFileList.map((file) => { if (file.response) { // Component will show file.url as link file.url = file.response.url; } return file; }); setFileList(resultFileList); setFieldsValue({ cover: resultFileList }); } function handleTopicsChange(topics: string) { setFieldsValue({ topics }); } function handleCategoriesChange(categories: string) { setFieldsValue({ categories }); } return ( <div css={css` width: 100%; padding: 0 24px; & img { margin: 0; } `} > <Form layout="vertical" onSubmit={handleSubmit}> <Form.Item label="封面" css={css` width: 100%; `} > {getFieldDecorator('cover', { initialValue: initialCover, })( <Upload fileList={fileList as any[]} onChange={handleCoverChange} {...coverProps} > <Button> <Icon type="upload" /> 上传封面 </Button> </Upload>, )} </Form.Item> <Form.Item label="标题" css={css` width: 100%; `} > {getFieldDecorator('name', { rules: [{ required: true, message: '请输入文章标题' }], initialValue: initialName, })(<Input placeholder="标题" />)} </Form.Item> <Form.Item label="分类" css={css` width: 100%; `} > {getFieldDecorator('categories', { initialValue: initialCategories, })( <Select mode="tags" placeholder="输入文章分类" onChange={handleCategoriesChange} > {getFieldValue('categories').map((category: string) => ( <Option key={category}>{category}</Option> ))} </Select>, )} </Form.Item> <Form.Item label="标签" css={css` width: 100%; `} > {getFieldDecorator('topics', { initialValue: initialTopics, })( <Select mode="tags" placeholder="输入文章标签" onChange={handleTopicsChange} > {getFieldValue('topics').map((topic: string) => ( <Option key={topic}>{topic}</Option> ))} </Select>, )} </Form.Item> <Form.Item label="选择步骤"> {getFieldDecorator('steps', { rules: [{ required: true, message: '请选择文章包含的步骤' }], initialValue: initialTargetKeys, })( <Transfer dataSource={collectionSteps} titles={['所有步骤', '已选步骤']} targetKeys={targetKeys} operations={['选择', '释放']} listStyle={{ width: 320, height: 300, }} selectedKeys={selectedKeys} onChange={handleTargetChange} onSelectChange={handleSelectChange} showSearch filterOption={filterOption} render={(item) => { if (targetKeys.includes(item.key)) { return item.title!; } return ( <span> {item?.articleId && ( <Tooltip title={`此步骤已经被文章 ${item?.articleName} 选择了`} > <Tag color="#02b875" css={css` color: #fff; &:hover { cursor: pointer; } `} > {item.articleIndex + 1} </Tag> </Tooltip> )} <span>{item.title}</span> </span> ); }} />, )} </Form.Item> <Form.Item css={css` width: 100%; `} > <div> <Button css={css` margin-right: 16px; `} onClick={() => dispatch.drawer.setChildrenVisible(false)} > 取消 </Button> <Button htmlType="submit" type="primary"> 确认 </Button> </div> </Form.Item> </Form> {props.childrenDrawerType === EDIT_ARTICLE && ( <React.Fragment> <Divider /> <div onClick={() => showDeleteConfirm( articleMeta.name!, dispatch, editArticleId!, nowArticleId!, history, ) } css={css` &:hover span, &:hover svg { color: #02b875; cursor: pointer; } `} > <Icon type="delete" /> <span css={css` margin-left: 8px; font-size: 14px; font-family: PingFangSC-Medium, PingFang SC; font-weight: 500; color: rgba(0, 0, 0, 1); line-height: 22px; `} > 删除此文章 </span> </div> </React.Fragment> )} </div> ); } export default Form.create<CreateEditArticleProps>({ name: 'CreateEditArticle', })(CreateEditArticle);
the_stack
import * as models from '../models'; /* generated type guards */ export function isBlob(arg: any): arg is models.Blob { return ( arg != null && typeof arg === 'object' && // content?: string ( typeof arg.content === 'undefined' || typeof arg.content === 'string' ) && // encoding?: ('utf-8' | 'base64') ( typeof arg.encoding === 'undefined' || ['utf-8', 'base64'].includes(arg.encoding) ) && // sha?: string ( typeof arg.sha === 'undefined' || typeof arg.sha === 'string' ) && // size?: number ( typeof arg.size === 'undefined' || typeof arg.size === 'number' ) && true ); } export function isCat(arg: any): arg is models.Cat { return ( arg != null && typeof arg === 'object' && // age?: number ( typeof arg.age === 'undefined' || typeof arg.age === 'number' ) && // eaten?: Mouse[] ( typeof arg.eaten === 'undefined' || ( Array.isArray(arg.eaten) && arg.eaten.every((item: any) => isMouse(item)) ) ) && // hunts?: boolean ( typeof arg.hunts === 'undefined' || typeof arg.hunts === 'boolean' ) && // extends Pet isPet(arg) && true ); } export function isCornerTestCasesModel(arg: any): arg is models.CornerTestCasesModel { return ( arg != null && typeof arg === 'object' && // metadata?: any true ); } export function isCustomer(arg: any): arg is models.Customer { return ( arg != null && typeof arg === 'object' && // address?: string ( typeof arg.address === 'undefined' || typeof arg.address === 'string' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // right?: Right ( typeof arg.right === 'undefined' || isRight(arg.right) ) && // extends Model isModel(arg) && true ); } export function isData(arg: any): arg is models.Data { return ( arg != null && typeof arg === 'object' && // email?: string ( typeof arg.email === 'undefined' || typeof arg.email === 'string' ) && // firstName?: string ( typeof arg.firstName === 'undefined' || typeof arg.firstName === 'string' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // lastName?: string ( typeof arg.lastName === 'undefined' || typeof arg.lastName === 'string' ) && // phone?: string ( typeof arg.phone === 'undefined' || typeof arg.phone === 'string' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isDataModel(arg: any): arg is models.DataModel { return ( arg != null && typeof arg === 'object' && // audioConfig?: Data ( typeof arg.audioConfig === 'undefined' || ( isData(arg.audioConfig) ) ) && // details?: object[] ( typeof arg.details === 'undefined' || ( Array.isArray(arg.details) && arg.details.every((item: any) => typeof item === 'object') ) ) && // entities?: number[] ( typeof arg.entities === 'undefined' || ( Array.isArray(arg.entities) && arg.entities.every((item: any) => typeof item === 'number') ) ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // imageData?: string ( typeof arg.imageData === 'undefined' || typeof arg.imageData === 'string' ) && // imageUrl?: string ( typeof arg.imageUrl === 'undefined' || typeof arg.imageUrl === 'string' ) && // metadata?: object ( typeof arg.metadata === 'undefined' || typeof arg.metadata === 'object' ) && // roleId?: number ( typeof arg.roleId === 'undefined' || typeof arg.roleId === 'number' ) && // testWithArray?: Pet[] & Data ( typeof arg.testWithArray === 'undefined' || ( ( Array.isArray(arg.testWithArray) && arg.testWithArray.every((item: any) => isPet(item)) ) && isData(arg.testWithArray) ) ) && // text?: ItemList & Data ( typeof arg.text === 'undefined' || ( isItemList(arg.text) && isData(arg.text) ) ) && // willAlsoBeRemoved?: string ( typeof arg.willAlsoBeRemoved === 'undefined' || typeof arg.willAlsoBeRemoved === 'string' ) && // willBeRemoved?: string ( typeof arg.willBeRemoved === 'undefined' || typeof arg.willBeRemoved === 'string' ) && true ); } export function isDictionary(arg: any): arg is models.Dictionary { return ( arg != null && typeof arg === 'object' && // [key: string]: DictionaryItem Object.values(arg).every((value: any) => isDictionaryItem(value)) && true ); } export function isDictionaryItem(arg: any): arg is models.DictionaryItem { return ( arg != null && typeof arg === 'object' && // [key: string]: number Object.values(arg).every((value: any) => typeof value === 'number') && true ); } export function isDog(arg: any): arg is models.Dog { return ( arg != null && typeof arg === 'object' && // bark?: boolean ( typeof arg.bark === 'undefined' || typeof arg.bark === 'boolean' ) && // breed?: ('Dingo' | 'Husky' | 'Retriever' | 'Shepherd') ( typeof arg.breed === 'undefined' || ['Dingo', 'Husky', 'Retriever', 'Shepherd'].includes(arg.breed) ) && // extends Pet isPet(arg) && true ); } export function isInterfaceWithArrayOfDictionariesOfArrayOfRights(arg: any): arg is models.InterfaceWithArrayOfDictionariesOfArrayOfRights { return ( arg != null && typeof arg === 'object' && // foo?: { [key: string]: Right[] }[] ( typeof arg.foo === 'undefined' || ( Array.isArray(arg.foo) && arg.foo.every((item: any) => Object.values(item).every((value: any) => ( Array.isArray(value) && value.every((item: any) => isRight(item)) ))) ) ) && true ); } export function isInterfaceWithArrayOfDictionariesOfNumbers(arg: any): arg is models.InterfaceWithArrayOfDictionariesOfNumbers { return ( arg != null && typeof arg === 'object' && // arrayOfDicsOfNumbers: { [key: string]: number }[] ( Array.isArray(arg.arrayOfDicsOfNumbers) && arg.arrayOfDicsOfNumbers.every((item: any) => Object.values(item).every((value: any) => typeof value === 'number')) ) && true ); } export function isInterfaceWithArrayOfDictionariesOfRights(arg: any): arg is models.InterfaceWithArrayOfDictionariesOfRights { return ( arg != null && typeof arg === 'object' && // foo?: { [key: string]: Right }[] ( typeof arg.foo === 'undefined' || ( Array.isArray(arg.foo) && arg.foo.every((item: any) => Object.values(item).every((value: any) => isRight(value))) ) ) && true ); } export function isInterfaceWithDictionary(arg: any): arg is models.InterfaceWithDictionary { return ( arg != null && typeof arg === 'object' && // customers?: { [key: string]: Customer } ( typeof arg.customers === 'undefined' || Object.values(arg.customers).every((value: any) => isCustomer(value)) ) && // id: string typeof arg.id === 'string' && true ); } export function isInterfaceWithDictionaryOfArraysOfNumbers(arg: any): arg is models.InterfaceWithDictionaryOfArraysOfNumbers { return ( arg != null && typeof arg === 'object' && // dicOfNumberArrays: { [key: string]: number[] } Object.values(arg.dicOfNumberArrays).every((value: any) => ( Array.isArray(value) && value.every((item: any) => typeof item === 'number') )) && true ); } export function isInterfaceWithSimpleDictionary(arg: any): arg is models.InterfaceWithSimpleDictionary { return ( arg != null && typeof arg === 'object' && // foo: { [key: string]: number } Object.values(arg.foo).every((value: any) => typeof value === 'number') && true ); } export function isItemList(arg: any): arg is models.ItemList { return ( arg != null && typeof arg === 'object' && // data: Data[] ( Array.isArray(arg.data) && arg.data.every((item: any) => isData(item)) ) && true ); } export function isItemModelList(arg: any): arg is models.ItemModelList { return ( arg != null && typeof arg === 'object' && // data: DataModel[] ( Array.isArray(arg.data) && arg.data.every((item: any) => isDataModel(item)) ) && true ); } export function isModel(arg: any): arg is models.Model { return ( arg != null && typeof arg === 'object' && // created?: number ( typeof arg.created === 'undefined' || typeof arg.created === 'number' ) && // deleted?: number ( typeof arg.deleted === 'undefined' || typeof arg.deleted === 'number' ) && // id?: string ( typeof arg.id === 'undefined' || typeof arg.id === 'string' ) && // recursivePointer?: Model ( typeof arg.recursivePointer === 'undefined' || isModel(arg.recursivePointer) ) && // updated?: number ( typeof arg.updated === 'undefined' || typeof arg.updated === 'number' ) && true ); } export function isModelParam(arg: any): arg is models.ModelParam { return ( arg != null && typeof arg === 'object' && // privilegesToAssing?: number[] ( typeof arg.privilegesToAssing === 'undefined' || ( Array.isArray(arg.privilegesToAssing) && arg.privilegesToAssing.every((item: any) => typeof item === 'number') ) ) && // privilegesToUnassing?: number[] ( typeof arg.privilegesToUnassing === 'undefined' || ( Array.isArray(arg.privilegesToUnassing) && arg.privilegesToUnassing.every((item: any) => typeof item === 'number') ) ) && // status?: Model ( typeof arg.status === 'undefined' || isModel(arg.status) ) && // usersToAssing?: number[] ( typeof arg.usersToAssing === 'undefined' || ( Array.isArray(arg.usersToAssing) && arg.usersToAssing.every((item: any) => typeof item === 'number') ) ) && // usersToUnassing?: number[] ( typeof arg.usersToUnassing === 'undefined' || ( Array.isArray(arg.usersToUnassing) && arg.usersToUnassing.every((item: any) => typeof item === 'number') ) ) && true ); } export function isMouse(arg: any): arg is models.Mouse { return ( arg != null && typeof arg === 'object' && // color?: string ( typeof arg.color === 'undefined' || typeof arg.color === 'string' ) && // extends Pet isPet(arg) && true ); } export function isMyInterface(arg: any): arg is models.MyInterface { return ( arg != null && typeof arg === 'object' && // myId?: string ( typeof arg.myId === 'undefined' || typeof arg.myId === 'string' ) && // myMap?: { [key: string]: Data } ( typeof arg.myMap === 'undefined' || Object.values(arg.myMap).every((value: any) => isData(value)) ) && // myName?: string ( typeof arg.myName === 'undefined' || typeof arg.myName === 'string' ) && true ); } export function isNumberEnumParam(arg: any): arg is models.NumberEnumParam { return arg != null || arg === models.NumberEnumParam.V1 || arg === models.NumberEnumParam.V2 ; } export function isPageData(arg: any): arg is models.PageData { return ( arg != null && typeof arg === 'object' && // appliedIf?: PageDataRules ( typeof arg.appliedIf === 'undefined' || isPageDataRules(arg.appliedIf) ) && true ); } export function isPageDataRules(arg: any): arg is models.PageDataRules { return ( arg != null && typeof arg === 'object' && // [key: string]: string[] Object.values(arg).every((value: any) => ( Array.isArray(value) && value.every((item: any) => typeof item === 'string') )) && true ); } export function isPet(arg: any): arg is models.Pet { return ( arg != null && typeof arg === 'object' && // pet_type: string typeof arg.pet_type === 'string' && true ); } export function isPosition(arg: any): arg is models.Position { return arg != null || arg === models.Position.First || arg === models.Position.Second || arg === models.Position.Third ; } export function isRight(arg: any): arg is models.Right { return arg != null || arg === models.Right.MEMBER || arg === models.Right.ADMIN || arg === models.Right.VIEW_ALL || arg === models.Right.VIEW_MY || arg === models.Right.VIEW_EDIT || arg === models.Right.READ_WRITE || arg === models.Right.CONTROL ; } export function isStringEnumParam(arg: any): arg is models.StringEnumParam { return arg != null || arg === models.StringEnumParam.json || arg === models.StringEnumParam.media || arg === models.StringEnumParam.proto ; } export function isTable(arg: any): arg is models.Table { return ( arg != null && typeof arg === 'object' && // someOtherData?: number[][] ( typeof arg.someOtherData === 'undefined' || ( Array.isArray(arg.someOtherData) && arg.someOtherData.every((item: any) => ( Array.isArray(item) && item.every((item: any) => typeof item === 'number') )) ) ) && // tableData?: DataModel[][] ( typeof arg.tableData === 'undefined' || ( Array.isArray(arg.tableData) && arg.tableData.every((item: any) => ( Array.isArray(item) && item.every((item: any) => isDataModel(item)) )) ) ) && // tableHead?: DataModel[] ( typeof arg.tableHead === 'undefined' || ( Array.isArray(arg.tableHead) && arg.tableHead.every((item: any) => isDataModel(item)) ) ) && true ); } export function isTestModel(arg: any): arg is models.TestModel { return ( arg != null && typeof arg === 'object' && // '\u6c49\u5b57'?: string ( typeof arg['汉字'] === 'undefined' || typeof arg['汉字'] === 'string' ) && // '42test'?: string ( typeof arg['42test'] === 'undefined' || typeof arg['42test'] === 'string' ) && // 'anotherKey@'?: string ( typeof arg['anotherKey@'] === 'undefined' || typeof arg['anotherKey@'] === 'string' ) && // 'some-key'?: string ( typeof arg['some-key'] === 'undefined' || typeof arg['some-key'] === 'string' ) && // 'yet@notherKey'?: string ( typeof arg['yet@notherKey'] === 'undefined' || typeof arg['yet@notherKey'] === 'string' ) && // $name?: string ( typeof arg.$name === 'undefined' || typeof arg.$name === 'string' ) && // count?: number ( typeof arg.count === 'undefined' || typeof arg.count === 'number' ) && true ); } export function isV1ContentModelArray(arg: any): arg is models.V1ContentModelArray { return ( arg != null && typeof arg === 'object' && // itemSchema?: V1ContentModelElement ( typeof arg.itemSchema === 'undefined' || isV1ContentModelElement(arg.itemSchema) ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && true ); } export function isV1ContentModelBool(arg: any): arg is models.V1ContentModelBool { return ( arg != null && typeof arg === 'object' && // default?: boolean ( typeof arg.default === 'undefined' || typeof arg.default === 'boolean' ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && true ); } export function isV1ContentModelDouble(arg: any): arg is models.V1ContentModelDouble { return ( arg != null && typeof arg === 'object' && // default?: number ( typeof arg.default === 'undefined' || typeof arg.default === 'number' ) && // enum?: number[] ( typeof arg.enum === 'undefined' || ( Array.isArray(arg.enum) && arg.enum.every((item: any) => typeof item === 'number') ) ) && // maximum?: number ( typeof arg.maximum === 'undefined' || typeof arg.maximum === 'number' ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && // minimum?: number ( typeof arg.minimum === 'undefined' || typeof arg.minimum === 'number' ) && true ); } export function isV1ContentModelElement(arg: any): arg is models.V1ContentModelElement { return ( arg != null && typeof arg === 'object' && // array?: V1ContentModelArray ( typeof arg.array === 'undefined' || isV1ContentModelArray(arg.array) ) && // bool?: V1ContentModelBool ( typeof arg.bool === 'undefined' || isV1ContentModelBool(arg.bool) ) && // double?: V1ContentModelDouble ( typeof arg.double === 'undefined' || isV1ContentModelDouble(arg.double) ) && // int?: V1ContentModelInteger ( typeof arg.int === 'undefined' || isV1ContentModelInteger(arg.int) ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && // object?: V1ContentModelObject ( typeof arg.object === 'undefined' || isV1ContentModelObject(arg.object) ) && // string?: V1ContentModelString ( typeof arg.string === 'undefined' || isV1ContentModelString(arg.string) ) && true ); } export function isV1ContentModelField(arg: any): arg is models.V1ContentModelField { return ( arg != null && typeof arg === 'object' && // array?: V1ContentModelArray ( typeof arg.array === 'undefined' || isV1ContentModelArray(arg.array) ) && // bool?: V1ContentModelBool ( typeof arg.bool === 'undefined' || isV1ContentModelBool(arg.bool) ) && // double?: V1ContentModelDouble ( typeof arg.double === 'undefined' || isV1ContentModelDouble(arg.double) ) && // int?: V1ContentModelInteger ( typeof arg.int === 'undefined' || isV1ContentModelInteger(arg.int) ) && // key?: string ( typeof arg.key === 'undefined' || typeof arg.key === 'string' ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && // object?: V1ContentModelObject ( typeof arg.object === 'undefined' || isV1ContentModelObject(arg.object) ) && // string?: V1ContentModelString ( typeof arg.string === 'undefined' || isV1ContentModelString(arg.string) ) && true ); } export function isV1ContentModelInteger(arg: any): arg is models.V1ContentModelInteger { return ( arg != null && typeof arg === 'object' && // default?: string ( typeof arg.default === 'undefined' || typeof arg.default === 'string' ) && // enum?: string[] ( typeof arg.enum === 'undefined' || ( Array.isArray(arg.enum) && arg.enum.every((item: any) => typeof item === 'string') ) ) && // maximum?: string ( typeof arg.maximum === 'undefined' || typeof arg.maximum === 'string' ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && // minimum?: string ( typeof arg.minimum === 'undefined' || typeof arg.minimum === 'string' ) && true ); } export function isV1ContentModelMetaInfo(arg: any): arg is models.V1ContentModelMetaInfo { return ( arg != null && typeof arg === 'object' && // comment?: string ( typeof arg.comment === 'undefined' || typeof arg.comment === 'string' ) && // customId?: string ( typeof arg.customId === 'undefined' || typeof arg.customId === 'string' ) && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isV1ContentModelObject(arg: any): arg is models.V1ContentModelObject { return ( arg != null && typeof arg === 'object' && // fields?: V1ContentModelField[] ( typeof arg.fields === 'undefined' || ( Array.isArray(arg.fields) && arg.fields.every((item: any) => isV1ContentModelField(item)) ) ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && true ); } export function isV1ContentModelString(arg: any): arg is models.V1ContentModelString { return ( arg != null && typeof arg === 'object' && // default?: string ( typeof arg.default === 'undefined' || typeof arg.default === 'string' ) && // enum?: string[] ( typeof arg.enum === 'undefined' || ( Array.isArray(arg.enum) && arg.enum.every((item: any) => typeof item === 'string') ) ) && // meta?: V1ContentModelMetaInfo ( typeof arg.meta === 'undefined' || isV1ContentModelMetaInfo(arg.meta) ) && // regex?: string ( typeof arg.regex === 'undefined' || typeof arg.regex === 'string' ) && true ); } export function isV1ContentModelVersion(arg: any): arg is models.V1ContentModelVersion { return ( arg != null && typeof arg === 'object' && // contentModelId?: string ( typeof arg.contentModelId === 'undefined' || typeof arg.contentModelId === 'string' ) && // contentModelVersionId?: string ( typeof arg.contentModelVersionId === 'undefined' || typeof arg.contentModelVersionId === 'string' ) && // createdAt?: string ( typeof arg.createdAt === 'undefined' || typeof arg.createdAt === 'string' ) && // nextVersionId?: string ( typeof arg.nextVersionId === 'undefined' || typeof arg.nextVersionId === 'string' ) && // previousVersionId?: string ( typeof arg.previousVersionId === 'undefined' || typeof arg.previousVersionId === 'string' ) && // schema?: V1ContentModelObject ( typeof arg.schema === 'undefined' || isV1ContentModelObject(arg.schema) ) && true ); } export function isV1ContentModelVersionList(arg: any): arg is models.V1ContentModelVersionList { return ( arg != null && typeof arg === 'object' && // versions?: V1ContentModelVersion[] ( typeof arg.versions === 'undefined' || ( Array.isArray(arg.versions) && arg.versions.every((item: any) => isV1ContentModelVersion(item)) ) ) && true ); }
the_stack
import React, { useState, useEffect, useCallback } from "react"; import { cloneDeep } from "lodash"; import { css } from "emotion"; import { Dialog, DialogContent, DialogTitle, DialogActions } from "@webiny/ui/Dialog"; import { Form } from "@webiny/form"; import { Tabs, Tab } from "@webiny/ui/Tabs"; import { i18n } from "@webiny/app/i18n"; import { CmsEditorField, CmsEditorFieldRendererPlugin, CmsEditorFieldTypePlugin, CmsEditorFieldValidatorPlugin } from "~/types"; import { plugins } from "@webiny/plugins"; import GeneralTab from "./EditFieldDialog/GeneralTab"; import AppearanceTab from "./EditFieldDialog/AppearanceTab"; import PredefinedValues from "./EditFieldDialog/PredefinedValues"; import ValidatorsTab from "./EditFieldDialog/ValidatorsTab"; import { Grid, Cell } from "@webiny/ui/Grid"; import { Typography } from "@webiny/ui/Typography"; import { Elevation } from "@webiny/ui/Elevation"; import { useFieldEditor } from "~/admin/components/FieldEditor/useFieldEditor"; import invariant from "invariant"; import { ButtonDefault, ButtonPrimary } from "@webiny/ui/Button"; const t = i18n.namespace("app-headless-cms/admin/components/editor"); const dialogBody = css({ "&.webiny-ui-dialog__content": { width: 875, height: 450 } }); interface EditFieldDialogProps { field: CmsEditorField | null; onClose: () => void; onSubmit: (data: CmsEditorField) => void; } interface Validator { optional: boolean; validator: CmsEditorFieldValidatorPlugin["validator"]; } const getValidators = ( fieldPlugin: CmsEditorFieldTypePlugin, /** * We only have validators and listValidators, thats why the strict string types */ key: "validators" | "listValidators", defaultValidators: string[] = [] ): Validator[] => { const mappedValidators = plugins .byType<CmsEditorFieldValidatorPlugin>("cms-editor-field-validator") .map(({ validator }) => { const allowedValidators = fieldPlugin.field[key] || defaultValidators; if (allowedValidators.includes(validator.name)) { return { optional: true, validator }; } else if (allowedValidators.includes(`!${validator.name}`)) { return { optional: false, validator }; } return null; }); const filteredValidators = mappedValidators.filter(Boolean) as Validator[]; return ( filteredValidators /** * We can safely cast because we are filtering in previous step. */ .sort((a: Validator, b: Validator) => { if (!a.optional && b.optional) { return -1; } if (a.optional && !b.optional) { return 1; } return 0; }) as Validator[] ); }; const getListValidators = (fieldPlugin: CmsEditorFieldTypePlugin) => { return getValidators(fieldPlugin, "listValidators", ["minLength", "maxLength"]); }; const getFieldValidators = (fieldPlugin: CmsEditorFieldTypePlugin) => { return getValidators(fieldPlugin, "validators"); }; const fieldEditorDialog = css({ width: "100vw", height: "100vh", ".mdc-dialog__surface": { maxWidth: "100% !important", maxHeight: "100% !important", ".webiny-ui-dialog__content": { maxWidth: "100% !important", maxHeight: "100% !important", width: "100vw", height: "calc(100vh - 155px)", paddingTop: "0 !important" } } }); const EditFieldDialog: React.FC<EditFieldDialogProps> = ({ field, onSubmit, ...props }) => { const [current, setCurrent] = useState<CmsEditorField | null>(null); const { getFieldPlugin } = useFieldEditor(); useEffect((): void => { if (!field) { setCurrent(field); return; } const clonedField = cloneDeep(field); if (!clonedField.renderer || !clonedField.renderer.name) { const [renderPlugin] = plugins .byType<CmsEditorFieldRendererPlugin>("cms-editor-field-renderer") .filter(item => item.renderer.canUse({ field })); if (renderPlugin) { clonedField.renderer = { name: renderPlugin.renderer.rendererName }; } } setCurrent(clonedField); }, [field]); const onClose = useCallback((): void => { setCurrent(null); props.onClose(); }, []); let render = null; let headerTitle = t`Field Settings`; if (current) { /** * Something must be very wrong for field plugin to be missing. */ const fieldPlugin = getFieldPlugin(current.type) as CmsEditorFieldTypePlugin; /** * We will throw error because of that. */ invariant(fieldPlugin, `Missing field plugin for type "${current.type}".`); headerTitle = t`Field Settings - {fieldTypeLabel}`({ fieldTypeLabel: fieldPlugin.field.label }); render = ( <Form data={current} onSubmit={data => { /** * We know that data is CmsEditorField. */ return onSubmit(data as unknown as CmsEditorField); }} > {form => { const predefinedValuesTabEnabled = fieldPlugin.field.allowPredefinedValues && form.data.predefinedValues && form.data.predefinedValues.enabled; return ( <> <DialogContent className={dialogBody}> <Tabs> <Tab label={t`General`}> <GeneralTab form={form} field={form.data as CmsEditorField} fieldPlugin={fieldPlugin} /> </Tab> <Tab label={t`Predefined Values`} disabled={!predefinedValuesTabEnabled} > {predefinedValuesTabEnabled && ( <PredefinedValues form={form} field={form.data as CmsEditorField} fieldPlugin={fieldPlugin} /> )} </Tab> {form.data.multipleValues && ( <Tab label={"Validators"} data-testid={"cms.editor.field.tabs.validators"} > <Grid> <Cell span={12}> <Typography use={"headline5"}> List validators </Typography> <br /> <Typography use={"body2"}> These validators are applied to the entire list of values. </Typography> </Cell> <Cell span={12}> <Elevation z={2}> <ValidatorsTab field={current} name={"listValidation"} validators={getListValidators( fieldPlugin )} form={form} /> </Elevation> </Cell> </Grid> <Grid> <Cell span={12}> <Typography use={"headline5"}> Individual value validators </Typography> <br /> <Typography use={"body2"}> These validators are applied to each value in the list. </Typography> </Cell> <Cell span={12}> <Elevation z={2}> <ValidatorsTab field={current} form={form} name={"validation"} validators={getFieldValidators( fieldPlugin )} /> </Elevation> </Cell> </Grid> </Tab> )} {!form.data.multipleValues && Array.isArray(fieldPlugin.field.validators) && fieldPlugin.field.validators.length > 0 && ( <Tab label={"Validators"} data-testid={"cms.editor.field.tabs.validators"} > <ValidatorsTab field={current} form={form} name={"validation"} validators={getFieldValidators(fieldPlugin)} /> </Tab> )} <Tab label={t`Appearance`}> <AppearanceTab form={form} field={form.data as CmsEditorField} // TODO @ts-refactor verify that this actually worked? There was no fieldPlugin in AppearanceTab props // @ts-ignore fieldPlugin={fieldPlugin} /> </Tab> </Tabs> </DialogContent> <DialogActions> <ButtonDefault onClick={onClose}>{t`Cancel`}</ButtonDefault> <ButtonPrimary onClick={ev => { form.submit(ev); }} >{t`Save Field`}</ButtonPrimary> </DialogActions> </> ); }} </Form> ); } return ( <Dialog preventOutsideDismiss open={!!current} onClose={onClose} data-testid={"cms-editor-edit-fields-dialog"} className={fieldEditorDialog} > <DialogTitle>{headerTitle}</DialogTitle> {render} </Dialog> ); }; export default EditFieldDialog;
the_stack
module android.widget { import R = android.R; import ColorStateList = android.content.res.ColorStateList; import Resources = android.content.res.Resources; import Canvas = android.graphics.Canvas; import Paint = android.graphics.Paint; import Path = android.graphics.Path; import Rect = android.graphics.Rect; import Color = android.graphics.Color; import RectF = android.graphics.RectF; import Drawable = android.graphics.drawable.Drawable; import Handler = android.os.Handler; import Message = android.os.Message; import SystemClock = android.os.SystemClock; import BoringLayout = android.text.BoringLayout; import DynamicLayout = android.text.DynamicLayout; import InputType = android.text.InputType; import Layout = android.text.Layout; import SpanWatcher = android.text.SpanWatcher; import Spannable = android.text.Spannable; import Spanned = android.text.Spanned; import StaticLayout = android.text.StaticLayout; import TextDirectionHeuristic = android.text.TextDirectionHeuristic; import TextDirectionHeuristics = android.text.TextDirectionHeuristics; import TextPaint = android.text.TextPaint; import TextUtils = android.text.TextUtils; import TruncateAt = android.text.TextUtils.TruncateAt; import TextWatcher = android.text.TextWatcher; import AllCapsTransformationMethod = android.text.method.AllCapsTransformationMethod; import MovementMethod = android.text.method.MovementMethod; import SingleLineTransformationMethod = android.text.method.SingleLineTransformationMethod; import TransformationMethod = android.text.method.TransformationMethod; import TransformationMethod2 = android.text.method.TransformationMethod2; import CharacterStyle = android.text.style.CharacterStyle; import ParagraphStyle = android.text.style.ParagraphStyle; import UpdateAppearance = android.text.style.UpdateAppearance; import Log = android.util.Log; import TypedValue = android.util.TypedValue; import Gravity = android.view.Gravity; import HapticFeedbackConstants = android.view.HapticFeedbackConstants; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import View = android.view.View; import ViewConfiguration = android.view.ViewConfiguration; import LayoutParams = android.view.ViewGroup.LayoutParams; import ViewRootImpl = android.view.ViewRootImpl; import ViewTreeObserver = android.view.ViewTreeObserver; import AnimationUtils = android.view.animation.AnimationUtils; import WeakReference = java.lang.ref.WeakReference; import ArrayList = java.util.ArrayList; import Integer = java.lang.Integer; import System = java.lang.System; import Runnable = java.lang.Runnable; import OverScroller = android.widget.OverScroller; import NetDrawable = androidui.image.NetDrawable; import AttrBinder = androidui.attr.AttrBinder; /** * Displays text to the user and optionally allows them to edit it. A TextView * is a complete text editor, however the basic class is configured to not * allow editing; see {@link EditText} for a subclass that configures the text * view for editing. * * <p> * To allow users to copy some or all of the TextView's value and paste it somewhere else, set the * XML attribute {@link android.R.styleable#TextView_textIsSelectable * android:textIsSelectable} to "true" or call * {@link #setTextIsSelectable setTextIsSelectable(true)}. The {@code textIsSelectable} flag * allows users to make selection gestures in the TextView, which in turn triggers the system's * built-in copy/paste controls. * <p> * <b>XML attributes</b> * <p> * See {@link android.R.styleable#TextView TextView Attributes}, * {@link android.R.styleable#View View Attributes} * * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_bufferType * @attr ref android.R.styleable#TextView_hint * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * @attr ref android.R.styleable#TextView_textSize * @attr ref android.R.styleable#TextView_textScaleX * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle * @attr ref android.R.styleable#TextView_cursorVisible * @attr ref android.R.styleable#TextView_maxLines * @attr ref android.R.styleable#TextView_maxHeight * @attr ref android.R.styleable#TextView_lines * @attr ref android.R.styleable#TextView_height * @attr ref android.R.styleable#TextView_minLines * @attr ref android.R.styleable#TextView_minHeight * @attr ref android.R.styleable#TextView_maxEms * @attr ref android.R.styleable#TextView_maxWidth * @attr ref android.R.styleable#TextView_ems * @attr ref android.R.styleable#TextView_width * @attr ref android.R.styleable#TextView_minEms * @attr ref android.R.styleable#TextView_minWidth * @attr ref android.R.styleable#TextView_gravity * @attr ref android.R.styleable#TextView_scrollHorizontally * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine * @attr ref android.R.styleable#TextView_selectAllOnFocus * @attr ref android.R.styleable#TextView_includeFontPadding * @attr ref android.R.styleable#TextView_maxLength * @attr ref android.R.styleable#TextView_shadowColor * @attr ref android.R.styleable#TextView_shadowDx * @attr ref android.R.styleable#TextView_shadowDy * @attr ref android.R.styleable#TextView_shadowRadius * @attr ref android.R.styleable#TextView_autoLink * @attr ref android.R.styleable#TextView_linksClickable * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText * @attr ref android.R.styleable#TextView_editable * @attr ref android.R.styleable#TextView_freezesText * @attr ref android.R.styleable#TextView_ellipsize * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableBottom * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawablePadding * @attr ref android.R.styleable#TextView_lineSpacingExtra * @attr ref android.R.styleable#TextView_lineSpacingMultiplier * @attr ref android.R.styleable#TextView_marqueeRepeatLimit * @attr ref android.R.styleable#TextView_inputType * @attr ref android.R.styleable#TextView_imeOptions * @attr ref android.R.styleable#TextView_privateImeOptions * @attr ref android.R.styleable#TextView_imeActionLabel * @attr ref android.R.styleable#TextView_imeActionId * @attr ref android.R.styleable#TextView_editorExtras */ export class TextView extends View implements ViewTreeObserver.OnPreDrawListener { static LOG_TAG:string = "TextView"; static DEBUG_EXTRACT:boolean = false; // Enum for the "typeface" XML parameter. // TODO: How can we get this from the XML instead of hardcoding it here? private static SANS:number = 1; private static SERIF:number = 2; private static MONOSPACE:number = 3; // Bitfield for the "numeric" XML parameter. // TODO: How can we get this from the XML instead of hardcoding it here? private static SIGNED:number = 2; private static DECIMAL:number = 4; /** * Draw marquee text with fading edges as usual */ private static MARQUEE_FADE_NORMAL:number = 0; /** * Draw marquee text as ellipsize end while inactive instead of with the fade. * (Useful for devices where the fade can be expensive if overdone) */ private static MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS:number = 1; /** * Draw marquee text with fading edges because it is currently active/animating. */ private static MARQUEE_FADE_SWITCH_SHOW_FADE:number = 2; private static LINES:number = 1; private static EMS:number = TextView.LINES; private static PIXELS:number = 2; private static TEMP_RECTF:RectF = new RectF(); // XXX should be much larger private static VERY_WIDE:number = 1024 * 1024; private static ANIMATED_SCROLL_GAP:number = 250; private static NO_FILTERS = new Array<any>(0); //private static EMPTY_SPANNED:Spanned = new SpannedString(""); private static CHANGE_WATCHER_PRIORITY:number = 100; // New state used to change background based on whether this TextView is multiline. private static MULTILINE_STATE_SET:number[] = [ View.VIEW_STATE_MULTILINE ]; // System wide time for last cut or copy action. static LAST_CUT_OR_COPY_TIME:number = 0; private mTextColor:ColorStateList = ColorStateList.valueOf(Color.BLACK); private mHintTextColor:ColorStateList; private mLinkTextColor:ColorStateList; private mCurTextColor:number = 0; private mCurHintTextColor:number = 0; private mFreezesText:boolean; private mTemporaryDetach:boolean; private mDispatchTemporaryDetach:boolean; //private mEditableFactory:Editable.Factory = Editable.Factory.getInstance(); private mSpannableFactory:Spannable.Factory = Spannable.Factory.getInstance(); private mShadowRadius:number = 0; private mShadowDx:number = 0; private mShadowDy:number = 0; private mPreDrawRegistered:boolean; // A flag to prevent repeated movements from escaping the enclosing text view. The idea here is // that if a user is holding down a movement key to traverse text, we shouldn't also traverse // the view hierarchy. On the other hand, if the user is using the movement key to traverse views // (i.e. the first movement was to traverse out of this view, or this view was traversed into by // the user holding the movement key down) then we shouldn't prevent the focus from changing. private mPreventDefaultMovement:boolean; private mEllipsize:TextUtils.TruncateAt; mDrawables:TextView.Drawables; //private mCharWrapper:TextView.CharWrapper; private mMarquee:TextView.Marquee; private mRestartMarquee:boolean; private mMarqueeRepeatLimit:number = 3; private mLastLayoutDirection:number = -1; /** * On some devices the fading edges add a performance penalty if used * extensively in the same layout. This mode indicates how the marquee * is currently being shown, if applicable. (mEllipsize will == MARQUEE) */ private mMarqueeFadeMode:number = TextView.MARQUEE_FADE_NORMAL; /** * When mMarqueeFadeMode is not MARQUEE_FADE_NORMAL, this stores * the layout that should be used when the mode switches. */ private mSavedMarqueeModeLayout:Layout; private mText:String; private mTransformed:String; private mBufferType:TextView.BufferType = TextView.BufferType.NORMAL; private mHint:String; private mHintLayout:Layout; private mMovement:MovementMethod; private mTransformation:TransformationMethod; private mAllowTransformationLengthChange:boolean; private mChangeWatcher:TextView.ChangeWatcher; private mListeners:ArrayList<TextWatcher>; // display attributes private mTextPaint:TextPaint; private mUserSetTextScaleX:boolean; private mLayout:Layout; private mGravity:number = Gravity.TOP | Gravity.LEFT; private mHorizontallyScrolling:boolean; private mAutoLinkMask:number = 0; private mLinksClickable:boolean = true; private mSpacingMult:number = 1.0; private mSpacingAdd:number = 0.0; private mMaximum:number = Integer.MAX_VALUE; private mMaxMode:number = TextView.LINES; private mMinimum:number = 0; private mMinMode:number = TextView.LINES; private mOldMaximum:number = this.mMaximum; private mOldMaxMode:number = this.mMaxMode; private mMaxWidthValue:number = Integer.MAX_VALUE; private mMaxWidthMode:number = TextView.PIXELS; private mMinWidthValue:number = 0; private mMinWidthMode:number = TextView.PIXELS; private mSingleLine:boolean; private mDesiredHeightAtMeasure:number = -1; private mIncludePad:boolean = true; private mDeferScroll:number = -1; // tmp primitives, so we don't alloc them on each draw private mTempRect:Rect; private mLastScroll:number = 0; private mScroller:OverScroller; private mBoring:BoringLayout.Metrics; private mHintBoring:BoringLayout.Metrics; private mSavedLayout:BoringLayout; private mSavedHintLayout:BoringLayout; private mTextDir:TextDirectionHeuristic; private mFilters = TextView.NO_FILTERS; //private mCurrentSpellCheckerLocaleCache:Locale; // It is possible to have a selection even when mEditor is null (programmatically set, like when // a link is pressed). These highlight-related fields do not go in mEditor. mHighlightColor:number = 0x6633B5E5; private mHighlightPath:Path; private mHighlightPaint:Paint; private mHighlightPathBogus:boolean = true; // Although these fields are specific to editable text, they are not added to Editor because // they are defined by the TextView's style and are theme-dependent. mCursorDrawableRes:number = 0; // These four fields, could be moved to Editor, since we know their default values and we // could condition the creation of the Editor to a non standard value. This is however // brittle since the hardcoded values here (such as // com.android.internal.R.drawable.text_select_handle_left) would have to be updated if the // default style is modified. mTextSelectHandleLeftRes:number = 0; mTextSelectHandleRightRes:number = 0; mTextSelectHandleRes:number = 0; mTextEditSuggestionItemLayout:number = 0; /** * EditText specific data, created on demand when one of the Editor fields is used. * See {@link #createEditorIfNeeded()}. */ private mEditor:any; //androidui: flag will set to true when editing. protected mSkipDrawText = false; /* * Kick-start the font cache for the zygote process (to pay the cost of * initializing freetype for our default font only once). */ //static { // let p:Paint = new Paint(); // p.setAntiAlias(true); // // We don't care about the result, just the side-effect of measuring. // p.measureText("H"); //} constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle=android.R.attr.textViewStyle){ super(context, bindElement, defStyle); this.mText = ""; // const res = this.getResources(); // const compat = res.getCompatibilityInfo(); this.mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); // this.mTextPaint.density = res.getDisplayMetrics().density; // mTextPaint.setCompatibilityScaling(compat.applicationScale); this.mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // mHighlightPaint.setCompatibilityScaling(compat.applicationScale); this.mMovement = this.getDefaultMovementMethod(); this.mTransformation = null; let textColorHighlight = 0; let textColor:ColorStateList = null; let textColorHint:ColorStateList = null; let textColorLink:ColorStateList = null; let textSize = 14 * this.getResources().getDisplayMetrics().density; // let fontFamily:string = null; // let typefaceIndex = -1; // let styleIndex = -1; let allCaps = false; let shadowcolor = 0; let dx = 0, dy = 0, r = 0; /* * Look the appearance up without checking first if it exists because * almost every TextView has one and it greatly simplifies the logic * to be able to parse the appearance first and then let specific tags * for this View override it. * AndroidUIX note : not support text appearance now. */ // let a = context.obtainStyledAttributes(bindElement, defStyle); // let appearance = context.obtainStyledAttributes(bindElement, defStyle); // let appearance:android.content.res.TypedArray = null; // let ap = a.getString('textAppearance'); // a.recycle(); // if (ap) { // appearance = theme.obtainStyledAttributes( // ap, com.android.internal.R.styleable.TextAppearance); // } // if (appearance != null) { // for (let attr of appearance.getLowerCaseNoNamespaceAttrNames()) { // switch (attr) { // case 'textcolorhighlight': // textColorHighlight = appearance.getColor(attr, textColorHighlight); // break; // // case 'textcolor': // textColor = appearance.getColorStateList(attr); // break; // // case 'textcolorhint': // textColorHint = appearance.getColorStateList(attr); // break; // // case 'textcolorlink': // textColorLink = appearance.getColorStateList(attr); // break; // // case 'textsize': // textSize = appearance.getDimensionPixelSize(attr, textSize); // break; // // case 'typeface': // typefaceIndex = appearance.getInt(attr, -1); // break; // // case 'fontfamily': // fontFamily = appearance.getString(attr); // break; // // case 'textstyle': // styleIndex = appearance.getInt(attr, -1); // break; // // case 'textallcaps': // allCaps = appearance.getBoolean(attr, false); // break; // // case 'shadowcolor': // shadowcolor = appearance.getInt(attr, 0); // break; // // case 'shadowdx': // dx = appearance.getFloat(attr, 0); // break; // // case 'shadowdy': // dy = appearance.getFloat(attr, 0); // break; // // case 'shadowradius': // r = appearance.getFloat(attr, 0); // break; // } // // appearance.recycle(); // } // } let editable = this.getDefaultEditable(); // let inputMethod:String = null; let numeric = 0; let digits:String = null; // let phone = false; // let autotext = false; // let autocap = -1; // let buffertype = 0; // let selectallonfocus = false; let drawableLeft:Drawable = null, drawableTop:Drawable = null, drawableRight:Drawable = null, drawableBottom:Drawable = null, drawableStart:Drawable = null, drawableEnd:Drawable = null; let drawablePadding = 0; let ellipsize:TextUtils.TruncateAt; let singleLine = false; let maxlength = -1; let text = ""; let hint = null; // let password = false; // let inputType = 0; // EditorInfo.TYPE_NULL; let a = context.obtainStyledAttributes(bindElement, defStyle); for (let attr of a.getLowerCaseNoNamespaceAttrNames()) { switch (attr) { case 'editable': editable = a.getBoolean(attr, editable); break; case 'inputmethod': // inputMethod = a.getText(attr); break; case 'numeric': numeric = a.getInt(attr, numeric); break; case 'digits': digits = a.getText(attr); break; case 'phonenumber': // phone = a.getBoolean(attr, phone); break; case 'autotext': // autotext = a.getBoolean(attr, autotext); break; case 'capitalize': // autocap = a.getInt(attr, autocap); break; case 'buffertype': // buffertype = a.getInt(attr, buffertype); break; case 'selectallonfocus': // selectallonfocus = a.getBoolean(attr, selectallonfocus); break; case 'autolink': this.mAutoLinkMask = a.getInt(attr, 0); break; case 'linksclickable': this.mLinksClickable = a.getBoolean(attr, true); break; case 'drawableleft': drawableLeft = a.getDrawable(attr); break; case 'drawabletop': drawableTop = a.getDrawable(attr); break; case 'drawableright': drawableRight = a.getDrawable(attr); break; case 'drawablebottom': drawableBottom = a.getDrawable(attr); break; case 'drawablestart': drawableStart = a.getDrawable(attr); break; case 'drawableend': drawableEnd = a.getDrawable(attr); break; case 'drawablepadding': drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); break; case 'maxlines': this.setMaxLines(a.getInt(attr, -1)); break; case 'maxheight': this.setMaxHeight(a.getDimensionPixelSize(attr, -1)); break; case 'lines': this.setLines(a.getInt(attr, -1)); break; case 'height': this.setHeight(a.getDimensionPixelSize(attr, -1)); break; case 'minlines': this.setMinLines(a.getInt(attr, -1)); break; case 'minheight': this.setMinHeight(a.getDimensionPixelSize(attr, -1)); break; case 'maxems': this.setMaxEms(a.getInt(attr, -1)); break; case 'maxwidth': this.setMaxWidth(a.getDimensionPixelSize(attr, -1)); break; case 'ems': this.setEms(a.getInt(attr, -1)); break; case 'width': this.setWidth(a.getDimensionPixelSize(attr, -1)); break; case 'minems': this.setMinEms(a.getInt(attr, -1)); break; case 'minwidth': this.setMinWidth(a.getDimensionPixelSize(attr, -1)); break; case 'gravity': this.setGravity(Gravity.parseGravity(a.getAttrValue(attr), -1)); break; case 'hint': hint = a.getText(attr); break; case 'text': text = a.getText(attr); break; case 'scrollhorizontally': if (a.getBoolean(attr, false)) { this.setHorizontallyScrolling(true); } break; case 'singleline': singleLine = a.getBoolean(attr, singleLine); break; case 'ellipsize': ellipsize = TextUtils.TruncateAt[(a.getAttrValue(attr) + '').toUpperCase()]; break; case 'marqueerepeatlimit': this.setMarqueeRepeatLimit(a.getInt(attr, this.mMarqueeRepeatLimit)); break; case 'includefontpadding': if (!a.getBoolean(attr, true)) { this.setIncludeFontPadding(false); } break; case 'cursorvisible': if (!a.getBoolean(attr, true)) { this.setCursorVisible(false); } break; case 'maxlength': maxlength = a.getInt(attr, -1); break; case 'textscalex': this.setTextScaleX(a.getFloat(attr, 1.0)); break; case 'freezestext': this.mFreezesText = a.getBoolean(attr, false); break; case 'shadowcolor': shadowcolor = a.getInt(attr, 0); break; case 'shadowdx': dx = a.getFloat(attr, 0); break; case 'shadowdy': dy = a.getFloat(attr, 0); break; case 'shadowradius': r = a.getFloat(attr, 0); break; case 'enabled': this.setEnabled(a.getBoolean(attr, this.isEnabled())); break; case 'textcolorhighlight': textColorHighlight = a.getColor(attr, textColorHighlight); break; case 'textcolor': textColor = a.getColorStateList(attr); break; case 'textcolorhint': textColorHint = a.getColorStateList(attr); break; case 'textcolorlink': textColorLink = a.getColorStateList(attr); break; case 'textsize': textSize = a.getDimensionPixelSize(attr, textSize); break; case 'typeface': // typefaceIndex = a.getInt(attr, typefaceIndex); break; case 'textstyle': // styleIndex = a.getInt(attr, styleIndex); break; case 'fontfamily': // fontFamily = a.getString(attr); break; case 'password': // password = a.getBoolean(attr, password); break; case 'linespacingextra': this.mSpacingAdd = a.getDimensionPixelSize(attr, Math.floor(this.mSpacingAdd)); break; case 'linespacingmultiplier': this.mSpacingMult = a.getFloat(attr, this.mSpacingMult); break; case 'inputtype': // inputType = a.getInt(attr, EditorInfo.TYPE_NULL); break; case 'imeoptions': // createEditorIfNeeded(); // mEditor.createInputContentTypeIfNeeded(); // mEditor.mInputContentType.imeOptions = a.getInt(attr, // mEditor.mInputContentType.imeOptions); break; case 'imeactionlabel': // createEditorIfNeeded(); // mEditor.createInputContentTypeIfNeeded(); // mEditor.mInputContentType.imeActionLabel = a.getText(attr); break; case 'imeactionid': // createEditorIfNeeded(); // mEditor.createInputContentTypeIfNeeded(); // mEditor.mInputContentType.imeActionId = a.getInt(attr, // mEditor.mInputContentType.imeActionId); break; case 'privateimeoptions': // this.setPrivateImeOptions(a.getString(attr)); break; case 'editorextras': // try { // this.setInputExtras(a.getResourceId(attr, 0)); // } catch (e) { // Log.w(LOG_TAG, "Failure reading input extras", e); // } catch (IOException e) { // Log.w(LOG_TAG, "Failure reading input extras", e); // } break; case 'textcursordrawable': // this.mCursorDrawableRes = a.getResourceId(attr, 0); break; case 'textselecthandleleft': // this.mTextSelectHandleLeftRes = a.getResourceId(attr, 0); break; case 'textselecthandleright': // this.mTextSelectHandleRightRes = a.getResourceId(attr, 0); break; case 'textselecthandle': // this.mTextSelectHandleRes = a.getResourceId(attr, 0); break; case 'texteditsuggestionitemlayout': // this.mTextEditSuggestionItemLayout = a.getResourceId(attr, 0); break; case 'textisselectable': this.setTextIsSelectable(a.getBoolean(attr, false)); break; case 'textallcaps': allCaps = a.getBoolean(attr, false); break; } } a.recycle(); let bufferType = this.mBufferType;// TextView.BufferType.EDITABLE; // const variation = // inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); // final boolean passwordInputType = variation // == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); // final boolean webPasswordInputType = variation // == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD); // final boolean numberPasswordInputType = variation // == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); // if (inputMethod != null) { // Class<?> c; // // try { // c = Class.forName(inputMethod.toString()); // } catch (ClassNotFoundException ex) { // throw new RuntimeException(ex); // } // // try { // createEditorIfNeeded(); // mEditor.mKeyListener = (KeyListener) c.newInstance(); // } catch (InstantiationException ex) { // throw new RuntimeException(ex); // } catch (IllegalAccessException ex) { // throw new RuntimeException(ex); // } // try { // mEditor.mInputType = inputType != EditorInfo.TYPE_NULL // ? inputType // : mEditor.mKeyListener.getInputType(); // } catch (IncompatibleClassChangeError e) { // mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; // } // } else if (digits != null) { // createEditorIfNeeded(); // mEditor.mKeyListener = DigitsKeyListener.getInstance(digits.toString()); // // If no input type was specified, we will default to generic // // text, since we can't tell the IME about the set of digits // // that was selected. // mEditor.mInputType = inputType != EditorInfo.TYPE_NULL // ? inputType : EditorInfo.TYPE_CLASS_TEXT; // } else if (inputType != EditorInfo.TYPE_NULL) { // setInputType(inputType, true); // // If set, the input type overrides what was set using the deprecated singleLine flag. // singleLine = !isMultilineInputType(inputType); // } else if (phone) { // createEditorIfNeeded(); // mEditor.mKeyListener = DialerKeyListener.getInstance(); // mEditor.mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE; // } else if (numeric != 0) { // createEditorIfNeeded(); // mEditor.mKeyListener = DigitsKeyListener.getInstance((numeric & SIGNED) != 0, // (numeric & DECIMAL) != 0); // inputType = EditorInfo.TYPE_CLASS_NUMBER; // if ((numeric & SIGNED) != 0) { // inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; // } // if ((numeric & DECIMAL) != 0) { // inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; // } // mEditor.mInputType = inputType; // } else if (autotext || autocap != -1) { // TextKeyListener.Capitalize cap; // // inputType = EditorInfo.TYPE_CLASS_TEXT; // // switch (autocap) { // case 1: // cap = TextKeyListener.Capitalize.SENTENCES; // inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; // break; // // case 2: // cap = TextKeyListener.Capitalize.WORDS; // inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; // break; // // case 3: // cap = TextKeyListener.Capitalize.CHARACTERS; // inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; // break; // // default: // cap = TextKeyListener.Capitalize.NONE; // break; // } // // createEditorIfNeeded(); // mEditor.mKeyListener = TextKeyListener.getInstance(autotext, cap); // mEditor.mInputType = inputType; // } else if (isTextSelectable()) { // // Prevent text changes from keyboard. // if (mEditor != null) { // mEditor.mKeyListener = null; // mEditor.mInputType = EditorInfo.TYPE_NULL; // } // bufferType = BufferType.SPANNABLE; // // So that selection can be changed using arrow keys and touch is handled. // setMovementMethod(ArrowKeyMovementMethod.getInstance()); // } else if (editable) { // createEditorIfNeeded(); // mEditor.mKeyListener = TextKeyListener.getInstance(); // mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; // } else { // if (mEditor != null) mEditor.mKeyListener = null; // // switch (buffertype) { // case 0: // bufferType = BufferType.NORMAL; // break; // case 1: // bufferType = BufferType.SPANNABLE; // break; // case 2: // bufferType = BufferType.EDITABLE; // break; // } // } // // if (mEditor != null) mEditor.adjustInputType(password, passwordInputType, // webPasswordInputType, numberPasswordInputType); // // if (selectallonfocus) { // createEditorIfNeeded(); // mEditor.mSelectAllOnFocus = true; // // if (bufferType == BufferType.NORMAL) // bufferType = BufferType.SPANNABLE; // } // This call will save the initial left/right drawables this.setCompoundDrawablesWithIntrinsicBounds( drawableLeft, drawableTop, drawableRight, drawableBottom); this.setRelativeDrawablesIfNeeded(drawableStart, drawableEnd); this.setCompoundDrawablePadding(drawablePadding); // Same as setSingleLine(), but make sure the transformation method and the maximum number // of lines of height are unchanged for multi-line TextViews. this.setInputTypeSingleLine(singleLine); this.applySingleLine(singleLine, singleLine, singleLine); if (singleLine && this.getKeyListener() == null && ellipsize == null) { ellipsize = TextUtils.TruncateAt.END; // END } switch (ellipsize) { case TextUtils.TruncateAt.START: this.setEllipsize(TextUtils.TruncateAt.START); break; case TextUtils.TruncateAt.MIDDLE: this.setEllipsize(TextUtils.TruncateAt.MIDDLE); break; case TextUtils.TruncateAt.END: this.setEllipsize(TextUtils.TruncateAt.END); break; case TextUtils.TruncateAt.MARQUEE: // if (ViewConfiguration.get(context).isFadingMarqueeEnabled()) { // this.setHorizontalFadingEdgeEnabled(true); // this.mMarqueeFadeMode = MARQUEE_FADE_NORMAL; // } else { this.setHorizontalFadingEdgeEnabled(false); this.mMarqueeFadeMode = TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; // } this.setEllipsize(TextUtils.TruncateAt.MARQUEE); break; } this.setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000)); this.setHintTextColor(textColorHint); this.setLinkTextColor(textColorLink); if (textColorHighlight != 0) { this.setHighlightColor(textColorHighlight); } this.setRawTextSize(textSize); if (allCaps) { this.setTransformationMethod(new AllCapsTransformationMethod(this.getContext())); } // if (password || passwordInputType || webPasswordInputType || numberPasswordInputType) { // this.setTransformationMethod(android.text.method.PasswordTransformationMethod.PasswordTransformationMethod.getInstance()); // typefaceIndex = MONOSPACE; // } else if (mEditor != null && // (mEditor.mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION)) // == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { // typefaceIndex = MONOSPACE; // } // // setTypefaceFromAttrs(fontFamily, typefaceIndex, styleIndex); if (shadowcolor != 0) { this.setShadowLayer(r, dx, dy, shadowcolor); } // if (maxlength >= 0) { // this.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) }); // } else { // this.setFilters(TextView.NO_FILTERS); // } this.setText(text, bufferType); if (hint != null) this.setHint(hint); // /* // * Views are not normally focusable unless specified to be. // * However, TextViews that have input or movement methods *are* // * focusable by default. // */ // a = context.obtainStyledAttributes(attrs, // com.android.internal.R.styleable.View, // defStyle, 0); // // boolean focusable = mMovement != null || getKeyListener() != null; // boolean clickable = focusable; // boolean longClickable = focusable; // // n = a.getIndexCount(); // for (int i = 0; i < n; i++) { // int attr = a.getIndex(i); // // switch (attr) { // case com.android.internal.R.styleable.View_focusable: // focusable = a.getBoolean(attr, focusable); // break; // // case com.android.internal.R.styleable.View_clickable: // clickable = a.getBoolean(attr, clickable); // break; // // case com.android.internal.R.styleable.View_longClickable: // longClickable = a.getBoolean(attr, longClickable); // break; // } // } // a.recycle(); // // setFocusable(focusable); // setClickable(clickable); // setLongClickable(longClickable); // // if (mEditor != null) mEditor.prepareCursorControllers(); // // // If not explicitly specified this view is important for accessibility. // if (getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { // setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); // } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder() .set('textColorHighlight', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setHighlightColor(attrBinder.parseColor(value, v.mHighlightColor)); }, getter(v: TextView){ return v.getHighlightColor(); } }).set('textColor', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let color = attrBinder.parseColorList(value); if (color) v.setTextColor(color); }, getter(v: TextView){ return v.mTextColor; } }).set('textColorHint', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let color = attrBinder.parseColorList(value); if (color) v.setHintTextColor(color); }, getter(v: TextView){ return v.mHintTextColor; } }).set('textSize', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let size = attrBinder.parseNumberPixelSize(value, v.mTextPaint.getTextSize()); v.setTextSize(TypedValue.COMPLEX_UNIT_PX, size); }, getter(v: TextView){ return v.mTextPaint.getTextSize(); } }).set('textAllCaps', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setAllCaps(attrBinder.parseBoolean(value, true)); } }).set('shadowColor', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setShadowLayer(v.mShadowRadius, v.mShadowDx, v.mShadowDy, attrBinder.parseColor(value, v.mTextPaint.shadowColor)); }, getter(v: TextView){ return v.getShadowColor(); } }).set('shadowDx', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dx = attrBinder.parseNumberPixelSize(value, v.mShadowDx); v.setShadowLayer(v.mShadowRadius, dx, v.mShadowDy, v.mTextPaint.shadowColor); }, getter(v: TextView){ return v.getShadowDx(); } }).set('shadowDy', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dy = attrBinder.parseNumberPixelSize(value, v.mShadowDy); v.setShadowLayer(v.mShadowRadius, v.mShadowDx, dy, v.mTextPaint.shadowColor); }, getter(v: TextView){ return v.getShadowDy(); } }).set('shadowRadius', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let radius = attrBinder.parseNumberPixelSize(value, v.mShadowRadius); v.setShadowLayer(radius, v.mShadowDx, v.mShadowDy, v.mTextPaint.shadowColor); }, getter(v: TextView){ return v.getShadowRadius(); } }).set('drawableLeft', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dr = v.mDrawables || <TextView.Drawables>{}; let drawable = attrBinder.parseDrawable(value); v.setCompoundDrawablesWithIntrinsicBounds(drawable, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom); }, getter(v: TextView){ return v.getCompoundDrawables()[0]; } }).set('drawableStart', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dr = v.mDrawables || <TextView.Drawables>{}; let drawable = attrBinder.parseDrawable(value); v.setCompoundDrawablesWithIntrinsicBounds(drawable, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom); }, getter(v: TextView){ return v.getCompoundDrawables()[0]; } }).set('drawableTop', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dr = v.mDrawables || <TextView.Drawables>{}; let drawable = attrBinder.parseDrawable(value); v.setCompoundDrawablesWithIntrinsicBounds(dr.mDrawableLeft, drawable, dr.mDrawableRight, dr.mDrawableBottom); }, getter(v: TextView){ return v.getCompoundDrawables()[1]; } }).set('drawableRight', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dr = v.mDrawables || <TextView.Drawables>{}; let drawable = attrBinder.parseDrawable(value); v.setCompoundDrawablesWithIntrinsicBounds(dr.mDrawableLeft, dr.mDrawableTop, drawable, dr.mDrawableBottom); }, getter(v: TextView){ return v.getCompoundDrawables()[2]; } }).set('drawableEnd', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dr = v.mDrawables || <TextView.Drawables>{}; let drawable = attrBinder.parseDrawable(value); v.setCompoundDrawablesWithIntrinsicBounds(dr.mDrawableLeft, dr.mDrawableTop, drawable, dr.mDrawableBottom); }, getter(v: TextView){ return v.getCompoundDrawables()[2]; } }).set('drawableBottom', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let dr = v.mDrawables || <TextView.Drawables>{}; let drawable = attrBinder.parseDrawable(value); v.setCompoundDrawablesWithIntrinsicBounds(dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, drawable); }, getter(v: TextView){ return v.getCompoundDrawables()[3]; } }).set('drawablePadding', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setCompoundDrawablePadding(attrBinder.parseNumberPixelSize(value)); }, getter(v: TextView){ return v.getCompoundDrawablePadding(); } }).set('maxLines', { setter(v: TextView, value: any, attrBinder: AttrBinder) { value = Number.parseInt(value); if (Number.isInteger(value)) v.setMaxLines(value); }, getter(v: TextView){ return v.getMaxLines(); } }).set('maxHeight', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMaxHeight(attrBinder.parseNumberPixelSize(value, v.getMaxHeight())); }, getter(v: TextView){ return v.getMaxHeight(); } }).set('lines', { setter(v: TextView, value: any, attrBinder: AttrBinder) { value = Number.parseInt(value); if (Number.isInteger(value)) v.setLines(value); }, getter(v: TextView){ if (v.getMaxLines() === v.getMinLines()) return v.getMaxLines(); return null; } }).set('height', { setter(v: TextView, value: any, attrBinder: AttrBinder) { value = attrBinder.parseNumberPixelSize(value, -1); if (value >= 0) v.setHeight(value); }, getter(v: TextView){ if (v.getMaxHeight() === v.getMinimumHeight()) return v.getMaxHeight(); return null; } }).set('minLines', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMinLines(attrBinder.parseInt(value, v.getMinLines())); }, getter(v: TextView){ return v.getMinLines(); } }).set('minHeight', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMinHeight(attrBinder.parseNumberPixelSize(value, v.getMinHeight())); }, getter(v: TextView){ return v.getMinHeight(); } }).set('maxEms', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMaxEms(attrBinder.parseInt(value, v.getMaxEms())); }, getter(v: TextView){ return v.getMaxEms(); } }).set('maxWidth', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMaxWidth(attrBinder.parseNumberPixelSize(value, v.getMaxWidth())); }, getter(v: TextView){ return v.getMaxWidth(); } }).set('ems', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let ems = attrBinder.parseInt(value, null); if (ems != null) v.setEms(ems); }, getter(v: TextView){ if (v.getMinEms() === v.getMaxEms()) return v.getMaxEms(); return null; } }).set('width', { setter(v: TextView, value: any, attrBinder: AttrBinder) { value = attrBinder.parseNumberPixelSize(value, -1); if (value >= 0) v.setWidth(value); }, getter(v: TextView){ if (v.getMinWidth() === v.getMaxWidth()) return v.getMinWidth(); return null; } }).set('minEms', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMinEms(attrBinder.parseInt(value, v.getMinEms())); }, getter(v: TextView){ return v.getMinEms(); } }).set('minWidth', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setMinWidth(attrBinder.parseNumberPixelSize(value, v.getMinWidth())); }, getter(v: TextView){ return v.getMinWidth(); } }).set('gravity', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setGravity(attrBinder.parseGravity(value, v.mGravity)); }, getter(v: TextView){ return v.mGravity; } }).set('hint', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setHint(attrBinder.parseString(value)); }, getter(v: TextView){ return v.getHint(); } }).set('text', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setText(attrBinder.parseString(value)); }, getter(v: TextView){ return v.getText(); } }).set('scrollHorizontally', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setHorizontallyScrolling(attrBinder.parseBoolean(value, false)); } }).set('singleLine', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setSingleLine(attrBinder.parseBoolean(value, false)); } }).set('ellipsize', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let ellipsize = TextUtils.TruncateAt[(value + '').toUpperCase()]; if (ellipsize) v.setEllipsize(ellipsize); } }).set('marqueeRepeatLimit', { setter(v: TextView, value: any, attrBinder: AttrBinder) { let marqueeRepeatLimit = attrBinder.parseInt(value, -1); if (marqueeRepeatLimit >= 0) v.setMarqueeRepeatLimit(marqueeRepeatLimit); } }).set('includeFontPadding', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setIncludeFontPadding(attrBinder.parseBoolean(value, false)); } }).set('enabled', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setEnabled(attrBinder.parseBoolean(value, v.isEnabled())); }, getter(v: TextView){ return v.isEnabled(); } }).set('lineSpacingExtra', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setLineSpacing(attrBinder.parseNumberPixelSize(value, v.mSpacingAdd), v.mSpacingMult); }, getter(v: TextView){ return v.mSpacingAdd; } }).set('lineSpacingMultiplier', { setter(v: TextView, value: any, attrBinder: AttrBinder) { v.setLineSpacing(v.mSpacingAdd, attrBinder.parseFloat(value, v.mSpacingMult)); }, getter(v: TextView){ return v.mSpacingMult; } }); } private setTypefaceFromAttrs(familyName:string, typefaceIndex:number, styleIndex:number):void { //let tf:Typeface = null; //if (familyName != null) { // tf = Typeface.create(familyName, styleIndex); // if (tf != null) { // this.setTypeface(tf); // return; // } //} //switch(typefaceIndex) { // case TextView.SANS: // tf = Typeface.SANS_SERIF; // break; // case TextView.SERIF: // tf = Typeface.SERIF; // break; // case TextView.MONOSPACE: // tf = Typeface.MONOSPACE; // break; //} //this.setTypeface(tf, styleIndex); } private setRelativeDrawablesIfNeeded(start:Drawable, end:Drawable):void { let hasRelativeDrawables:boolean = (start != null) || (end != null); if (hasRelativeDrawables) { let dr:TextView.Drawables = this.mDrawables; if (dr == null) { this.mDrawables = dr = new TextView.Drawables(); } this.mDrawables.mOverride = true; const compoundRect:Rect = dr.mCompoundRect; let state:number[] = this.getDrawableState(); if (start != null) { start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); start.setState(state); start.copyBounds(compoundRect); start.setCallback(this); dr.mDrawableStart = start; dr.mDrawableSizeStart = compoundRect.width(); dr.mDrawableHeightStart = compoundRect.height(); } else { dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; } if (end != null) { end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); end.setState(state); end.copyBounds(compoundRect); end.setCallback(this); dr.mDrawableEnd = end; dr.mDrawableSizeEnd = compoundRect.width(); dr.mDrawableHeightEnd = compoundRect.height(); } else { dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; } this.resetResolvedDrawables(); this.resolveDrawables(); } } setEnabled(enabled:boolean):void { if (enabled == this.isEnabled()) { return; } //if (!enabled) { // // Hide the soft input if the currently active TextView is disabled // let imm:InputMethodManager = InputMethodManager.peekInstance(); // if (imm != null && imm.isActive(this)) { // imm.hideSoftInputFromWindow(this.getWindowToken(), 0); // } //} super.setEnabled(enabled); //if (enabled) { // // Make sure IME is updated with current editor info. // let imm:InputMethodManager = InputMethodManager.peekInstance(); // if (imm != null) // imm.restartInput(this); //} //// Will change text color //if (this.mEditor != null) { // this.mEditor.invalidateTextDisplayList(); // this.mEditor.prepareCursorControllers(); // // start or stop the cursor blinking as appropriate // this.mEditor.makeBlink(); //} } /** * Sets the typeface and style in which the text should be displayed, * and turns on the fake bold and italic bits in the Paint if the * Typeface that you provided does not have all the bits in the * style that you specified. * * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ setTypeface(tf:any, style:number):void { //if (style > 0) { // if (tf == null) { // tf = Typeface.defaultFromStyle(style); // } else { // tf = Typeface.create(tf, style); // } // this.setTypeface(tf); // // now compute what (if any) algorithmic styling is needed // let typefaceStyle:number = tf != null ? tf.getStyle() : 0; // let need:number = style & ~typefaceStyle; // this.mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); // this.mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25 : 0); //} else { // this.mTextPaint.setFakeBoldText(false); // this.mTextPaint.setTextSkewX(0); // this.setTypeface(tf); //} } /** * Subclasses override this to specify that they have a KeyListener * by default even if not specifically called for in the XML options. */ protected getDefaultEditable():boolean { return false; } /** * Subclasses override this to specify a default movement method. */ protected getDefaultMovementMethod():MovementMethod { return null; } /** * Return the text the TextView is displaying. If setText() was called with * an argument of TextView.BufferType.SPANNABLE or TextView.BufferType.EDITABLE, you can cast * the return value from this method to Spannable or Editable, respectively. * * Note: The content of the return value should not be modified. If you want * a modifiable one, you should make your own copy first. * * @attr ref android.R.styleable#TextView_text */ getText():String { return this.mText; } /** * Returns the length, in characters, of the text managed by this TextView */ length():number { return this.mText.length; } /** * Return the text the TextView is displaying as an Editable object. If * the text is not editable, null is returned. * * @see #getText */ getEditableText():any { return null; //return (this.mText instanceof Editable) ? <Editable> this.mText : null; } /** * @return the height of one standard line in pixels. Note that markup * within the text can cause individual lines to be taller or shorter * than this height, and the layout may contain additional first- * or last-line padding. */ getLineHeight():number { return Math.round(this.mTextPaint.getFontMetricsInt(null) * this.mSpacingMult + this.mSpacingAdd); } /** * @return the Layout that is currently being used to display the text. * This can be null if the text or width has recently changes. */ getLayout():Layout { return this.mLayout; } /** * @return the Layout that is currently being used to display the hint text. * This can be null. */ getHintLayout():Layout { return this.mHintLayout; } /** * Retrieve the {@link android.content.UndoManager} that is currently associated * with this TextView. By default there is no associated UndoManager, so null * is returned. One can be associated with the TextView through * {@link #setUndoManager(android.content.UndoManager, String)} * * @hide */ getUndoManager():any { return null; //return this.mEditor == null ? null : this.mEditor.mUndoManager; } /** * Associate an {@link android.content.UndoManager} with this TextView. Once * done, all edit operations on the TextView will result in appropriate * {@link android.content.UndoOperation} objects pushed on the given UndoManager's * stack. * * @param undoManager The {@link android.content.UndoManager} to associate with * this TextView, or null to clear any existing association. * @param tag String tag identifying this particular TextView owner in the * UndoManager. This is used to keep the correct association with the * {@link android.content.UndoOwner} of any operations inside of the UndoManager. * * @hide */ setUndoManager(undoManager:any, tag:string):void { //not support now //if (undoManager != null) { // this.createEditorIfNeeded(); // this.mEditor.mUndoManager = undoManager; // this.mEditor.mUndoOwner = undoManager.getOwner(tag, this); // this.mEditor.mUndoInputFilter = new Editor.UndoInputFilter(this.mEditor); // if (!(this.mText instanceof Editable)) { // this.setText(this.mText, TextView.BufferType.EDITABLE); // } // this.setFilters(<Editable> this.mText, this.mFilters); //} else if (this.mEditor != null) { // // XXX need to destroy all associated state. // this.mEditor.mUndoManager = null; // this.mEditor.mUndoOwner = null; // this.mEditor.mUndoInputFilter = null; //} } /** * @return the current key listener for this TextView. * This will frequently be null for non-EditText TextViews. * * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText */ getKeyListener():any { return null; //return this.mEditor == null ? null : this.mEditor.mKeyListener; } /** * Sets the key listener to be used with this TextView. This can be null * to disallow user input. Note that this method has significant and * subtle interactions with soft keyboards and other input method: * see {@link KeyListener#getInputType() KeyListener.getContentType()} * for important details. Calling this method will replace the current * content type of the text view with the content type returned by the * key listener. * <p> * Be warned that if you want a TextView with a key listener or movement * method not to be focusable, or if you want a TextView without a * key listener or movement method to be focusable, you must call * {@link #setFocusable} again after calling this to get the focusability * back the way you want it. * * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText */ setKeyListener(input:any):void { //not support //this.setKeyListenerOnly(input); //this.fixFocusableAndClickableSettings(); //if (input != null) { // this.createEditorIfNeeded(); // try { // this.mEditor.mInputType = this.mEditor.mKeyListener.getInputType(); // } catch (e){ // this.mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; // } // // Change inputType, without affecting transformation. // // No need to applySingleLine since mSingleLine is unchanged. // this.setInputTypeSingleLine(this.mSingleLine); //} else { // if (this.mEditor != null) // this.mEditor.mInputType = EditorInfo.TYPE_NULL; //} //let imm:InputMethodManager = InputMethodManager.peekInstance(); //if (imm != null) // imm.restartInput(this); } private setKeyListenerOnly(input:any):void { //not support // null is the default value //if (this.mEditor == null && input == null) // return; //this.createEditorIfNeeded(); //if (this.mEditor.mKeyListener != input) { // this.mEditor.mKeyListener = input; // if (input != null && !(this.mText instanceof Editable)) { // this.setText(this.mText); // } // this.setFilters(<Editable> this.mText, this.mFilters); //} } /** * @return the movement method being used for this TextView. * This will frequently be null for non-EditText TextViews. */ getMovementMethod():MovementMethod { return this.mMovement; } /** * Sets the movement method (arrow key handler) to be used for * this TextView. This can be null to disallow using the arrow keys * to move the cursor or scroll the view. * <p> * Be warned that if you want a TextView with a key listener or movement * method not to be focusable, or if you want a TextView without a * key listener or movement method to be focusable, you must call * {@link #setFocusable} again after calling this to get the focusability * back the way you want it. */ setMovementMethod(movement:MovementMethod):void { if (this.mMovement != movement) { this.mMovement = movement; if (movement != null && !Spannable.isImpl(this.mText)) { this.setText(this.mText); } this.fixFocusableAndClickableSettings(); // mMovement //if (this.mEditor != null) // this.mEditor.prepareCursorControllers(); } } private fixFocusableAndClickableSettings():void { if (this.mMovement != null //|| (this.mEditor != null && this.mEditor.mKeyListener != null) ) { this.setFocusable(true); this.setClickable(true); this.setLongClickable(true); } else { this.setFocusable(false); this.setClickable(false); this.setLongClickable(false); } } /** * @return the current transformation method for this TextView. * This will frequently be null except for single-line and password * fields. * * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine */ getTransformationMethod():TransformationMethod { return this.mTransformation; } /** * Sets the transformation that is applied to the text that this * TextView is displaying. * * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine */ setTransformationMethod(method:TransformationMethod):void { if (method == this.mTransformation) { // the same. return; } if (this.mTransformation != null) { if (Spannable.isImpl(this.mText)) { (<Spannable> this.mText).removeSpan(this.mTransformation); } } this.mTransformation = method; if (TransformationMethod2.isImpl(method)) { let method2:TransformationMethod2 = <TransformationMethod2> method; this.mAllowTransformationLengthChange = !this.isTextSelectable();// && !(this.mText instanceof Editable); method2.setLengthChangesAllowed(this.mAllowTransformationLengthChange); } else { this.mAllowTransformationLengthChange = false; } this.setText(this.mText); //if (this.hasPasswordTransformationMethod()) { // this.notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); //} } /** * Returns the top padding of the view, plus space for the top * Drawable if any. */ getCompoundPaddingTop():number { const dr:TextView.Drawables = this.mDrawables; if (dr == null || dr.mDrawableTop == null) { return this.mPaddingTop; } else { return this.mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop; } } /** * Returns the bottom padding of the view, plus space for the bottom * Drawable if any. */ getCompoundPaddingBottom():number { const dr:TextView.Drawables = this.mDrawables; if (dr == null || dr.mDrawableBottom == null) { return this.mPaddingBottom; } else { return this.mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom; } } /** * Returns the left padding of the view, plus space for the left * Drawable if any. */ getCompoundPaddingLeft():number { const dr:TextView.Drawables = this.mDrawables; if (dr == null || dr.mDrawableLeft == null) { return this.mPaddingLeft; } else { return this.mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft; } } /** * Returns the right padding of the view, plus space for the right * Drawable if any. */ getCompoundPaddingRight():number { const dr:TextView.Drawables = this.mDrawables; if (dr == null || dr.mDrawableRight == null) { return this.mPaddingRight; } else { return this.mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight; } } /** * Returns the start padding of the view, plus space for the start * Drawable if any. */ getCompoundPaddingStart():number { this.resolveDrawables(); //switch(this.getLayoutDirection()) { // default: // case TextView.LAYOUT_DIRECTION_LTR: return this.getCompoundPaddingLeft(); // case TextView.LAYOUT_DIRECTION_RTL: // return this.getCompoundPaddingRight(); //} } /** * Returns the end padding of the view, plus space for the end * Drawable if any. */ getCompoundPaddingEnd():number { this.resolveDrawables(); //switch(this.getLayoutDirection()) { // default: // case TextView.LAYOUT_DIRECTION_LTR: return this.getCompoundPaddingRight(); // case TextView.LAYOUT_DIRECTION_RTL: // return this.getCompoundPaddingLeft(); //} } /** * Returns the extended top padding of the view, including both the * top Drawable if any and any extra space to keep more than maxLines * of text from showing. It is only valid to call this after measuring. */ getExtendedPaddingTop():number { if (this.mMaxMode != TextView.LINES) { return this.getCompoundPaddingTop(); } if (this.mLayout.getLineCount() <= this.mMaximum) { return this.getCompoundPaddingTop(); } let top:number = this.getCompoundPaddingTop(); let bottom:number = this.getCompoundPaddingBottom(); let viewht:number = this.getHeight() - top - bottom; let layoutht:number = this.mLayout.getLineTop(this.mMaximum); if (layoutht >= viewht) { return top; } const gravity:number = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; if (gravity == Gravity.TOP) { return top; } else if (gravity == Gravity.BOTTOM) { return top + viewht - layoutht; } else { // (gravity == Gravity.CENTER_VERTICAL) return top + (viewht - layoutht) / 2; } } /** * Returns the extended bottom padding of the view, including both the * bottom Drawable if any and any extra space to keep more than maxLines * of text from showing. It is only valid to call this after measuring. */ getExtendedPaddingBottom():number { if (this.mMaxMode != TextView.LINES) { return this.getCompoundPaddingBottom(); } if (this.mLayout.getLineCount() <= this.mMaximum) { return this.getCompoundPaddingBottom(); } let top:number = this.getCompoundPaddingTop(); let bottom:number = this.getCompoundPaddingBottom(); let viewht:number = this.getHeight() - top - bottom; let layoutht:number = this.mLayout.getLineTop(this.mMaximum); if (layoutht >= viewht) { return bottom; } const gravity:number = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; if (gravity == Gravity.TOP) { return bottom + viewht - layoutht; } else if (gravity == Gravity.BOTTOM) { return bottom; } else { // (gravity == Gravity.CENTER_VERTICAL) return bottom + (viewht - layoutht) / 2; } } /** * Returns the total left padding of the view, including the left * Drawable if any. */ getTotalPaddingLeft():number { return this.getCompoundPaddingLeft(); } /** * Returns the total right padding of the view, including the right * Drawable if any. */ getTotalPaddingRight():number { return this.getCompoundPaddingRight(); } /** * Returns the total start padding of the view, including the start * Drawable if any. */ getTotalPaddingStart():number { return this.getCompoundPaddingStart(); } /** * Returns the total end padding of the view, including the end * Drawable if any. */ getTotalPaddingEnd():number { return this.getCompoundPaddingEnd(); } /** * Returns the total top padding of the view, including the top * Drawable if any, the extra space to keep more than maxLines * from showing, and the vertical offset for gravity, if any. */ getTotalPaddingTop():number { return this.getExtendedPaddingTop() + this.getVerticalOffset(true); } /** * Returns the total bottom padding of the view, including the bottom * Drawable if any, the extra space to keep more than maxLines * from showing, and the vertical offset for gravity, if any. */ getTotalPaddingBottom():number { return this.getExtendedPaddingBottom() + this.getBottomVerticalOffset(true); } /** * Sets the Drawables (if any) to appear to the left of, above, * to the right of, and below the text. Use null if you do not * want a Drawable there. The Drawables must already have had * {@link Drawable#setBounds} called. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ setCompoundDrawables(left:Drawable, top:Drawable, right:Drawable, bottom:Drawable):void { let dr:TextView.Drawables = this.mDrawables; const drawables:boolean = left != null || top != null || right != null || bottom != null; if (!drawables) { // Clearing drawables... can we free the data structure? if (dr != null) { if (dr.mDrawablePadding == 0) { this.mDrawables = null; } else { // out all of the fields in the existing structure. if (dr.mDrawableLeft != null){ dr.mDrawableLeft.setCallback(null); } dr.mDrawableLeft = null; if (dr.mDrawableTop != null){ dr.mDrawableTop.setCallback(null); } dr.mDrawableTop = null; if (dr.mDrawableRight != null){ dr.mDrawableRight.setCallback(null); } dr.mDrawableRight = null; if (dr.mDrawableBottom != null){ dr.mDrawableBottom.setCallback(null); } dr.mDrawableBottom = null; dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } } else { if (dr == null) { this.mDrawables = dr = new TextView.Drawables(); } this.mDrawables.mOverride = false; if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) { dr.mDrawableLeft.setCallback(null); } dr.mDrawableLeft = left; if (dr.mDrawableTop != top && dr.mDrawableTop != null) { dr.mDrawableTop.setCallback(null); } dr.mDrawableTop = top; if (dr.mDrawableRight != right && dr.mDrawableRight != null) { dr.mDrawableRight.setCallback(null); } dr.mDrawableRight = right; if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { dr.mDrawableBottom.setCallback(null); } dr.mDrawableBottom = bottom; const compoundRect:Rect = dr.mCompoundRect; let state:number[]; state = this.getDrawableState(); if (left != null) { left.setState(state); left.copyBounds(compoundRect); left.setCallback(this); dr.mDrawableSizeLeft = compoundRect.width(); dr.mDrawableHeightLeft = compoundRect.height(); } else { dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; } if (right != null) { right.setState(state); right.copyBounds(compoundRect); right.setCallback(this); dr.mDrawableSizeRight = compoundRect.width(); dr.mDrawableHeightRight = compoundRect.height(); } else { dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; } if (top != null) { top.setState(state); top.copyBounds(compoundRect); top.setCallback(this); dr.mDrawableSizeTop = compoundRect.height(); dr.mDrawableWidthTop = compoundRect.width(); } else { dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; } if (bottom != null) { bottom.setState(state); bottom.copyBounds(compoundRect); bottom.setCallback(this); dr.mDrawableSizeBottom = compoundRect.height(); dr.mDrawableWidthBottom = compoundRect.width(); } else { dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } // Save initial left/right drawables if (dr != null) { dr.mDrawableLeftInitial = left; dr.mDrawableRightInitial = right; } this.resetResolvedDrawables(); this.resolveDrawables(); this.invalidate(); this.requestLayout(); } /** * Sets the Drawables (if any) to appear to the left of, above, * to the right of, and below the text. Use null if you do not * want a Drawable there. The Drawables' bounds will be set to * their intrinsic bounds. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ setCompoundDrawablesWithIntrinsicBounds(left:Drawable, top:Drawable, right:Drawable, bottom:Drawable):void { if (left != null) { left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight()); } if (right != null) { right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight()); } if (top != null) { top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); } if (bottom != null) { bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); } this.setCompoundDrawables(left, top, right, bottom); } /** * Sets the Drawables (if any) to appear to the start of, above, * to the end of, and below the text. Use null if you do not * want a Drawable there. The Drawables must already have had * {@link Drawable#setBounds} called. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ setCompoundDrawablesRelative(start:Drawable, top:Drawable, end:Drawable, bottom:Drawable):void { let dr:TextView.Drawables = this.mDrawables; const drawables:boolean = start != null || top != null || end != null || bottom != null; if (!drawables) { // Clearing drawables... can we free the data structure? if (dr != null) { if (dr.mDrawablePadding == 0) { this.mDrawables = null; } else { // out all of the fields in the existing structure. if (dr.mDrawableStart != null){ dr.mDrawableStart.setCallback(null); } dr.mDrawableStart = null; if (dr.mDrawableTop != null){ dr.mDrawableTop.setCallback(null); } dr.mDrawableTop = null; if (dr.mDrawableEnd != null){ dr.mDrawableEnd.setCallback(null); } dr.mDrawableEnd = null; if (dr.mDrawableBottom != null){ dr.mDrawableBottom.setCallback(null); } dr.mDrawableBottom = null; dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } } else { if (dr == null) { this.mDrawables = dr = new TextView.Drawables(); } this.mDrawables.mOverride = true; if (dr.mDrawableStart != start && dr.mDrawableStart != null) { dr.mDrawableStart.setCallback(null); } dr.mDrawableStart = start; if (dr.mDrawableTop != top && dr.mDrawableTop != null) { dr.mDrawableTop.setCallback(null); } dr.mDrawableTop = top; if (dr.mDrawableEnd != end && dr.mDrawableEnd != null) { dr.mDrawableEnd.setCallback(null); } dr.mDrawableEnd = end; if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { dr.mDrawableBottom.setCallback(null); } dr.mDrawableBottom = bottom; const compoundRect:Rect = dr.mCompoundRect; let state:number[]; state = this.getDrawableState(); if (start != null) { start.setState(state); start.copyBounds(compoundRect); start.setCallback(this); dr.mDrawableSizeStart = compoundRect.width(); dr.mDrawableHeightStart = compoundRect.height(); } else { dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; } if (end != null) { end.setState(state); end.copyBounds(compoundRect); end.setCallback(this); dr.mDrawableSizeEnd = compoundRect.width(); dr.mDrawableHeightEnd = compoundRect.height(); } else { dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; } if (top != null) { top.setState(state); top.copyBounds(compoundRect); top.setCallback(this); dr.mDrawableSizeTop = compoundRect.height(); dr.mDrawableWidthTop = compoundRect.width(); } else { dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; } if (bottom != null) { bottom.setState(state); bottom.copyBounds(compoundRect); bottom.setCallback(this); dr.mDrawableSizeBottom = compoundRect.height(); dr.mDrawableWidthBottom = compoundRect.width(); } else { dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } this.resetResolvedDrawables(); this.resolveDrawables(); this.invalidate(); this.requestLayout(); } ///** // * Sets the Drawables (if any) to appear to the start of, above, // * to the end of, and below the text. Use 0 if you do not // * want a Drawable there. The Drawables' bounds will be set to // * their intrinsic bounds. // * // * @param start Resource identifier of the start Drawable. // * @param top Resource identifier of the top Drawable. // * @param end Resource identifier of the end Drawable. // * @param bottom Resource identifier of the bottom Drawable. // * // * @attr ref android.R.styleable#TextView_drawableStart // * @attr ref android.R.styleable#TextView_drawableTop // * @attr ref android.R.styleable#TextView_drawableEnd // * @attr ref android.R.styleable#TextView_drawableBottom // */ //setCompoundDrawablesRelativeWithIntrinsicBounds(start:number, top:number, end:number, bottom:number):void { // const resources:Resources = this.getResources(); // this.setCompoundDrawablesRelativeWithIntrinsicBounds(start != 0 ? resources.getDrawable(start) : null, top != 0 ? resources.getDrawable(top) : null, end != 0 ? resources.getDrawable(end) : null, bottom != 0 ? resources.getDrawable(bottom) : null); //} /** * Sets the Drawables (if any) to appear to the start of, above, * to the end of, and below the text. Use null if you do not * want a Drawable there. The Drawables' bounds will be set to * their intrinsic bounds. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ setCompoundDrawablesRelativeWithIntrinsicBounds(start:Drawable, top:Drawable, end:Drawable, bottom:Drawable):void { if (start != null) { start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); } if (end != null) { end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); } if (top != null) { top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); } if (bottom != null) { bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); } this.setCompoundDrawablesRelative(start, top, end, bottom); } /** * Returns drawables for the left, top, right, and bottom borders. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ getCompoundDrawables():Drawable[] { const dr:TextView.Drawables = this.mDrawables; if (dr != null) { return [ dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom ]; } else { return [ null, null, null, null ]; } } /** * Returns drawables for the start, top, end, and bottom borders. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ getCompoundDrawablesRelative():Drawable[] { const dr:TextView.Drawables = this.mDrawables; if (dr != null) { return [ dr.mDrawableStart, dr.mDrawableTop, dr.mDrawableEnd, dr.mDrawableBottom ]; } else { return [ null, null, null, null ]; } } /** * Sets the size of the padding between the compound drawables and * the text. * * @attr ref android.R.styleable#TextView_drawablePadding */ setCompoundDrawablePadding(pad:number):void { let dr:TextView.Drawables = this.mDrawables; if (pad == 0) { if (dr != null) { dr.mDrawablePadding = pad; } } else { if (dr == null) { this.mDrawables = dr = new TextView.Drawables(); } dr.mDrawablePadding = pad; } this.invalidate(); this.requestLayout(); } /** * Returns the padding between the compound drawables and the text. * * @attr ref android.R.styleable#TextView_drawablePadding */ getCompoundDrawablePadding():number { const dr:TextView.Drawables = this.mDrawables; return dr != null ? dr.mDrawablePadding : 0; } setPadding(left:number, top:number, right:number, bottom:number):void { if (left != this.mPaddingLeft || right != this.mPaddingRight || top != this.mPaddingTop || bottom != this.mPaddingBottom) { this.nullLayouts(); } // the super call will requestLayout() super.setPadding(left, top, right, bottom); this.invalidate(); } //setPaddingRelative(start:number, top:number, end:number, bottom:number):void { // if (start != this.getPaddingStart() || end != this.getPaddingEnd() || top != this.mPaddingTop || bottom != this.mPaddingBottom) { // this.nullLayouts(); // } // // the super call will requestLayout() // super.setPaddingRelative(start, top, end, bottom); // this.invalidate(); //} /** * Gets the autolink mask of the text. See {@link * android.text.util.Linkify#ALL Linkify.ALL} and peers for * possible values. * * @attr ref android.R.styleable#TextView_autoLink */ getAutoLinkMask():number { return this.mAutoLinkMask; } ///** // * Sets the text color, size, style, hint color, and highlight color // * from the specified TextAppearance resource. // */ //setTextAppearance(context:Context, resid:number):void { // let appearance:TypedArray = context.obtainStyledAttributes(resid, com.android.internal.R.styleable.TextAppearance); // let color:number; // let colors:ColorStateList; // let ts:number; // color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0); // if (color != 0) { // this.setHighlightColor(color); // } // colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColor); // if (colors != null) { // this.setTextColor(colors); // } // ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.TextAppearance_textSize, 0); // if (ts != 0) { // this.setRawTextSize(ts); // } // colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColorHint); // if (colors != null) { // this.setHintTextColor(colors); // } // colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColorLink); // if (colors != null) { // this.setLinkTextColor(colors); // } // let familyName:string; // let typefaceIndex:number, styleIndex:number; // familyName = appearance.getString(com.android.internal.R.styleable.TextAppearance_fontFamily); // typefaceIndex = appearance.getInt(com.android.internal.R.styleable.TextAppearance_typeface, -1); // styleIndex = appearance.getInt(com.android.internal.R.styleable.TextAppearance_textStyle, -1); // this.setTypefaceFromAttrs(familyName, typefaceIndex, styleIndex); // const shadowcolor:number = appearance.getInt(com.android.internal.R.styleable.TextAppearance_shadowColor, 0); // if (shadowcolor != 0) { // const dx:number = appearance.getFloat(com.android.internal.R.styleable.TextAppearance_shadowDx, 0); // const dy:number = appearance.getFloat(com.android.internal.R.styleable.TextAppearance_shadowDy, 0); // const r:number = appearance.getFloat(com.android.internal.R.styleable.TextAppearance_shadowRadius, 0); // this.setShadowLayer(r, dx, dy, shadowcolor); // } // if (appearance.getBoolean(com.android.internal.R.styleable.TextAppearance_textAllCaps, false)) { // this.setTransformationMethod(new AllCapsTransformationMethod()); // } // appearance.recycle(); //} /** * Get the default {@link Locale} of the text in this TextView. * @return the default {@link Locale} of the text in this TextView. */ getTextLocale():any { return null; //return this.mTextPaint.getTextLocale(); } /** * Set the default {@link Locale} of the text in this TextView to the given value. This value * is used to choose appropriate typefaces for ambiguous characters. Typically used for CJK * locales to disambiguate Hanzi/Kanji/Hanja characters. * * @param locale the {@link Locale} for drawing text, must not be null. * * @see Paint#setTextLocale */ setTextLocale(locale:any):void { //this.mTextPaint.setTextLocale(locale); } /** * @return the size (in pixels) of the default text size in this TextView. */ getTextSize():number { return this.mTextPaint.getTextSize(); } /** * Set the default text size to the given value, interpreted as "scaled * pixel" units. This size is adjusted based on the current density and * user font size preference. * * @param size The scaled pixel size. * * @attr ref android.R.styleable#TextView_textSize */ setTextSize(size:number):void; /** * Set the default text size to a given unit and value. See {@link * TypedValue} for the possible dimension units. * * @param unit The desired dimension unit. * @param size The desired size in the given units. * * @attr ref android.R.styleable#TextView_textSize */ setTextSize(unit:string, size:number):void; setTextSize(...args):void { if(args.length==1){ this.setTextSize(TypedValue.COMPLEX_UNIT_SP, <number>args[0]); return; } let [unit, size] = args; this.setRawTextSize(TypedValue.applyDimension(unit, size, this.getResources().getDisplayMetrics())); } protected setRawTextSize(size:number):void { if (size != this.mTextPaint.getTextSize()) { this.mTextPaint.setTextSize(size); if (this.mLayout != null) { this.nullLayouts(); this.requestLayout(); this.invalidate(); } } } /** * @return the extent by which text is currently being stretched * horizontally. This will usually be 1. */ getTextScaleX():number { return 1; //return this.mTextPaint.getTextScaleX(); } /** * Sets the extent by which text should be stretched horizontally. * * @attr ref android.R.styleable#TextView_textScaleX */ setTextScaleX(size:number):void { //if (size != this.mTextPaint.getTextScaleX()) { // this.mUserSetTextScaleX = true; // this.mTextPaint.setTextScaleX(size); // if (this.mLayout != null) { // this.nullLayouts(); // this.requestLayout(); // this.invalidate(); // } //} } ///** // * Sets the typeface and style in which the text should be displayed. // * Note that not all Typeface families actually have bold and italic // * variants, so you may need to use // * {@link #setTypeface(Typeface, int)} to get the appearance // * that you actually want. // * // * @see #getTypeface() // * // * @attr ref android.R.styleable#TextView_fontFamily // * @attr ref android.R.styleable#TextView_typeface // * @attr ref android.R.styleable#TextView_textStyle // */ //setTypeface(tf:any):void { // if (this.mTextPaint.getTypeface() != tf) { // this.mTextPaint.setTypeface(tf); // if (this.mLayout != null) { // this.nullLayouts(); // this.requestLayout(); // this.invalidate(); // } // } //} /** * @return the current typeface and style in which the text is being * displayed. * * @see #setTypeface(Typeface) * * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ getTypeface():any { return null;//TODO when Typeface impl //return this.mTextPaint.getTypeface(); } /** * Sets the text color. * * @see #setTextColor(int) * @see #getTextColors() * @see #setHintTextColor(ColorStateList) * @see #setLinkTextColor(ColorStateList) * * @attr ref android.R.styleable#TextView_textColor */ setTextColor(colors:ColorStateList|number):void { if(typeof colors === 'number'){ colors = ColorStateList.valueOf(<number>colors); } if (colors == null) { throw Error(`new NullPointerException()`); } this.mTextColor = <ColorStateList>colors; this.updateTextColors(); } /** * Gets the text colors for the different states (normal, selected, focused) of the TextView. * * @see #setTextColor(ColorStateList) * @see #setTextColor(int) * * @attr ref android.R.styleable#TextView_textColor */ getTextColors():ColorStateList { return this.mTextColor; } /** * <p>Return the current color selected for normal text.</p> * * @return Returns the current text color. */ getCurrentTextColor():number { return this.mCurTextColor; } /** * Sets the color used to display the selection highlight. * * @attr ref android.R.styleable#TextView_textColorHighlight */ setHighlightColor(color:number):void { if (this.mHighlightColor != color) { this.mHighlightColor = color; this.invalidate(); } } /** * @return the color used to display the selection highlight * * @see #setHighlightColor(int) * * @attr ref android.R.styleable#TextView_textColorHighlight */ getHighlightColor():number { return this.mHighlightColor; } /** * Sets whether the soft input method will be made visible when this * TextView gets focused. The default is true. * @hide */ setShowSoftInputOnFocus(show:boolean):void { this.createEditorIfNeeded(); //this.mEditor.mShowSoftInputOnFocus = show; } /** * Returns whether the soft input method will be made visible when this * TextView gets focused. The default is true. * @hide */ getShowSoftInputOnFocus():boolean { return false; // When there is no Editor, return default true value //return this.mEditor == null || this.mEditor.mShowSoftInputOnFocus; } /** * Gives the text a shadow of the specified radius and color, the specified * distance from its normal position. * * @attr ref android.R.styleable#TextView_shadowColor * @attr ref android.R.styleable#TextView_shadowDx * @attr ref android.R.styleable#TextView_shadowDy * @attr ref android.R.styleable#TextView_shadowRadius */ setShadowLayer(radius:number, dx:number, dy:number, color:number):void { this.mTextPaint.setShadowLayer(radius, dx, dy, color); this.mShadowRadius = radius; this.mShadowDx = dx; this.mShadowDy = dy; // Will change text clip region //if (this.mEditor != null) // this.mEditor.invalidateTextDisplayList(); this.invalidate(); } /** * Gets the radius of the shadow layer. * * @return the radius of the shadow layer. If 0, the shadow layer is not visible * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowRadius */ getShadowRadius():number { return this.mShadowRadius; } /** * @return the horizontal offset of the shadow layer * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowDx */ getShadowDx():number { return this.mShadowDx; } /** * @return the vertical offset of the shadow layer * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowDy */ getShadowDy():number { return this.mShadowDy; } /** * @return the color of the shadow layer * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowColor */ getShadowColor():number { return this.mTextPaint.shadowColor; } /** * @return the base paint used for the text. Please use this only to * consult the Paint's properties and not to change them. */ getPaint():TextPaint { return this.mTextPaint; } /** * Sets the autolink mask of the text. See {@link * android.text.util.Linkify#ALL Linkify.ALL} and peers for * possible values. * * @attr ref android.R.styleable#TextView_autoLink */ setAutoLinkMask(mask:number):void { this.mAutoLinkMask = mask; } /** * Sets whether the movement method will automatically be set to * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been * set to nonzero and links are detected in {@link #setText}. * The default is true. * * @attr ref android.R.styleable#TextView_linksClickable */ setLinksClickable(whether:boolean):void { this.mLinksClickable = whether; } /** * Returns whether the movement method will automatically be set to * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been * set to nonzero and links are detected in {@link #setText}. * The default is true. * * @attr ref android.R.styleable#TextView_linksClickable */ getLinksClickable():boolean { return this.mLinksClickable; } /** * Returns the list of URLSpans attached to the text * (by {@link Linkify} or otherwise) if any. You can call * {@link URLSpan#getURL} on them to find where they link to * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd} * to find the region of the text they are attached to. */ getUrls():any[] { //if (this.mText instanceof Spanned) { // return (<Spanned> this.mText).getSpans(0, this.mText.length(), URLSpan.class); //} else { return new Array<any>(0); //} } /** * Sets the color of the hint text. * * @see #getHintTextColors() * @see #setHintTextColor(int) * @see #setTextColor(ColorStateList) * @see #setLinkTextColor(ColorStateList) * * @attr ref android.R.styleable#TextView_textColorHint */ setHintTextColor(colors:ColorStateList|number):void { if(typeof colors === 'number'){ colors = ColorStateList.valueOf(<number>colors); } this.mHintTextColor = <ColorStateList>colors; this.updateTextColors(); } /** * @return the color of the hint text, for the different states of this TextView. * * @see #setHintTextColor(ColorStateList) * @see #setHintTextColor(int) * @see #setTextColor(ColorStateList) * @see #setLinkTextColor(ColorStateList) * * @attr ref android.R.styleable#TextView_textColorHint */ getHintTextColors():ColorStateList { return this.mHintTextColor; } /** * <p>Return the current color selected to paint the hint text.</p> * * @return Returns the current hint text color. */ getCurrentHintTextColor():number { return this.mHintTextColor != null ? this.mCurHintTextColor : this.mCurTextColor; } /** * Sets the color of links in the text. * * @see #setLinkTextColor(int) * @see #getLinkTextColors() * @see #setTextColor(ColorStateList) * @see #setHintTextColor(ColorStateList) * * @attr ref android.R.styleable#TextView_textColorLink */ setLinkTextColor(colors: number|ColorStateList): void { if (typeof colors === 'number') { colors = ColorStateList.valueOf(<number>colors); } this.mLinkTextColor = <ColorStateList>colors; this.updateTextColors(); } /** * @return the list of colors used to paint the links in the text, for the different states of * this TextView * * @see #setLinkTextColor(ColorStateList) * @see #setLinkTextColor(int) * * @attr ref android.R.styleable#TextView_textColorLink */ getLinkTextColors():ColorStateList { return this.mLinkTextColor; } /** * Sets the horizontal alignment of the text and the * vertical gravity that will be used when there is extra space * in the TextView beyond what is required for the text itself. * * @see android.view.Gravity * @attr ref android.R.styleable#TextView_gravity */ setGravity(gravity:number):void { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.LEFT; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { gravity |= Gravity.TOP; } let newLayout:boolean = false; if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) != (this.mGravity & Gravity.HORIZONTAL_GRAVITY_MASK)) { newLayout = true; } if (gravity != this.mGravity) { this.invalidate(); } this.mGravity = gravity; if (this.mLayout != null && newLayout) { // XXX this is heavy-handed because no actual content changes. let want:number = this.mLayout.getWidth(); let hintWant:number = this.mHintLayout == null ? 0 : this.mHintLayout.getWidth(); this.makeNewLayout(want, hintWant, TextView.UNKNOWN_BORING, TextView.UNKNOWN_BORING, this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(), true); } } /** * Returns the horizontal and vertical alignment of this TextView. * * @see android.view.Gravity * @attr ref android.R.styleable#TextView_gravity */ getGravity():number { return this.mGravity; } /** * @return the flags on the Paint being used to display the text. * @see Paint#getFlags */ getPaintFlags():number { return this.mTextPaint.getFlags(); } /** * Sets flags on the Paint being used to display the text and * reflows the text if they are different from the old flags. * @see Paint#setFlags */ setPaintFlags(flags:number):void { if (this.mTextPaint.getFlags() != flags) { this.mTextPaint.setFlags(flags); if (this.mLayout != null) { this.nullLayouts(); this.requestLayout(); this.invalidate(); } } } /** * Sets whether the text should be allowed to be wider than the * View is. If false, it will be wrapped to the width of the View. * * @attr ref android.R.styleable#TextView_scrollHorizontally */ setHorizontallyScrolling(whether:boolean):void { if (this.mHorizontallyScrolling != whether) { this.mHorizontallyScrolling = whether; if (this.mLayout != null) { this.nullLayouts(); this.requestLayout(); this.invalidate(); } } } /** * Returns whether the text is allowed to be wider than the View is. * If false, the text will be wrapped to the width of the View. * * @attr ref android.R.styleable#TextView_scrollHorizontally * @hide */ getHorizontallyScrolling():boolean { return this.mHorizontallyScrolling; } /** * Makes the TextView at least this many lines tall. * * Setting this value overrides any other (minimum) height setting. A single line TextView will * set this value to 1. * * @see #getMinLines() * * @attr ref android.R.styleable#TextView_minLines */ setMinLines(minlines:number):void { this.mMinimum = minlines; this.mMinMode = TextView.LINES; this.requestLayout(); this.invalidate(); } /** * @return the minimum number of lines displayed in this TextView, or -1 if the minimum * height was set in pixels instead using {@link #setMinHeight(int) or #setHeight(int)}. * * @see #setMinLines(int) * * @attr ref android.R.styleable#TextView_minLines */ getMinLines():number { return this.mMinMode == TextView.LINES ? this.mMinimum : -1; } /** * Makes the TextView at least this many pixels tall. * * Setting this value overrides any other (minimum) number of lines setting. * * @attr ref android.R.styleable#TextView_minHeight */ setMinHeight(minHeight:number):void { this.mMinimum = minHeight; this.mMinMode = TextView.PIXELS; this.requestLayout(); this.invalidate(); } /** * @return the minimum height of this TextView expressed in pixels, or -1 if the minimum * height was set in number of lines instead using {@link #setMinLines(int) or #setLines(int)}. * * @see #setMinHeight(int) * * @attr ref android.R.styleable#TextView_minHeight */ getMinHeight():number { return this.mMinMode == TextView.PIXELS ? this.mMinimum : -1; } /** * Makes the TextView at most this many lines tall. * * Setting this value overrides any other (maximum) height setting. * * @attr ref android.R.styleable#TextView_maxLines */ setMaxLines(maxlines:number):void { this.mMaximum = maxlines; this.mMaxMode = TextView.LINES; this.requestLayout(); this.invalidate(); } /** * @return the maximum number of lines displayed in this TextView, or -1 if the maximum * height was set in pixels instead using {@link #setMaxHeight(int) or #setHeight(int)}. * * @see #setMaxLines(int) * * @attr ref android.R.styleable#TextView_maxLines */ getMaxLines():number { return this.mMaxMode == TextView.LINES ? this.mMaximum : -1; } /** * Makes the TextView at most this many pixels tall. This option is mutually exclusive with the * {@link #setMaxLines(int)} method. * * Setting this value overrides any other (maximum) number of lines setting. * * @attr ref android.R.styleable#TextView_maxHeight */ setMaxHeight(maxHeight:number):void { this.mMaximum = maxHeight; this.mMaxMode = TextView.PIXELS; this.requestLayout(); this.invalidate(); } /** * @return the maximum height of this TextView expressed in pixels, or -1 if the maximum * height was set in number of lines instead using {@link #setMaxLines(int) or #setLines(int)}. * * @see #setMaxHeight(int) * * @attr ref android.R.styleable#TextView_maxHeight */ getMaxHeight():number { return this.mMaxMode == TextView.PIXELS ? this.mMaximum : -1; } /** * Makes the TextView exactly this many lines tall. * * Note that setting this value overrides any other (minimum / maximum) number of lines or * height setting. A single line TextView will set this value to 1. * * @attr ref android.R.styleable#TextView_lines */ setLines(lines:number):void { this.mMaximum = this.mMinimum = lines; this.mMaxMode = this.mMinMode = TextView.LINES; this.requestLayout(); this.invalidate(); } /** * Makes the TextView exactly this many pixels tall. * You could do the same thing by specifying this number in the * LayoutParams. * * Note that setting this value overrides any other (minimum / maximum) number of lines or * height setting. * * @attr ref android.R.styleable#TextView_height */ setHeight(pixels:number):void { this.mMaximum = this.mMinimum = pixels; this.mMaxMode = this.mMinMode = TextView.PIXELS; this.requestLayout(); this.invalidate(); } /** * Makes the TextView at least this many ems wide * * @attr ref android.R.styleable#TextView_minEms */ setMinEms(minems:number):void { this.mMinWidthValue = minems; this.mMinWidthMode = TextView.EMS; this.requestLayout(); this.invalidate(); } /** * @return the minimum width of the TextView, expressed in ems or -1 if the minimum width * was set in pixels instead (using {@link #setMinWidth(int)} or {@link #setWidth(int)}). * * @see #setMinEms(int) * @see #setEms(int) * * @attr ref android.R.styleable#TextView_minEms */ getMinEms():number { return this.mMinWidthMode == TextView.EMS ? this.mMinWidthValue : -1; } /** * Makes the TextView at least this many pixels wide * * @attr ref android.R.styleable#TextView_minWidth */ setMinWidth(minpixels:number):void { this.mMinWidthValue = minpixels; this.mMinWidthMode = TextView.PIXELS; this.requestLayout(); this.invalidate(); } /** * @return the minimum width of the TextView, in pixels or -1 if the minimum width * was set in ems instead (using {@link #setMinEms(int)} or {@link #setEms(int)}). * * @see #setMinWidth(int) * @see #setWidth(int) * * @attr ref android.R.styleable#TextView_minWidth */ getMinWidth():number { return this.mMinWidthMode == TextView.PIXELS ? this.mMinWidthValue : -1; } /** * Makes the TextView at most this many ems wide * * @attr ref android.R.styleable#TextView_maxEms */ setMaxEms(maxems:number):void { this.mMaxWidthValue = maxems; this.mMaxWidthMode = TextView.EMS; this.requestLayout(); this.invalidate(); } /** * @return the maximum width of the TextView, expressed in ems or -1 if the maximum width * was set in pixels instead (using {@link #setMaxWidth(int)} or {@link #setWidth(int)}). * * @see #setMaxEms(int) * @see #setEms(int) * * @attr ref android.R.styleable#TextView_maxEms */ getMaxEms():number { return this.mMaxWidthMode == TextView.EMS ? this.mMaxWidthValue : -1; } /** * Makes the TextView at most this many pixels wide * * @attr ref android.R.styleable#TextView_maxWidth */ setMaxWidth(maxpixels:number):void { this.mMaxWidthValue = maxpixels; this.mMaxWidthMode = TextView.PIXELS; this.requestLayout(); this.invalidate(); } /** * @return the maximum width of the TextView, in pixels or -1 if the maximum width * was set in ems instead (using {@link #setMaxEms(int)} or {@link #setEms(int)}). * * @see #setMaxWidth(int) * @see #setWidth(int) * * @attr ref android.R.styleable#TextView_maxWidth */ getMaxWidth():number { return this.mMaxWidthMode == TextView.PIXELS ? this.mMaxWidthValue : -1; } /** * Makes the TextView exactly this many ems wide * * @see #setMaxEms(int) * @see #setMinEms(int) * @see #getMinEms() * @see #getMaxEms() * * @attr ref android.R.styleable#TextView_ems */ setEms(ems:number):void { this.mMaxWidthValue = this.mMinWidthValue = ems; this.mMaxWidthMode = this.mMinWidthMode = TextView.EMS; this.requestLayout(); this.invalidate(); } /** * Makes the TextView exactly this many pixels wide. * You could do the same thing by specifying this number in the * LayoutParams. * * @see #setMaxWidth(int) * @see #setMinWidth(int) * @see #getMinWidth() * @see #getMaxWidth() * * @attr ref android.R.styleable#TextView_width */ setWidth(pixels:number):void { this.mMaxWidthValue = this.mMinWidthValue = pixels; this.mMaxWidthMode = this.mMinWidthMode = TextView.PIXELS; this.requestLayout(); this.invalidate(); } /** * Sets line spacing for this TextView. Each line will have its height * multiplied by <code>mult</code> and have <code>add</code> added to it. * * @attr ref android.R.styleable#TextView_lineSpacingExtra * @attr ref android.R.styleable#TextView_lineSpacingMultiplier */ setLineSpacing(add:number, mult:number):void { if (this.mSpacingAdd != add || this.mSpacingMult != mult) { this.mSpacingAdd = add; this.mSpacingMult = mult; if (this.mLayout != null) { this.nullLayouts(); this.requestLayout(); this.invalidate(); } } } /** * Gets the line spacing multiplier * * @return the value by which each line's height is multiplied to get its actual height. * * @see #setLineSpacing(float, float) * @see #getLineSpacingExtra() * * @attr ref android.R.styleable#TextView_lineSpacingMultiplier */ getLineSpacingMultiplier():number { return this.mSpacingMult; } /** * Gets the line spacing extra space * * @return the extra space that is added to the height of each lines of this TextView. * * @see #setLineSpacing(float, float) * @see #getLineSpacingMultiplier() * * @attr ref android.R.styleable#TextView_lineSpacingExtra */ getLineSpacingExtra():number { return this.mSpacingAdd; } ///** // * Convenience method: Append the specified text slice to the TextView's // * display buffer, upgrading it to TextView.BufferType.EDITABLE if it was // * not already editable. // */ //append(text:String, start=0, end=text.length):void { // if (!(this.mText instanceof Editable)) { // this.setText(this.mText, TextView.BufferType.EDITABLE); // } // (<Editable> this.mText).append(text, start, end); //} protected updateTextColors():void { let inval:boolean = false; let color:number = this.mTextColor.getColorForState(this.getDrawableState(), 0); if (color != this.mCurTextColor) { this.mCurTextColor = color; inval = true; } if (this.mLinkTextColor != null) { color = this.mLinkTextColor.getColorForState(this.getDrawableState(), 0); if (color != this.mTextPaint.linkColor) { this.mTextPaint.linkColor = color; inval = true; } } if (this.mHintTextColor != null) { color = this.mHintTextColor.getColorForState(this.getDrawableState(), 0); if (color != this.mCurHintTextColor && this.mText.length == 0) { this.mCurHintTextColor = color; inval = true; } } if (inval) { // Text needs to be redrawn with the new color //if (this.mEditor != null) // this.mEditor.invalidateTextDisplayList(); this.invalidate(); } } protected drawableStateChanged():void { super.drawableStateChanged(); if (this.mTextColor != null && this.mTextColor.isStateful() || (this.mHintTextColor != null && this.mHintTextColor.isStateful()) || (this.mLinkTextColor != null && this.mLinkTextColor.isStateful())) { this.updateTextColors(); } const dr:TextView.Drawables = this.mDrawables; if (dr != null) { let state:number[] = this.getDrawableState(); if (dr.mDrawableTop != null && dr.mDrawableTop.isStateful()) { dr.mDrawableTop.setState(state); } if (dr.mDrawableBottom != null && dr.mDrawableBottom.isStateful()) { dr.mDrawableBottom.setState(state); } if (dr.mDrawableLeft != null && dr.mDrawableLeft.isStateful()) { dr.mDrawableLeft.setState(state); } if (dr.mDrawableRight != null && dr.mDrawableRight.isStateful()) { dr.mDrawableRight.setState(state); } if (dr.mDrawableStart != null && dr.mDrawableStart.isStateful()) { dr.mDrawableStart.setState(state); } if (dr.mDrawableEnd != null && dr.mDrawableEnd.isStateful()) { dr.mDrawableEnd.setState(state); } } } //onSaveInstanceState():Parcelable { // let superState:Parcelable = super.onSaveInstanceState(); // // Save state if we are forced to // let save:boolean = this.mFreezesText; // let start:number = 0; // let end:number = 0; // if (this.mText != null) { // start = this.getSelectionStart(); // end = this.getSelectionEnd(); // if (start >= 0 || end >= 0) { // // Or save state if there is a selection // save = true; // } // } // if (save) { // let ss:TextView.SavedState = new TextView.SavedState(superState); // // XXX Should also save the current scroll position! // ss.selStart = start; // ss.selEnd = end; // if (this.mText instanceof Spanned) { // let sp:Spannable = new SpannableStringBuilder(this.mText); // if (this.mEditor != null) { // this.removeMisspelledSpans(sp); // sp.removeSpan(this.mEditor.mSuggestionRangeSpan); // } // ss.text = sp; // } else { // ss.text = this.mText.toString(); // } // if (this.isFocused() && start >= 0 && end >= 0) { // ss.frozenWithFocus = true; // } // ss.error = this.getError(); // return ss; // } // return superState; //} removeMisspelledSpans(spannable:Spannable):void { //let suggestionSpans:SuggestionSpan[] = spannable.getSpans(0, spannable.length(), SuggestionSpan.class); //for (let i:number = 0; i < suggestionSpans.length; i++) { // let flags:number = suggestionSpans[i].getFlags(); // if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) { // spannable.removeSpan(suggestionSpans[i]); // } //} } //onRestoreInstanceState(state:Parcelable):void { // if (!(state instanceof TextView.SavedState)) { // super.onRestoreInstanceState(state); // return; // } // let ss:TextView.SavedState = <TextView.SavedState> state; // super.onRestoreInstanceState(ss.getSuperState()); // // XXX restore buffer type too, as well as lots of other stuff // if (ss.text != null) { // this.setText(ss.text); // } // if (ss.selStart >= 0 && ss.selEnd >= 0) { // if (this.mText instanceof Spannable) { // let len:number = this.mText.length(); // if (ss.selStart > len || ss.selEnd > len) { // let restored:string = ""; // if (ss.text != null) { // restored = "(restored) "; // } // Log.e(TextView.LOG_TAG, "Saved cursor position " + ss.selStart + "/" + ss.selEnd + " out of range for " + restored + "text " + this.mText); // } else { // Selection.setSelection(<Spannable> this.mText, ss.selStart, ss.selEnd); // if (ss.frozenWithFocus) { // this.createEditorIfNeeded(); // this.mEditor.mFrozenWithFocus = true; // } // } // } // } // if (ss.error != null) { // const error:CharSequence = ss.error; // // Display the error later, after the first layout pass // this.post((()=>{ // const inner_this=this; // class _Inner extends Runnable { // // run():void { // inner_this.setError(error); // } // } // return new _Inner(); // })()); // } //} /** * Control whether this text view saves its entire text contents when * freezing to an icicle, in addition to dynamic state such as cursor * position. By default this is false, not saving the text. Set to true * if the text in the text view is not being saved somewhere else in * persistent storage (such as in a content provider) so that if the * view is later thawed the user will not lose their data. * * @param freezesText Controls whether a frozen icicle should include the * entire text data: true to include it, false to not. * * @attr ref android.R.styleable#TextView_freezesText */ setFreezesText(freezesText:boolean):void { this.mFreezesText = freezesText; } /** * Return whether this text view is including its entire text contents * in frozen icicles. * * @return Returns true if text is included, false if it isn't. * * @see #setFreezesText */ getFreezesText():boolean { return this.mFreezesText; } /////////////////////////////////////////////////////////////////////////// ///** // * Sets the Factory used to create new Editables. // */ //setEditableFactory(factory:Editable.Factory):void { // this.mEditableFactory = factory; // this.setText(this.mText); //} /** * Sets the Factory used to create new Spannables. */ setSpannableFactory(factory:Spannable.Factory):void { this.mSpannableFactory = factory; this.setText(this.mText); } /** * Like {@link #setText(CharSequence)}, * except that the cursor position (if any) is retained in the new text. * * @param text The new text to place in the text view. * * @see #setText(CharSequence) */ //setTextKeepState(text:CharSequence):void { // this.setTextKeepState(text, this.mBufferType); //} setText(text:String, type=this.mBufferType, notifyBefore=true, oldlen=0):void { if (text == null) { text = ""; } // If suggestions are not enabled, remove the suggestion spans from the text if (!this.isSuggestionsEnabled()) { text = this.removeSuggestionSpans(text); } //if (!this.mUserSetTextScaleX) this.mTextPaint.setTextScaleX(1.0); if (Spanned.isImplements(text) && (<Spanned> text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) { //if (ViewConfiguration.get().isFadingMarqueeEnabled()) { this.setHorizontalFadingEdgeEnabled(true); this.mMarqueeFadeMode = TextView.MARQUEE_FADE_NORMAL; //} else { // this.setHorizontalFadingEdgeEnabled(false); // this.mMarqueeFadeMode = TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; //} this.setEllipsize(TextUtils.TruncateAt.MARQUEE); } //let n:number = this.mFilters.length;//TODO when filter impl //for (let i:number = 0; i < n; i++) { // let out:CharSequence = this.mFilters[i].filter(text, 0, text.length(), TextView.EMPTY_SPANNED, 0, 0); // if (out != null) { // text = out; // } //} if (notifyBefore) { if (this.mText != null) { oldlen = this.mText.length; this.sendBeforeTextChanged(this.mText, 0, oldlen, text.length); } else { this.sendBeforeTextChanged("", 0, 0, text.length); } } let needEditableForNotification:boolean = false; if (this.mListeners != null && this.mListeners.size() != 0) { needEditableForNotification = true; } //if (type == TextView.BufferType.EDITABLE || this.getKeyListener() != null || needEditableForNotification) { // this.createEditorIfNeeded(); // let t:Editable = this.mEditableFactory.newEditable(text); // text = t; // this.setFilters(t, this.mFilters); // let imm:InputMethodManager = InputMethodManager.peekInstance(); // if (imm != null) // imm.restartInput(this); // // } else if (type == TextView.BufferType.SPANNABLE || this.mMovement != null) { text = this.mSpannableFactory.newSpannable(text); } //else if (!(text instanceof TextView.CharWrapper)) { // text = TextUtils.stringOrSpannedString(text); //} //if (this.mAutoLinkMask != 0) { // let s2:Spannable; // if (type == TextView.BufferType.EDITABLE || text instanceof Spannable) { // s2 = <Spannable> text; // } else { // s2 = this.mSpannableFactory.newSpannable(text); // } // if (Linkify.addLinks(s2, this.mAutoLinkMask)) { // text = s2; // type = (type == TextView.BufferType.EDITABLE) ? TextView.BufferType.EDITABLE : TextView.BufferType.SPANNABLE; // /* // * We must go ahead and set the text before changing the // * movement method, because setMovementMethod() may call // * setText() again to try to upgrade the buffer type. // */ // this.mText = text; // // would prevent an arbitrary cursor displacement. // if (this.mLinksClickable && !this.textCanBeSelected()) { // this.setMovementMethod(LinkMovementMethod.getInstance()); // } // } //} this.mBufferType = type; this.mText = text; if (this.mTransformation == null) { this.mTransformed = text; } else { this.mTransformed = this.mTransformation.getTransformation(text, this); } const textLength:number = text.length; //if (Spannable.isImpl(text) && !this.mAllowTransformationLengthChange) { // let sp:Spannable = <Spannable> text; // // Remove any ChangeWatchers that might have come from other TextViews. // const watchers:TextView.ChangeWatcher[] = sp.getSpans(0, sp.length, TextView.ChangeWatcher.type); // const count:number = watchers.length; // for (let i:number = 0; i < count; i++) { // sp.removeSpan(watchers[i]); // } // if (this.mChangeWatcher == null) // this.mChangeWatcher = new TextView.ChangeWatcher(this); // sp.setSpan(this.mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE | (TextView.CHANGE_WATCHER_PRIORITY << Spanned.SPAN_PRIORITY_SHIFT)); // //if (this.mEditor != null) this.mEditor.addSpanWatchers(sp); // if (this.mTransformation != null) { // sp.setSpan(this.mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // } // if (this.mMovement != null) { // this.mMovement.initialize(this, <Spannable> text); // /* // * Initializing the movement method will have set the // * selection, so reset mSelectionMoved to keep that from // * interfering with the normal on-focus selection-setting. // */ // //if (this.mEditor != null) // // this.mEditor.mSelectionMoved = false; // } //} if (this.mLayout != null) { this.checkForRelayout(); } this.sendOnTextChanged(text, 0, oldlen, textLength); this.onTextChanged(text, 0, oldlen, textLength); //this.notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT); //if (needEditableForNotification) { // this.sendAfterTextChanged(<Editable> text); //} // SelectionModifierCursorController depends on textCanBeSelected, which depends on text //if (this.mEditor != null) // this.mEditor.prepareCursorControllers(); } /** * Sets the TextView to display the specified slice of the specified * char array. You must promise that you will not change the contents * of the array except for right before another call to setText(), * since the TextView has no way to know that the text * has changed and that it needs to invalidate and re-layout. */ //setText(text:string[], start:number, len:number):void { // let oldlen:number = 0; // if (start < 0 || len < 0 || start + len > text.length) { // throw Error(`new IndexOutOfBoundsException(start + ", " + len)`); // } // /* // * We must do the before-notification here ourselves because if // * the old text is a CharWrapper we destroy it before calling // * into the normal path. // */ // if (this.mText != null) { // oldlen = this.mText.length(); // this.sendBeforeTextChanged(this.mText, 0, oldlen, len); // } else { // this.sendBeforeTextChanged("", 0, 0, len); // } // if (this.mCharWrapper == null) { // this.mCharWrapper = new TextView.CharWrapper(text, start, len); // } else { // this.mCharWrapper.set(text, start, len); // } // this.setText(this.mCharWrapper, this.mBufferType, false, oldlen); //} ///** // * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)}, // * except that the cursor position (if any) is retained in the new text. // * // * @see #setText(CharSequence, android.widget.TextView.BufferType) // */ //setTextKeepState(text:CharSequence, type:TextView.BufferType):void { // let start:number = this.getSelectionStart(); // let end:number = this.getSelectionEnd(); // let len:number = text.length(); // this.setText(text, type); // if (start >= 0 || end >= 0) { // if (this.mText instanceof Spannable) { // Selection.setSelection(<Spannable> this.mText, Math.max(0, Math.min(start, len)), Math.max(0, Math.min(end, len))); // } // } //} /** * Sets the text to be displayed when the text of the TextView is empty. * Null means to use the normal empty text. The hint does not currently * participate in determining the size of the view. * * @attr ref android.R.styleable#TextView_hint */ setHint(hint:String):void { this.mHint = hint;//TextUtils.stringOrSpannedString(hint); if (this.mLayout != null) { this.checkForRelayout(); } if (this.mText.length == 0) { this.invalidate(); } // Invalidate display list if hint is currently used //if (this.mEditor != null && this.mText.length() == 0 && this.mHint != null) { // this.mEditor.invalidateTextDisplayList(); //} } /** * Returns the hint that is displayed when the text of the TextView * is empty. * * @attr ref android.R.styleable#TextView_hint */ getHint():String { return this.mHint; } isSingleLine():boolean { return this.mSingleLine; } private static isMultilineInputType(type:number):boolean { return true; //return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); } /** * Removes the suggestion spans. */ removeSuggestionSpans(text:String):String { //if (text instanceof Spanned) { // let spannable:Spannable; // if (text instanceof Spannable) { // spannable = <Spannable> text; // } else { // spannable = new SpannableString(text); // text = spannable; // } // let spans:SuggestionSpan[] = spannable.getSpans(0, text.length(), SuggestionSpan.class); // for (let i:number = 0; i < spans.length; i++) { // spannable.removeSpan(spans[i]); // } //} return text; } ///** // * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This // * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, // * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} // * then a soft keyboard will not be displayed for this text view. // * // * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be // * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input // * type. // * // * @see #getInputType() // * @see #setRawInputType(int) // * @see android.text.InputType // * @attr ref android.R.styleable#TextView_inputType // */ //setInputType(type:number):void { // const wasPassword:boolean = TextView.isPasswordInputType(this.getInputType()); // const wasVisiblePassword:boolean = TextView.isVisiblePasswordInputType(this.getInputType()); // this.setInputType(type, false); // const isPassword:boolean = TextView.isPasswordInputType(type); // const isVisiblePassword:boolean = TextView.isVisiblePasswordInputType(type); // let forceUpdate:boolean = false; // if (isPassword) { // this.setTransformationMethod(PasswordTransformationMethod.getInstance()); // this.setTypefaceFromAttrs(null, /* fontFamily */ // TextView.MONOSPACE, 0); // } else if (isVisiblePassword) { // if (this.mTransformation == PasswordTransformationMethod.getInstance()) { // forceUpdate = true; // } // this.setTypefaceFromAttrs(null, /* fontFamily */ // TextView.MONOSPACE, 0); // } else if (wasPassword || wasVisiblePassword) { // // not in password mode, clean up typeface and transformation // this.setTypefaceFromAttrs(null, /* fontFamily */ // -1, -1); // if (this.mTransformation == PasswordTransformationMethod.getInstance()) { // forceUpdate = true; // } // } // let singleLine:boolean = !TextView.isMultilineInputType(type); // // were previously in password mode. // if (this.mSingleLine != singleLine || forceUpdate) { // // Change single line mode, but only change the transformation if // // we are not in password mode. // this.applySingleLine(singleLine, !isPassword, true); // } // if (!this.isSuggestionsEnabled()) { // this.mText = this.removeSuggestionSpans(this.mText); // } // let imm:InputMethodManager = InputMethodManager.peekInstance(); // if (imm != null) // imm.restartInput(this); //} /** * It would be better to rely on the input type for everything. A password inputType should have * a password transformation. We should hence use isPasswordInputType instead of this method. * * We should: * - Call setInputType in setKeyListener instead of changing the input type directly (which * would install the correct transformation). * - Refuse the installation of a non-password transformation in setTransformation if the input * type is password. * * However, this is like this for legacy reasons and we cannot break existing apps. This method * is useful since it matches what the user can see (obfuscated text or not). * * @return true if the current transformation method is of the password type. */ private hasPasswordTransformationMethod():boolean { return false; //return this.mTransformation instanceof PasswordTransformationMethod; } private static isPasswordInputType(inputType:number):boolean { return false; //const variation:number = inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); //return variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD) || variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD) || variation == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); } private static isVisiblePasswordInputType(inputType:number):boolean { return true; //const variation:number = inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); //return variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } /** * Directly change the content type integer of the text view, without * modifying any other state. * @see #setInputType(int) * @see android.text.InputType * @attr ref android.R.styleable#TextView_inputType */ setRawInputType(type:number):void { //TYPE_NULL is the default value //if (type == InputType.TYPE_NULL && this.mEditor == null) // return; //this.createEditorIfNeeded(); //this.mEditor.mInputType = type; } setInputType(type:number, direct:boolean=false):void { //const cls:number = type & EditorInfo.TYPE_MASK_CLASS; //let input:KeyListener; //if (cls == EditorInfo.TYPE_CLASS_TEXT) { // let autotext:boolean = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0; // let cap:TextKeyListener.Capitalize; // if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) { // cap = TextKeyListener.Capitalize.CHARACTERS; // } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) { // cap = TextKeyListener.Capitalize.WORDS; // } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) { // cap = TextKeyListener.Capitalize.SENTENCES; // } else { // cap = TextKeyListener.Capitalize.NONE; // } // input = TextKeyListener.getInstance(autotext, cap); //} else if (cls == EditorInfo.TYPE_CLASS_NUMBER) { // input = DigitsKeyListener.getInstance((type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0, (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0); //} else if (cls == EditorInfo.TYPE_CLASS_DATETIME) { // switch(type & EditorInfo.TYPE_MASK_VARIATION) { // case EditorInfo.TYPE_DATETIME_VARIATION_DATE: // input = DateKeyListener.getInstance(); // break; // case EditorInfo.TYPE_DATETIME_VARIATION_TIME: // input = TimeKeyListener.getInstance(); // break; // default: // input = DateTimeKeyListener.getInstance(); // break; // } //} else if (cls == EditorInfo.TYPE_CLASS_PHONE) { // input = DialerKeyListener.getInstance(); //} else { // input = TextKeyListener.getInstance(); //} //this.setRawInputType(type); //if (direct) { // this.createEditorIfNeeded(); // this.mEditor.mKeyListener = input; //} else { // this.setKeyListenerOnly(input); //} } /** * Get the type of the editable content. * * @see #setInputType(int) * @see android.text.InputType */ getInputType():number { return 0; //return this.mEditor == null ? EditorInfo.TYPE_NULL : this.mEditor.mInputType; } /** * Change the editor type integer associated with the text view, which * will be reported to an IME with {@link EditorInfo#imeOptions} when it * has focus. * @see #getImeOptions * @see android.view.inputmethod.EditorInfo * @attr ref android.R.styleable#TextView_imeOptions */ setImeOptions(imeOptions:number):void { //this.createEditorIfNeeded(); //this.mEditor.createInputContentTypeIfNeeded(); //this.mEditor.mInputContentType.imeOptions = imeOptions; } /** * Get the type of the IME editor. * * @see #setImeOptions(int) * @see android.view.inputmethod.EditorInfo */ getImeOptions():number { return -1; //return this.mEditor != null && this.mEditor.mInputContentType != null ? this.mEditor.mInputContentType.imeOptions : EditorInfo.IME_NULL; } /** * Change the custom IME action associated with the text view, which * will be reported to an IME with {@link EditorInfo#actionLabel} * and {@link EditorInfo#actionId} when it has focus. * @see #getImeActionLabel * @see #getImeActionId * @see android.view.inputmethod.EditorInfo * @attr ref android.R.styleable#TextView_imeActionLabel * @attr ref android.R.styleable#TextView_imeActionId */ setImeActionLabel(label:String, actionId:number):void { this.createEditorIfNeeded(); //this.mEditor.createInputContentTypeIfNeeded(); //this.mEditor.mInputContentType.imeActionLabel = label; //this.mEditor.mInputContentType.imeActionId = actionId; } /** * Get the IME action label previous set with {@link #setImeActionLabel}. * * @see #setImeActionLabel * @see android.view.inputmethod.EditorInfo */ getImeActionLabel():String { return ''; //return this.mEditor != null && this.mEditor.mInputContentType != null ? this.mEditor.mInputContentType.imeActionLabel : null; } /** * Get the IME action ID previous set with {@link #setImeActionLabel}. * * @see #setImeActionLabel * @see android.view.inputmethod.EditorInfo */ getImeActionId():number { return 0; //return this.mEditor != null && this.mEditor.mInputContentType != null ? this.mEditor.mInputContentType.imeActionId : 0; } /** * Set a special listener to be called when an action is performed * on the text view. This will be called when the enter key is pressed, * or when an action supplied to the IME is selected by the user. Setting * this means that the normal hard key event will not insert a newline * into the text view, even if it is multi-line; holding down the ALT * modifier will, however, allow the user to insert a newline character. */ setOnEditorActionListener(l:TextView.OnEditorActionListener):void { this.createEditorIfNeeded(); //this.mEditor.createInputContentTypeIfNeeded(); //this.mEditor.mInputContentType.onEditorActionListener = l; } /** * Called when an attached input method calls * {@link InputConnection#performEditorAction(int) * InputConnection.performEditorAction()} * for this text view. The default implementation will call your action * listener supplied to {@link #setOnEditorActionListener}, or perform * a standard operation for {@link EditorInfo#IME_ACTION_NEXT * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE * EditorInfo.IME_ACTION_DONE}. * * <p>For backwards compatibility, if no IME options have been set and the * text view would not normally advance focus on enter, then * the NEXT and DONE actions received here will be turned into an enter * key down/up pair to go through the normal key handling. * * @param actionCode The code of the action being performed. * * @see #setOnEditorActionListener */ //onEditorAction(actionCode:number):void { // const ict:Editor.InputContentType = this.mEditor == null ? null : this.mEditor.mInputContentType; // if (ict != null) { // if (ict.onEditorActionListener != null) { // if (ict.onEditorActionListener.onEditorAction(this, actionCode, null)) { // return; // } // } // // app may be expecting. // if (actionCode == EditorInfo.IME_ACTION_NEXT) { // let v:View = this.focusSearch(TextView.FOCUS_FORWARD); // if (v != null) { // if (!v.requestFocus(TextView.FOCUS_FORWARD)) { // throw Error(`new IllegalStateException("focus search returned a view " + "that wasn't able to take focus!")`); // } // } // return; // } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) { // let v:View = this.focusSearch(TextView.FOCUS_BACKWARD); // if (v != null) { // if (!v.requestFocus(TextView.FOCUS_BACKWARD)) { // throw Error(`new IllegalStateException("focus search returned a view " + "that wasn't able to take focus!")`); // } // } // return; // } else if (actionCode == EditorInfo.IME_ACTION_DONE) { // let imm:InputMethodManager = InputMethodManager.peekInstance(); // if (imm != null && imm.isActive(this)) { // imm.hideSoftInputFromWindow(this.getWindowToken(), 0); // } // return; // } // } // let viewRootImpl:ViewRootImpl = this.getViewRootImpl(); // if (viewRootImpl != null) { // let eventTime:number = SystemClock.uptimeMillis(); // viewRootImpl.dispatchKeyFromIme(new KeyEvent(eventTime, eventTime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE | KeyEvent.FLAG_EDITOR_ACTION)); // viewRootImpl.dispatchKeyFromIme(new KeyEvent(SystemClock.uptimeMillis(), eventTime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE | KeyEvent.FLAG_EDITOR_ACTION)); // } //} ///** // * Set the private content type of the text, which is the // * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} // * field that will be filled in when creating an input connection. // * // * @see #getPrivateImeOptions() // * @see EditorInfo#privateImeOptions // * @attr ref android.R.styleable#TextView_privateImeOptions // */ //setPrivateImeOptions(type:string):void { // this.createEditorIfNeeded(); // this.mEditor.createInputContentTypeIfNeeded(); // this.mEditor.mInputContentType.privateImeOptions = type; //} // ///** // * Get the private type of the content. // * // * @see #setPrivateImeOptions(String) // * @see EditorInfo#privateImeOptions // */ //getPrivateImeOptions():string { // return this.mEditor != null && this.mEditor.mInputContentType != null ? this.mEditor.mInputContentType.privateImeOptions : null; //} // ///** // * Set the extra input data of the text, which is the // * {@link EditorInfo#extras TextBoxAttribute.extras} // * Bundle that will be filled in when creating an input connection. The // * given integer is the resource ID of an XML resource holding an // * {@link android.R.styleable#InputExtras &lt;input-extras&gt;} XML tree. // * // * @see #getInputExtras(boolean) // * @see EditorInfo#extras // * @attr ref android.R.styleable#TextView_editorExtras // */ //setInputExtras(xmlResId:number):void { // this.createEditorIfNeeded(); // let parser:XmlResourceParser = this.getResources().getXml(xmlResId); // this.mEditor.createInputContentTypeIfNeeded(); // this.mEditor.mInputContentType.extras = new Bundle(); // this.getResources().parseBundleExtras(parser, this.mEditor.mInputContentType.extras); //} // ///** // * Retrieve the input extras currently associated with the text view, which // * can be viewed as well as modified. // * // * @param create If true, the extras will be created if they don't already // * exist. Otherwise, null will be returned if none have been created. // * @see #setInputExtras(int) // * @see EditorInfo#extras // * @attr ref android.R.styleable#TextView_editorExtras // */ //getInputExtras(create:boolean):any { // if (this.mEditor == null && !create) // return null; // this.createEditorIfNeeded(); // if (this.mEditor.mInputContentType == null) { // if (!create) // return null; // this.mEditor.createInputContentTypeIfNeeded(); // } // if (this.mEditor.mInputContentType.extras == null) { // if (!create) // return null; // this.mEditor.mInputContentType.extras = new Bundle(); // } // return this.mEditor.mInputContentType.extras; //} // ///** // * Returns the error message that was set to be displayed with // * {@link #setError}, or <code>null</code> if no error was set // * or if it the error was cleared by the widget after user input. // */ //getError():String { // return this.mEditor == null ? null : this.mEditor.mError; //} // ///** // * Sets the right-hand compound drawable of the TextView to the specified // * icon and sets an error message that will be displayed in a popup when // * the TextView has focus. The icon and error message will be reset to // * null when any key events cause changes to the TextView's text. The // * drawable must already have had {@link Drawable#setBounds} set on it. // * If the <code>error</code> is <code>null</code>, the error message will // * be cleared (and you should provide a <code>null</code> icon as well). // */ //setError(error:String, icon:Drawable=null):void { // this.createEditorIfNeeded(); // this.mEditor.setError(error, icon); // this.notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); //} protected setFrame(l:number, t:number, r:number, b:number):boolean { let result:boolean = super.setFrame(l, t, r, b); //if (this.mEditor != null) // this.mEditor.setFrame(); this.restartMarqueeIfNeeded(); return result; } private restartMarqueeIfNeeded():void { if (this.mRestartMarquee && this.mEllipsize == TextUtils.TruncateAt.MARQUEE) { this.mRestartMarquee = false; this.startMarquee(); } } /** * Sets the list of input filters that will be used if the buffer is * Editable. Has no effect otherwise. * * @attr ref android.R.styleable#TextView_maxLength */ setFilters(filters:any[]):void; setFilters(e:any, filters:any[]):void; setFilters(...args):void { //if (this.mEditor != null) { // const undoFilter:boolean = this.mEditor.mUndoInputFilter != null; // const keyFilter:boolean = this.mEditor.mKeyListener instanceof InputFilter; // let num:number = 0; // if (undoFilter) // num++; // if (keyFilter) // num++; // if (num > 0) { // let nf:InputFilter[] = new Array<InputFilter>(filters.length + num); // System.arraycopy(filters, 0, nf, 0, filters.length); // num = 0; // if (undoFilter) { // nf[filters.length] = this.mEditor.mUndoInputFilter; // num++; // } // if (keyFilter) { // nf[filters.length + num] = <InputFilter> this.mEditor.mKeyListener; // } // e.setFilters(nf); // return; // } //} //e.setFilters(filters); } /** * Returns the current list of input filters. * * @attr ref android.R.styleable#TextView_maxLength */ getFilters():any[] { return this.mFilters; } ///////////////////////////////////////////////////////////////////////// private getBoxHeight(l:Layout):number { //let opticalInsets:Insets = TextView.isLayoutModeOptical(this.mParent) ? this.getOpticalInsets() : Insets.NONE; let padding:number = (l == this.mHintLayout) ? this.getCompoundPaddingTop() + this.getCompoundPaddingBottom() : this.getExtendedPaddingTop() + this.getExtendedPaddingBottom(); return this.getMeasuredHeight() - padding;// + opticalInsets.top + opticalInsets.bottom; } getVerticalOffset(forceNormal:boolean):number { let voffset:number = 0; const gravity:number = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; let l:Layout = this.mLayout; if (!forceNormal && this.mText.length == 0 && this.mHintLayout != null) { l = this.mHintLayout; } if (gravity != Gravity.TOP) { let boxht:number = this.getBoxHeight(l); let textht:number = l.getHeight(); if (textht < boxht) { if (gravity == Gravity.BOTTOM) voffset = boxht - textht; else // (gravity == Gravity.CENTER_VERTICAL) voffset = (boxht - textht) >> 1; } } return voffset; } private getBottomVerticalOffset(forceNormal:boolean):number { let voffset:number = 0; const gravity:number = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; let l:Layout = this.mLayout; if (!forceNormal && this.mText.length == 0 && this.mHintLayout != null) { l = this.mHintLayout; } if (gravity != Gravity.BOTTOM) { let boxht:number = this.getBoxHeight(l); let textht:number = l.getHeight(); if (textht < boxht) { if (gravity == Gravity.TOP) voffset = boxht - textht; else // (gravity == Gravity.CENTER_VERTICAL) voffset = (boxht - textht) >> 1; } } return voffset; } //invalidateCursorPath():void { // if (this.mHighlightPathBogus) { // this.invalidateCursor(); // } else { // const horizontalPadding:number = this.getCompoundPaddingLeft(); // const verticalPadding:number = this.getExtendedPaddingTop() + this.getVerticalOffset(true); // if (this.mEditor.mCursorCount == 0) { // { // /* // * The reason for this concern about the thickness of the // * cursor and doing the floor/ceil on the coordinates is that // * some EditTexts (notably textfields in the Browser) have // * anti-aliased text where not all the characters are // * necessarily at integer-multiple locations. This should // * make sure the entire cursor gets invalidated instead of // * sometimes missing half a pixel. // */ // let thick:number = Math.ceil(this.mTextPaint.getStrokeWidth()); // if (thick < 1.0) { // thick = 1.0; // } // thick /= 2.0; // // mHighlightPath is guaranteed to be non null at that point. // this.mHighlightPath.computeBounds(TextView.TEMP_RECTF, false); // this.invalidate(Math.floor(Math.floor(horizontalPadding + TextView.TEMP_RECTF.left - thick)), Math.floor(Math.floor(verticalPadding + TextView.TEMP_RECTF.top - thick)), Math.floor(Math.ceil(horizontalPadding + TextView.TEMP_RECTF.right + thick)), Math.floor(Math.ceil(verticalPadding + TextView.TEMP_RECTF.bottom + thick))); // } // } else { // for (let i:number = 0; i < this.mEditor.mCursorCount; i++) { // let bounds:Rect = this.mEditor.mCursorDrawable[i].getBounds(); // this.invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding, bounds.right + horizontalPadding, bounds.bottom + verticalPadding); // } // } // } //} // //invalidateCursor():void { // let where:number = this.getSelectionEnd(); // this.invalidateCursor(where, where, where); //} // //private invalidateCursor(a:number, b:number, c:number):void { // if (a >= 0 || b >= 0 || c >= 0) { // let start:number = Math.min(Math.min(a, b), c); // let end:number = Math.max(Math.max(a, b), c); // this.invalidateRegion(start, end, true); // } //} /** * Invalidates the region of text enclosed between the start and end text offsets. */ invalidateRegion(start:number, end:number, invalidateCursor:boolean):void { if (this.mLayout == null) { this.invalidate(); } else { let lineStart:number = this.mLayout.getLineForOffset(start); let top:number = this.mLayout.getLineTop(lineStart); // the same problem with the descenders on the line above it!) if (lineStart > 0) { top -= this.mLayout.getLineDescent(lineStart - 1); } let lineEnd:number; if (start == end) lineEnd = lineStart; else lineEnd = this.mLayout.getLineForOffset(end); let bottom:number = this.mLayout.getLineBottom(lineEnd); // mEditor can be null in case selection is set programmatically. //if (invalidateCursor && this.mEditor != null) { // for (let i:number = 0; i < this.mEditor.mCursorCount; i++) { // let bounds:Rect = this.mEditor.mCursorDrawable[i].getBounds(); // top = Math.min(top, bounds.top); // bottom = Math.max(bottom, bounds.bottom); // } //} const compoundPaddingLeft:number = this.getCompoundPaddingLeft(); const verticalPadding:number = this.getExtendedPaddingTop() + this.getVerticalOffset(true); let left:number, right:number; if (lineStart == lineEnd && !invalidateCursor) { left = Math.floor(this.mLayout.getPrimaryHorizontal(start)); right = Math.floor((this.mLayout.getPrimaryHorizontal(end) + 1.0)); left += compoundPaddingLeft; right += compoundPaddingLeft; } else { // Rectangle bounding box when the region spans several lines left = compoundPaddingLeft; right = this.getWidth() - this.getCompoundPaddingRight(); } this.invalidate(this.mScrollX + left, verticalPadding + top, this.mScrollX + right, verticalPadding + bottom); } } private registerForPreDraw():void { if (!this.mPreDrawRegistered) { this.getViewTreeObserver().addOnPreDrawListener(this); this.mPreDrawRegistered = true; } } /** * {@inheritDoc} */ onPreDraw():boolean { if (this.mLayout == null) { this.assumeLayout(); } if (this.mMovement != null) { /* This code also provides auto-scrolling when a cursor is moved using a * CursorController (insertion point or selection limits). * For selection, ensure start or end is visible depending on controller's state. */ let curs:number = this.getSelectionEnd(); // Do not create the controller if it is not already created. //if (this.mEditor != null && this.mEditor.mSelectionModifierCursorController != null && this.mEditor.mSelectionModifierCursorController.isSelectionStartDragged()) { // curs = this.getSelectionStart(); //} /* * TODO: This should really only keep the end in view if * it already was before the text changed. I'm not sure * of a good way to tell from here if it was. */ if (curs < 0 && (this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { curs = this.mText.length; } if (curs >= 0) { this.bringPointIntoView(curs); } } else { this.bringTextIntoView(); } // a screen rotation) since layout is not yet initialized at that point. //if (this.mEditor != null && this.mEditor.mCreatedWithASelection) { // this.mEditor.startSelectionActionMode(); // this.mEditor.mCreatedWithASelection = false; //} // not be set. Do the test here instead. //if (this instanceof ExtractEditText && this.hasSelection() && this.mEditor != null) { // this.mEditor.startSelectionActionMode(); //} this.getViewTreeObserver().removeOnPreDrawListener(this); this.mPreDrawRegistered = false; return true; } protected onAttachedToWindow():void { super.onAttachedToWindow(); this.mTemporaryDetach = false; //if (this.mEditor != null) // this.mEditor.onAttachedToWindow(); } protected onDetachedFromWindow():void { super.onDetachedFromWindow(); if (this.mPreDrawRegistered) { this.getViewTreeObserver().removeOnPreDrawListener(this); this.mPreDrawRegistered = false; } this.resetResolvedDrawables(); //if (this.mEditor != null) // this.mEditor.onDetachedFromWindow(); } //onScreenStateChanged(screenState:number):void { // super.onScreenStateChanged(screenState); // if (this.mEditor != null) // this.mEditor.onScreenStateChanged(screenState); //} protected isPaddingOffsetRequired():boolean { return this.mShadowRadius != 0 || this.mDrawables != null; } protected getLeftPaddingOffset():number { return this.getCompoundPaddingLeft() - this.mPaddingLeft + Math.floor(Math.min(0, this.mShadowDx - this.mShadowRadius)); } protected getTopPaddingOffset():number { return Math.floor(Math.min(0, this.mShadowDy - this.mShadowRadius)); } protected getBottomPaddingOffset():number { return Math.floor(Math.max(0, this.mShadowDy + this.mShadowRadius)); } protected getRightPaddingOffset():number { return -(this.getCompoundPaddingRight() - this.mPaddingRight) + Math.floor(Math.max(0, this.mShadowDx + this.mShadowRadius)); } protected verifyDrawable(who:Drawable):boolean { const verified:boolean = super.verifyDrawable(who); if (!verified && this.mDrawables != null) { return who == this.mDrawables.mDrawableLeft || who == this.mDrawables.mDrawableTop || who == this.mDrawables.mDrawableRight || who == this.mDrawables.mDrawableBottom || who == this.mDrawables.mDrawableStart || who == this.mDrawables.mDrawableEnd; } return verified; } jumpDrawablesToCurrentState():void { super.jumpDrawablesToCurrentState(); if (this.mDrawables != null) { if (this.mDrawables.mDrawableLeft != null) { this.mDrawables.mDrawableLeft.jumpToCurrentState(); } if (this.mDrawables.mDrawableTop != null) { this.mDrawables.mDrawableTop.jumpToCurrentState(); } if (this.mDrawables.mDrawableRight != null) { this.mDrawables.mDrawableRight.jumpToCurrentState(); } if (this.mDrawables.mDrawableBottom != null) { this.mDrawables.mDrawableBottom.jumpToCurrentState(); } if (this.mDrawables.mDrawableStart != null) { this.mDrawables.mDrawableStart.jumpToCurrentState(); } if (this.mDrawables.mDrawableEnd != null) { this.mDrawables.mDrawableEnd.jumpToCurrentState(); } } } drawableSizeChange(d:android.graphics.drawable.Drawable):void { const drawables:TextView.Drawables = this.mDrawables; const isCompoundDrawable = drawables!=null && (d == drawables.mDrawableLeft || d == drawables.mDrawableTop || d == drawables.mDrawableRight || d == drawables.mDrawableBottom || d == drawables.mDrawableStart || d == drawables.mDrawableEnd); if(isCompoundDrawable){ d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); this.setCompoundDrawables(drawables.mDrawableLeft, drawables.mDrawableTop, drawables.mDrawableRight, drawables.mDrawableBottom); }else{ super.drawableSizeChange(d); } } invalidateDrawable(drawable:Drawable):void { if (this.verifyDrawable(drawable)) { const dirty:Rect = drawable.getBounds(); let scrollX:number = this.mScrollX; let scrollY:number = this.mScrollY; // IMPORTANT: The coordinates below are based on the coordinates computed // for each compound drawable in onDraw(). Make sure to update each section // accordingly. const drawables:TextView.Drawables = this.mDrawables; if (drawables != null) { if (drawable == drawables.mDrawableLeft) { const compoundPaddingTop:number = this.getCompoundPaddingTop(); const compoundPaddingBottom:number = this.getCompoundPaddingBottom(); const vspace:number = this.mBottom - this.mTop - compoundPaddingBottom - compoundPaddingTop; scrollX += this.mPaddingLeft; scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; } else if (drawable == drawables.mDrawableRight) { const compoundPaddingTop:number = this.getCompoundPaddingTop(); const compoundPaddingBottom:number = this.getCompoundPaddingBottom(); const vspace:number = this.mBottom - this.mTop - compoundPaddingBottom - compoundPaddingTop; scrollX += (this.mRight - this.mLeft - this.mPaddingRight - drawables.mDrawableSizeRight); scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; } else if (drawable == drawables.mDrawableTop) { const compoundPaddingLeft:number = this.getCompoundPaddingLeft(); const compoundPaddingRight:number = this.getCompoundPaddingRight(); const hspace:number = this.mRight - this.mLeft - compoundPaddingRight - compoundPaddingLeft; scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; scrollY += this.mPaddingTop; } else if (drawable == drawables.mDrawableBottom) { const compoundPaddingLeft:number = this.getCompoundPaddingLeft(); const compoundPaddingRight:number = this.getCompoundPaddingRight(); const hspace:number = this.mRight - this.mLeft - compoundPaddingRight - compoundPaddingLeft; scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; scrollY += (this.mBottom - this.mTop - this.mPaddingBottom - drawables.mDrawableSizeBottom); } } this.invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); } } //hasOverlappingRendering():boolean { // // horizontal fading edge causes SaveLayerAlpha, which doesn't support alpha modulation // return ((this.getBackground() != null && this.getBackground().getCurrent() != null) || this.mText instanceof Spannable || this.hasSelection() || this.isHorizontalFadingEdgeEnabled()); //} /** * * Returns the state of the {@code textIsSelectable} flag (See * {@link #setTextIsSelectable setTextIsSelectable()}). Although you have to set this flag * to allow users to select and copy text in a non-editable TextView, the content of an * {@link EditText} can always be selected, independently of the value of this flag. * <p> * * @return True if the text displayed in this TextView can be selected by the user. * * @attr ref android.R.styleable#TextView_textIsSelectable */ isTextSelectable():boolean { return false; //return this.mEditor == null ? false : this.mEditor.mTextIsSelectable; } /** * Sets whether the content of this view is selectable by the user. The default is * {@code false}, meaning that the content is not selectable. * <p> * When you use a TextView to display a useful piece of information to the user (such as a * contact's address), make it selectable, so that the user can select and copy its * content. You can also use set the XML attribute * {@link android.R.styleable#TextView_textIsSelectable} to "true". * <p> * When you call this method to set the value of {@code textIsSelectable}, it sets * the flags {@code focusable}, {@code focusableInTouchMode}, {@code clickable}, * and {@code longClickable} to the same value. These flags correspond to the attributes * {@link android.R.styleable#View_focusable android:focusable}, * {@link android.R.styleable#View_focusableInTouchMode android:focusableInTouchMode}, * {@link android.R.styleable#View_clickable android:clickable}, and * {@link android.R.styleable#View_longClickable android:longClickable}. To restore any of these * flags to a state you had set previously, call one or more of the following methods: * {@link #setFocusable(boolean) setFocusable()}, * {@link #setFocusableInTouchMode(boolean) setFocusableInTouchMode()}, * {@link #setClickable(boolean) setClickable()} or * {@link #setLongClickable(boolean) setLongClickable()}. * * @param selectable Whether the content of this TextView should be selectable. */ setTextIsSelectable(selectable:boolean):void { //// false is default value with no edit data //if (!selectable && this.mEditor == null) // return; //this.createEditorIfNeeded(); //if (this.mEditor.mTextIsSelectable == selectable) // return; //this.mEditor.mTextIsSelectable = selectable; //this.setFocusableInTouchMode(selectable); //this.setFocusable(selectable); //this.setClickable(selectable); //this.setLongClickable(selectable); //// mInputType should already be EditorInfo.TYPE_NULL and mInput should be null //this.setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); //this.setText(this.mText, selectable ? TextView.BufferType.SPANNABLE : TextView.BufferType.NORMAL); //// Called by setText above, but safer in case of future code changes //this.mEditor.prepareCursorControllers(); } protected onCreateDrawableState(extraSpace:number):number[] { let drawableState:number[]; if (this.mSingleLine) { drawableState = super.onCreateDrawableState(extraSpace); } else { drawableState = super.onCreateDrawableState(extraSpace + 1); TextView.mergeDrawableStates(drawableState, TextView.MULTILINE_STATE_SET); } if (this.isTextSelectable()) { // Disable pressed state, which was introduced when TextView was made clickable. // Prevents text color change. // setClickable(false) would have a similar effect, but it also disables focus changes // and long press actions, which are both needed by text selection. const length:number = drawableState.length; for (let i:number = 0; i < length; i++) { if (drawableState[i] == View.VIEW_STATE_PRESSED) { const nonPressedState:number[] = androidui.util.ArrayCreator.newNumberArray(length - 1); System.arraycopy(drawableState, 0, nonPressedState, 0, i); System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); return nonPressedState; } } } return drawableState; } private getUpdatedHighlightPath():Path { let highlight:Path = null; let highlightPaint:Paint = this.mHighlightPaint; const selStart:number = this.getSelectionStart(); const selEnd:number = this.getSelectionEnd(); if (this.mMovement != null && (this.isFocused() || this.isPressed()) && selStart >= 0) { if (selStart == selEnd) { //if (this.mEditor != null && this.mEditor.isCursorVisible() && (SystemClock.uptimeMillis() - this.mEditor.mShowCursor) % (2 * Editor.BLINK) < Editor.BLINK) { // if (this.mHighlightPathBogus) { // if (this.mHighlightPath == null) // this.mHighlightPath = new Path(); // this.mHighlightPath.reset(); // this.mLayout.getCursorPath(selStart, this.mHighlightPath, this.mText); // this.mEditor.updateCursorsPositions(); // this.mHighlightPathBogus = false; // } // // XXX should pass to skin instead of drawing directly // highlightPaint.setColor(this.mCurTextColor); // highlightPaint.setStyle(Paint.Style.STROKE); // highlight = this.mHighlightPath; //} } else { if (this.mHighlightPathBogus) { if (this.mHighlightPath == null) this.mHighlightPath = new Path(); this.mHighlightPath.reset(); this.mLayout.getSelectionPath(selStart, selEnd, this.mHighlightPath); this.mHighlightPathBogus = false; } // XXX should pass to skin instead of drawing directly highlightPaint.setColor(this.mHighlightColor); highlightPaint.setStyle(Paint.Style.FILL); highlight = this.mHighlightPath; } } return highlight; } /** * @hide */ getHorizontalOffsetForDrawables():number { return 0; } protected onDraw(canvas:Canvas):void { this.restartMarqueeIfNeeded(); // Draw the background for this view super.onDraw(canvas); const compoundPaddingLeft:number = this.getCompoundPaddingLeft(); const compoundPaddingTop:number = this.getCompoundPaddingTop(); const compoundPaddingRight:number = this.getCompoundPaddingRight(); const compoundPaddingBottom:number = this.getCompoundPaddingBottom(); const scrollX:number = this.mScrollX; const scrollY:number = this.mScrollY; const right:number = this.mRight; const left:number = this.mLeft; const bottom:number = this.mBottom; const top:number = this.mTop; const isLayoutRtl:boolean = this.isLayoutRtl(); const offset:number = this.getHorizontalOffsetForDrawables(); const leftOffset:number = isLayoutRtl ? 0 : offset; const rightOffset:number = isLayoutRtl ? offset : 0; const dr:TextView.Drawables = this.mDrawables; if (dr != null) { /* * Compound, not extended, because the icon is not clipped * if the text height is smaller. */ let vspace:number = bottom - top - compoundPaddingBottom - compoundPaddingTop; let hspace:number = right - left - compoundPaddingRight - compoundPaddingLeft; // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableLeft != null) { canvas.save(); canvas.translate(scrollX + this.mPaddingLeft + leftOffset, scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightLeft) / 2); dr.mDrawableLeft.draw(canvas); canvas.restore(); } // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableRight != null) { canvas.save(); canvas.translate(scrollX + right - left - this.mPaddingRight - dr.mDrawableSizeRight - rightOffset, scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); dr.mDrawableRight.draw(canvas); canvas.restore(); } // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableTop != null) { canvas.save(); canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, scrollY + this.mPaddingTop); dr.mDrawableTop.draw(canvas); canvas.restore(); } // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableBottom != null) { canvas.save(); canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthBottom) / 2, scrollY + bottom - top - this.mPaddingBottom - dr.mDrawableSizeBottom); dr.mDrawableBottom.draw(canvas); canvas.restore(); } } let color:number = this.mCurTextColor; if (this.mLayout == null) { this.assumeLayout(); } let layout:Layout = this.mLayout; if (this.mHint != null && this.mText.length == 0) { if (this.mHintTextColor != null) { color = this.mCurHintTextColor; } layout = this.mHintLayout; } this.mTextPaint.setColor(color); this.mTextPaint.drawableState = this.getDrawableState(); //androidui: will set to true by EditText (when editing) if(this.mSkipDrawText) return; canvas.save(); /* Would be faster if we didn't have to do this. Can we chop the (displayable) text so that we don't need to do this ever? */ let extendedPaddingTop:number = this.getExtendedPaddingTop(); let extendedPaddingBottom:number = this.getExtendedPaddingBottom(); const vspace:number = this.mBottom - this.mTop - compoundPaddingBottom - compoundPaddingTop; const maxScrollY:number = this.mLayout.getHeight() - vspace; let clipLeft:number = compoundPaddingLeft + scrollX; let clipTop:number = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY; let clipRight:number = right - left - compoundPaddingRight + scrollX; let clipBottom:number = bottom - top + scrollY - ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom); if (this.mShadowRadius != 0) { clipLeft += Math.min(0, this.mShadowDx - this.mShadowRadius); clipRight += Math.max(0, this.mShadowDx + this.mShadowRadius); clipTop += Math.min(0, this.mShadowDy - this.mShadowRadius); clipBottom += Math.max(0, this.mShadowDy + this.mShadowRadius); } canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); let voffsetText:number = 0; let voffsetCursor:number = 0; /* shortcircuit calling getVerticaOffset() */ if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffsetText = this.getVerticalOffset(false); voffsetCursor = this.getVerticalOffset(true); } canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); //const layoutDirection:number = this.getLayoutDirection(); const absoluteGravity:number = this.mGravity;//Gravity.getAbsoluteGravity(this.mGravity, layoutDirection); if (this.mEllipsize == TextUtils.TruncateAt.MARQUEE && this.mMarqueeFadeMode != TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { if (!this.mSingleLine && this.getLineCount() == 1 && this.canMarquee() && (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { const width:number = this.mRight - this.mLeft; const padding:number = this.getCompoundPaddingLeft() + this.getCompoundPaddingRight(); const dx:number = this.mLayout.getLineRight(0) - (width - padding); canvas.translate(isLayoutRtl ? -dx : +dx, 0.0); } if (this.mMarquee != null && this.mMarquee.isRunning()) { const dx:number = -this.mMarquee.getScroll(); canvas.translate(isLayoutRtl ? -dx : +dx, 0.0); } } const cursorOffsetVertical:number = voffsetCursor - voffsetText; let highlight:Path = this.getUpdatedHighlightPath(); //if (this.mEditor != null) { // this.mEditor.onDraw(canvas, layout, highlight, this.mHighlightPaint, cursorOffsetVertical); //} else { layout.draw(canvas, highlight, this.mHighlightPaint, cursorOffsetVertical); //} if (this.mMarquee != null && this.mMarquee.shouldDrawGhost()) { const dx:number = Math.floor(this.mMarquee.getGhostOffset()); canvas.translate(isLayoutRtl ? -dx : dx, 0.0); layout.draw(canvas, highlight, this.mHighlightPaint, cursorOffsetVertical); } canvas.restore(); } getFocusedRect(r:Rect):void { if (this.mLayout == null) { super.getFocusedRect(r); return; } let selEnd:number = this.getSelectionEnd(); if (selEnd < 0) { super.getFocusedRect(r); return; } //let selStart:number = this.getSelectionStart(); //if (selStart < 0 || selStart >= selEnd) { // let line:number = this.mLayout.getLineForOffset(selEnd); // r.top = this.mLayout.getLineTop(line); // r.bottom = this.mLayout.getLineBottom(line); // r.left = Math.floor(this.mLayout.getPrimaryHorizontal(selEnd)) - 2; // r.right = r.left + 4; //} else { // let lineStart:number = this.mLayout.getLineForOffset(selStart); // let lineEnd:number = this.mLayout.getLineForOffset(selEnd); // r.top = this.mLayout.getLineTop(lineStart); // r.bottom = this.mLayout.getLineBottom(lineEnd); // if (lineStart == lineEnd) { // r.left = Math.floor(this.mLayout.getPrimaryHorizontal(selStart)); // r.right = Math.floor(this.mLayout.getPrimaryHorizontal(selEnd)); // } else { // // rect cover the entire width. // if (this.mHighlightPathBogus) { // if (this.mHighlightPath == null) // this.mHighlightPath = new Path(); // this.mHighlightPath.reset(); // this.mLayout.getSelectionPath(selStart, selEnd, this.mHighlightPath); // this.mHighlightPathBogus = false; // } // { // this.mHighlightPath.computeBounds(TextView.TEMP_RECTF, true); // r.left = Math.floor(TextView.TEMP_RECTF.left) - 1; // r.right = Math.floor(TextView.TEMP_RECTF.right) + 1; // } // } //} //// Adjust for padding and gravity. //let paddingLeft:number = this.getCompoundPaddingLeft(); //let paddingTop:number = this.getExtendedPaddingTop(); //if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { // paddingTop += this.getVerticalOffset(false); //} //r.offset(paddingLeft, paddingTop); //let paddingBottom:number = this.getExtendedPaddingBottom(); //r.bottom += paddingBottom; } /** * Return the number of lines of text, or 0 if the internal Layout has not * been built. */ getLineCount():number { return this.mLayout != null ? this.mLayout.getLineCount() : 0; } /** * Return the baseline for the specified line (0...getLineCount() - 1) * If bounds is not null, return the top, left, right, bottom extents * of the specified line in it. If the internal Layout has not been built, * return 0 and set bounds to (0, 0, 0, 0) * @param line which line to examine (0..getLineCount() - 1) * @param bounds Optional. If not null, it returns the extent of the line * @return the Y-coordinate of the baseline */ getLineBounds(line:number, bounds:Rect):number { if (this.mLayout == null) { if (bounds != null) { bounds.set(0, 0, 0, 0); } return 0; } else { let baseline:number = this.mLayout.getLineBounds(line, bounds); let voffset:number = this.getExtendedPaddingTop(); if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffset += this.getVerticalOffset(true); } if (bounds != null) { bounds.offset(this.getCompoundPaddingLeft(), voffset); } return baseline + voffset; } } getBaseline():number { if (this.mLayout == null) { return super.getBaseline(); } let voffset:number = 0; if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffset = this.getVerticalOffset(true); } //if (TextView.isLayoutModeOptical(this.mParent)) { // voffset -= this.getOpticalInsets().top; //} return this.getExtendedPaddingTop() + voffset + this.mLayout.getLineBaseline(0); } /** * @hide */ protected getFadeTop(offsetRequired:boolean):number { if (this.mLayout == null) return 0; let voffset:number = 0; if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffset = this.getVerticalOffset(true); } if (offsetRequired) voffset += this.getTopPaddingOffset(); return this.getExtendedPaddingTop() + voffset; } /** * @hide */ protected getFadeHeight(offsetRequired:boolean):number { return this.mLayout != null ? this.mLayout.getHeight() : 0; } //onKeyPreIme(keyCode:number, event:KeyEvent):boolean { // if (keyCode == KeyEvent.KEYCODE_BACK) { // let isInSelectionMode:boolean = this.mEditor != null && this.mEditor.mSelectionActionMode != null; // if (isInSelectionMode) { // if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { // let state:KeyEvent.DispatcherState = this.getKeyDispatcherState(); // if (state != null) { // state.startTracking(event, this); // } // return true; // } else if (event.getAction() == KeyEvent.ACTION_UP) { // let state:KeyEvent.DispatcherState = this.getKeyDispatcherState(); // if (state != null) { // state.handleUpEvent(event); // } // if (event.isTracking() && !event.isCanceled()) { // this.stopSelectionActionMode(); // return true; // } // } // } // } // return super.onKeyPreIme(keyCode, event); //} onKeyDown(keyCode:number, event:KeyEvent):boolean { let which:number = this.doKeyDown(keyCode, event, null); if (which == 0) { return super.onKeyDown(keyCode, event); } return true; } //onKeyMultiple(keyCode:number, repeatCount:number, event:KeyEvent):boolean { // let down:KeyEvent = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); // let which:number = this.doKeyDown(keyCode, down, event); // if (which == 0) { // // Go through default dispatching. // return super.onKeyMultiple(keyCode, repeatCount, event); // } // if (which == -1) { // // Consumed the whole thing. // return true; // } // repeatCount--; // // We are going to dispatch the remaining events to either the input // // or movement method. To do this, we will just send a repeated stream // // of down and up events until we have done the complete repeatCount. // // It would be nice if those interfaces had an onKeyMultiple() method, // // but adding that is a more complicated change. // let up:KeyEvent = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); // if (which == 1) { // // mEditor and mEditor.mInput are not null from doKeyDown // this.mEditor.mKeyListener.onKeyUp(this, <Editable> this.mText, keyCode, up); // while (--repeatCount > 0) { // this.mEditor.mKeyListener.onKeyDown(this, <Editable> this.mText, keyCode, down); // this.mEditor.mKeyListener.onKeyUp(this, <Editable> this.mText, keyCode, up); // } // this.hideErrorIfUnchanged(); // } else if (which == 2) { // // mMovement is not null from doKeyDown // this.mMovement.onKeyUp(this, <Spannable> this.mText, keyCode, up); // while (--repeatCount > 0) { // this.mMovement.onKeyDown(this, <Spannable> this.mText, keyCode, down); // this.mMovement.onKeyUp(this, <Spannable> this.mText, keyCode, up); // } // } // return true; //} /** * Returns true if pressing ENTER in this field advances focus instead * of inserting the character. This is true mostly in single-line fields, * but also in mail addresses and subjects which will display on multiple * lines but where it doesn't make sense to insert newlines. */ private shouldAdvanceFocusOnEnter():boolean { if (this.getKeyListener() == null) { return false; } if (this.mSingleLine) { return true; } //if (this.mEditor != null && (this.mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { // let variation:number = this.mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; // if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { // return true; // } //} return false; } /** * Returns true if pressing TAB in this field advances focus instead * of inserting the character. Insert tabs only in multi-line editors. */ private shouldAdvanceFocusOnTab():boolean { //if (this.getKeyListener() != null && !this.mSingleLine && this.mEditor != null && (this.mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { // let variation:number = this.mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; // if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { // return false; // } //} return true; } private doKeyDown(keyCode:number, event:KeyEvent, otherEvent:KeyEvent):number { //if (!this.isEnabled()) { return 0; //} //// prevent the user from traversing out of this on the next key down. //if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) { // this.mPreventDefaultMovement = false; //} //switch(keyCode) { // case KeyEvent.KEYCODE_ENTER: // if (event.hasNoModifiers()) { // // enter key events. // if (this.mEditor != null && this.mEditor.mInputContentType != null) { // // chance to consume the event. // if (this.mEditor.mInputContentType.onEditorActionListener != null && this.mEditor.mInputContentType.onEditorActionListener.onEditorAction(this, EditorInfo.IME_NULL, event)) { // this.mEditor.mInputContentType.enterDown = true; // // We are consuming the enter key for them. // return -1; // } // } // // don't let it be inserted into the text. // if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 || this.shouldAdvanceFocusOnEnter()) { // if (this.hasOnClickListeners()) { // return 0; // } // return -1; // } // } // break; // case KeyEvent.KEYCODE_DPAD_CENTER: // if (event.hasNoModifiers()) { // if (this.shouldAdvanceFocusOnEnter()) { // return 0; // } // } // break; // case KeyEvent.KEYCODE_TAB: // if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { // if (this.shouldAdvanceFocusOnTab()) { // return 0; // } // } // break; // // Has to be done on key down (and not on key up) to correctly be intercepted. // case KeyEvent.KEYCODE_BACK: // if (this.mEditor != null && this.mEditor.mSelectionActionMode != null) { // this.stopSelectionActionMode(); // return -1; // } // break; //} //if (this.mEditor != null && this.mEditor.mKeyListener != null) { // this.resetErrorChangedFlag(); // let doDown:boolean = true; // if (otherEvent != null) { // try { // this.beginBatchEdit(); // const handled:boolean = this.mEditor.mKeyListener.onKeyOther(this, <Editable> this.mText, otherEvent); // this.hideErrorIfUnchanged(); // doDown = false; // if (handled) { // return -1; // } // } catch (e){ // } finally { // this.endBatchEdit(); // } // } // if (doDown) { // this.beginBatchEdit(); // const handled:boolean = this.mEditor.mKeyListener.onKeyDown(this, <Editable> this.mText, keyCode, event); // this.endBatchEdit(); // this.hideErrorIfUnchanged(); // if (handled) // return 1; // } //} //if (this.mMovement != null && this.mLayout != null) { // let doDown:boolean = true; // if (otherEvent != null) { // try { // let handled:boolean = this.mMovement.onKeyOther(this, <Spannable> this.mText, otherEvent); // doDown = false; // if (handled) { // return -1; // } // } catch (e){ // } // } // if (doDown) { // if (this.mMovement.onKeyDown(this, <Spannable> this.mText, keyCode, event)) { // if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) { // this.mPreventDefaultMovement = true; // } // return 2; // } // } //} //return this.mPreventDefaultMovement && !KeyEvent.isModifierKey(keyCode) ? -1 : 0; } /** * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} * can be recorded. * @hide */ resetErrorChangedFlag():void { /* * Keep track of what the error was before doing the input * so that if an input filter changed the error, we leave * that error showing. Otherwise, we take down whatever * error was showing when the user types something. */ //if (this.mEditor != null) // this.mEditor.mErrorWasChanged = false; } /** * @hide */ hideErrorIfUnchanged():void { //if (this.mEditor != null && this.mEditor.mError != null && !this.mEditor.mErrorWasChanged) { // this.setError(null, null); //} } onKeyUp(keyCode:number, event:KeyEvent):boolean { //if (!this.isEnabled()) { return super.onKeyUp(keyCode, event); //} //if (!KeyEvent.isModifierKey(keyCode)) { // this.mPreventDefaultMovement = false; //} //switch(keyCode) { // case KeyEvent.KEYCODE_DPAD_CENTER: // if (event.hasNoModifiers()) { // /* // * If there is a click listener, just call through to // * super, which will invoke it. // * // * If there isn't a click listener, try to show the soft // * input method. (It will also // * call performClick(), but that won't do anything in // * this case.) // */ // if (!this.hasOnClickListeners()) { // if (this.mMovement != null && this.mText instanceof Editable && this.mLayout != null && this.onCheckIsTextEditor()) { // let imm:InputMethodManager = InputMethodManager.peekInstance(); // this.viewClicked(imm); // if (imm != null && this.getShowSoftInputOnFocus()) { // imm.showSoftInput(this, 0); // } // } // } // } // return super.onKeyUp(keyCode, event); // case KeyEvent.KEYCODE_ENTER: // if (event.hasNoModifiers()) { // if (this.mEditor != null && this.mEditor.mInputContentType != null && this.mEditor.mInputContentType.onEditorActionListener != null && this.mEditor.mInputContentType.enterDown) { // this.mEditor.mInputContentType.enterDown = false; // if (this.mEditor.mInputContentType.onEditorActionListener.onEditorAction(this, EditorInfo.IME_NULL, event)) { // return true; // } // } // if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 || this.shouldAdvanceFocusOnEnter()) { // /* // * If there is a click listener, just call through to // * super, which will invoke it. // * // * If there isn't a click listener, try to advance focus, // * but still call through to super, which will reset the // * pressed state and longpress state. (It will also // * call performClick(), but that won't do anything in // * this case.) // */ // if (!this.hasOnClickListeners()) { // let v:View = this.focusSearch(TextView.FOCUS_DOWN); // if (v != null) { // if (!v.requestFocus(TextView.FOCUS_DOWN)) { // throw Error(`new IllegalStateException("focus search returned a view " + "that wasn't able to take focus!")`); // } // /* // * Return true because we handled the key; super // * will return false because there was no click // * listener. // */ // super.onKeyUp(keyCode, event); // return true; // } else if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0) { // // No target for next focus, but make sure the IME // // if this came from it. // let imm:InputMethodManager = InputMethodManager.peekInstance(); // if (imm != null && imm.isActive(this)) { // imm.hideSoftInputFromWindow(this.getWindowToken(), 0); // } // } // } // } // return super.onKeyUp(keyCode, event); // } // break; //} //if (this.mEditor != null && this.mEditor.mKeyListener != null) // if (this.mEditor.mKeyListener.onKeyUp(this, <Editable> this.mText, keyCode, event)) // return true; //if (this.mMovement != null && this.mLayout != null) // if (this.mMovement.onKeyUp(this, <Spannable> this.mText, keyCode, event)) // return true; //return super.onKeyUp(keyCode, event); } onCheckIsTextEditor():boolean { return false; //return this.mEditor != null && this.mEditor.mInputType != EditorInfo.TYPE_NULL; } //onCreateInputConnection(outAttrs:EditorInfo):InputConnection { // if (this.onCheckIsTextEditor() && this.isEnabled()) { // this.mEditor.createInputMethodStateIfNeeded(); // outAttrs.inputType = this.getInputType(); // if (this.mEditor.mInputContentType != null) { // outAttrs.imeOptions = this.mEditor.mInputContentType.imeOptions; // outAttrs.privateImeOptions = this.mEditor.mInputContentType.privateImeOptions; // outAttrs.actionLabel = this.mEditor.mInputContentType.imeActionLabel; // outAttrs.actionId = this.mEditor.mInputContentType.imeActionId; // outAttrs.extras = this.mEditor.mInputContentType.extras; // } else { // outAttrs.imeOptions = EditorInfo.IME_NULL; // } // if (this.focusSearch(TextView.FOCUS_DOWN) != null) { // outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; // } // if (this.focusSearch(TextView.FOCUS_UP) != null) { // outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; // } // if ((outAttrs.imeOptions & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_UNSPECIFIED) { // if ((outAttrs.imeOptions & EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { // // An action has not been set, but the enter key will move to // // the next focus, so set the action to that. // outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; // } else { // // An action has not been set, and there is no focus to move // // to, so let's just supply a "done" action. // outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; // } // if (!this.shouldAdvanceFocusOnEnter()) { // outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; // } // } // if (TextView.isMultilineInputType(outAttrs.inputType)) { // // Multi-line text editors should always show an enter key. // outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; // } // outAttrs.hintText = this.mHint; // if (this.mText instanceof Editable) { // let ic:InputConnection = new EditableInputConnection(this); // outAttrs.initialSelStart = this.getSelectionStart(); // outAttrs.initialSelEnd = this.getSelectionEnd(); // outAttrs.initialCapsMode = ic.getCursorCapsMode(this.getInputType()); // return ic; // } // } // return null; //} // ///** // * If this TextView contains editable content, extract a portion of it // * based on the information in <var>request</var> in to <var>outText</var>. // * @return Returns true if the text was successfully extracted, else false. // */ //extractText(request:ExtractedTextRequest, outText:ExtractedText):boolean { // this.createEditorIfNeeded(); // return this.mEditor.extractText(request, outText); //} // ///** // * This is used to remove all style-impacting spans from text before new // * extracted text is being replaced into it, so that we don't have any // * lingering spans applied during the replace. // */ //static removeParcelableSpans(spannable:Spannable, start:number, end:number):void { // let spans:any[] = spannable.getSpans(start, end, ParcelableSpan.class); // let i:number = spans.length; // while (i > 0) { // i--; // spannable.removeSpan(spans[i]); // } //} // ///** // * Apply to this text view the given extracted text, as previously // * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. // */ //setExtractedText(text:ExtractedText):void { // let content:Editable = this.getEditableText(); // if (text.text != null) { // if (content == null) { // this.setText(text.text, TextView.BufferType.EDITABLE); // } else if (text.partialStartOffset < 0) { // TextView.removeParcelableSpans(content, 0, content.length()); // content.replace(0, content.length(), text.text); // } else { // const N:number = content.length(); // let start:number = text.partialStartOffset; // if (start > N) // start = N; // let end:number = text.partialEndOffset; // if (end > N) // end = N; // TextView.removeParcelableSpans(content, start, end); // content.replace(start, end, text.text); // } // } // // Now set the selection position... make sure it is in range, to // // avoid crashes. If this is a partial update, it is possible that // // the underlying text may have changed, causing us problems here. // // Also we just don't want to trust clients to do the right thing. // let sp:Spannable = <Spannable> this.getText(); // const N:number = sp.length(); // let start:number = text.selectionStart; // if (start < 0) // start = 0; // else if (start > N) // start = N; // let end:number = text.selectionEnd; // if (end < 0) // end = 0; // else if (end > N) // end = N; // Selection.setSelection(sp, start, end); // // Finally, update the selection mode. // if ((text.flags & ExtractedText.FLAG_SELECTING) != 0) { // MetaKeyKeyListener.startSelecting(this, sp); // } else { // MetaKeyKeyListener.stopSelecting(this, sp); // } //} // ///** // * @hide // */ //setExtracting(req:ExtractedTextRequest):void { // if (this.mEditor.mInputMethodState != null) { // this.mEditor.mInputMethodState.mExtractedTextRequest = req; // } // // This would stop a possible selection mode, but no such mode is started in case // // extracted mode will start. Some text is selected though, and will trigger an action mode // // in the extracted view. // this.mEditor.hideControllers(); //} // ///** // * Called by the framework in response to a text completion from // * the current input method, provided by it calling // * {@link InputConnection#commitCompletion // * InputConnection.commitCompletion()}. The default implementation does // * nothing; text views that are supporting auto-completion should override // * this to do their desired behavior. // * // * @param text The auto complete text the user has selected. // */ //onCommitCompletion(text:CompletionInfo):void { //// intentionally empty //} // ///** // * Called by the framework in response to a text auto-correction (such as fixing a typo using a // * a dictionnary) from the current input method, provided by it calling // * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default // * implementation flashes the background of the corrected word to provide feedback to the user. // * // * @param info The auto correct info about the text that was corrected. // */ //onCommitCorrection(info:CorrectionInfo):void { // if (this.mEditor != null) // this.mEditor.onCommitCorrection(info); //} // //beginBatchEdit():void { // if (this.mEditor != null) // this.mEditor.beginBatchEdit(); //} // //endBatchEdit():void { // if (this.mEditor != null) // this.mEditor.endBatchEdit(); //} // ///** // * Called by the framework in response to a request to begin a batch // * of edit operations through a call to link {@link #beginBatchEdit()}. // */ //onBeginBatchEdit():void { //// intentionally empty //} // ///** // * Called by the framework in response to a request to end a batch // * of edit operations through a call to link {@link #endBatchEdit}. // */ //onEndBatchEdit():void { //// intentionally empty //} /** * Called by the framework in response to a private command from the * current method, provided by it calling * {@link InputConnection#performPrivateCommand * InputConnection.performPrivateCommand()}. * * @param action The action name of the command. * @param data Any additional data for the command. This may be null. * @return Return true if you handled the command, else false. */ //onPrivateIMECommand(action:string, data:Bundle):boolean { // return false; //} private nullLayouts():void { if (this.mLayout instanceof BoringLayout && this.mSavedLayout == null) { this.mSavedLayout = <BoringLayout> this.mLayout; } if (this.mHintLayout instanceof BoringLayout && this.mSavedHintLayout == null) { this.mSavedHintLayout = <BoringLayout> this.mHintLayout; } this.mSavedMarqueeModeLayout = this.mLayout = this.mHintLayout = null; this.mBoring = this.mHintBoring = null; // Since it depends on the value of mLayout //if (this.mEditor != null) // this.mEditor.prepareCursorControllers(); } /** * Make a new Layout based on the already-measured size of the view, * on the assumption that it was measured correctly at some point. */ private assumeLayout():void { let width:number = this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(); if (width < 1) { width = 0; } let physicalWidth:number = width; if (this.mHorizontallyScrolling) { width = TextView.VERY_WIDE; } this.makeNewLayout(width, physicalWidth, TextView.UNKNOWN_BORING, TextView.UNKNOWN_BORING, physicalWidth, false); } private getLayoutAlignment():Layout.Alignment { let alignment:Layout.Alignment; //switch(this.getTextAlignment()) { // case TextView.TEXT_ALIGNMENT_GRAVITY: switch(this.mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { //case Gravity.START: // alignment = Layout.Alignment.ALIGN_NORMAL; // break; //case Gravity.END: // alignment = Layout.Alignment.ALIGN_OPPOSITE; // break; case Gravity.LEFT: alignment = Layout.Alignment.ALIGN_LEFT; break; case Gravity.RIGHT: alignment = Layout.Alignment.ALIGN_RIGHT; break; case Gravity.CENTER_HORIZONTAL: alignment = Layout.Alignment.ALIGN_CENTER; break; default: alignment = Layout.Alignment.ALIGN_NORMAL; break; } // break; // case TextView.TEXT_ALIGNMENT_TEXT_START: // alignment = Layout.Alignment.ALIGN_NORMAL; // break; // case TextView.TEXT_ALIGNMENT_TEXT_END: // alignment = Layout.Alignment.ALIGN_OPPOSITE; // break; // case TextView.TEXT_ALIGNMENT_CENTER: // alignment = Layout.Alignment.ALIGN_CENTER; // break; // case TextView.TEXT_ALIGNMENT_VIEW_START: // alignment = (this.getLayoutDirection() == TextView.LAYOUT_DIRECTION_RTL) ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; // break; // case TextView.TEXT_ALIGNMENT_VIEW_END: // alignment = (this.getLayoutDirection() == TextView.LAYOUT_DIRECTION_RTL) ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; // break; // case TextView.TEXT_ALIGNMENT_INHERIT: // // but better safe than sorry so we just fall through // default: // alignment = Layout.Alignment.ALIGN_NORMAL; // break; //} return alignment; } /** * The width passed in is now the desired layout width, * not the full view width with padding. * {@hide} */ protected makeNewLayout(wantWidth:number, hintWidth:number, boring:BoringLayout.Metrics, hintBoring:BoringLayout.Metrics, ellipsisWidth:number, bringIntoView:boolean):void { this.stopMarquee(); // Update "old" cached values this.mOldMaximum = this.mMaximum; this.mOldMaxMode = this.mMaxMode; this.mHighlightPathBogus = true; if (wantWidth < 0) { wantWidth = 0; } if (hintWidth < 0) { hintWidth = 0; } let alignment:Layout.Alignment = this.getLayoutAlignment(); const testDirChange:boolean = this.mSingleLine && this.mLayout != null && (alignment == Layout.Alignment.ALIGN_NORMAL || alignment == Layout.Alignment.ALIGN_OPPOSITE); let oldDir:number = 0; if (testDirChange) oldDir = this.mLayout.getParagraphDirection(0); let shouldEllipsize:boolean = this.mEllipsize != null && this.getKeyListener() == null; const switchEllipsize:boolean = this.mEllipsize == TruncateAt.MARQUEE && this.mMarqueeFadeMode != TextView.MARQUEE_FADE_NORMAL; let effectiveEllipsize:TruncateAt = this.mEllipsize; if (this.mEllipsize == TruncateAt.MARQUEE && this.mMarqueeFadeMode == TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { effectiveEllipsize = TruncateAt.END_SMALL; } if (this.mTextDir == null) { this.mTextDir = this.getTextDirectionHeuristic(); } this.mLayout = this.makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, effectiveEllipsize, effectiveEllipsize == this.mEllipsize); if (switchEllipsize) { let oppositeEllipsize:TruncateAt = effectiveEllipsize == TruncateAt.MARQUEE ? TruncateAt.END : TruncateAt.MARQUEE; this.mSavedMarqueeModeLayout = this.makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, oppositeEllipsize, effectiveEllipsize != this.mEllipsize); } shouldEllipsize = this.mEllipsize != null; this.mHintLayout = null; if (this.mHint != null) { if (shouldEllipsize) hintWidth = wantWidth; if (hintBoring == TextView.UNKNOWN_BORING) { hintBoring = BoringLayout.isBoring(this.mHint, this.mTextPaint, this.mTextDir, this.mHintBoring); if (hintBoring != null) { this.mHintBoring = hintBoring; } } if (hintBoring != null) { if (hintBoring.width <= hintWidth && (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { if (this.mSavedHintLayout != null) { this.mHintLayout = this.mSavedHintLayout.replaceOrMake(this.mHint, this.mTextPaint, hintWidth, alignment, this.mSpacingMult, this.mSpacingAdd, hintBoring, this.mIncludePad); } else { this.mHintLayout = BoringLayout.make(this.mHint, this.mTextPaint, hintWidth, alignment, this.mSpacingMult, this.mSpacingAdd, hintBoring, this.mIncludePad); } this.mSavedHintLayout = <BoringLayout> this.mHintLayout; } else if (shouldEllipsize && hintBoring.width <= hintWidth) { if (this.mSavedHintLayout != null) { this.mHintLayout = this.mSavedHintLayout.replaceOrMake(this.mHint, this.mTextPaint, hintWidth, alignment, this.mSpacingMult, this.mSpacingAdd, hintBoring, this.mIncludePad, this.mEllipsize, ellipsisWidth); } else { this.mHintLayout = BoringLayout.make(this.mHint, this.mTextPaint, hintWidth, alignment, this.mSpacingMult, this.mSpacingAdd, hintBoring, this.mIncludePad, this.mEllipsize, ellipsisWidth); } } else if (shouldEllipsize) { this.mHintLayout = new StaticLayout(this.mHint, 0, this.mHint.length, this.mTextPaint, hintWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad, this.mEllipsize, ellipsisWidth, this.mMaxMode == TextView.LINES ? this.mMaximum : Integer.MAX_VALUE); } else { this.mHintLayout = new StaticLayout(this.mHint, 0, this.mHint.length, this.mTextPaint, hintWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad); } } else if (shouldEllipsize) { this.mHintLayout = new StaticLayout(this.mHint, 0, this.mHint.length, this.mTextPaint, hintWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad, this.mEllipsize, ellipsisWidth, this.mMaxMode == TextView.LINES ? this.mMaximum : Integer.MAX_VALUE); } else { this.mHintLayout = new StaticLayout(this.mHint, 0, this.mHint.length, this.mTextPaint, hintWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad); } } if (bringIntoView || (testDirChange && oldDir != this.mLayout.getParagraphDirection(0))) { this.registerForPreDraw(); } if (this.mEllipsize == TextUtils.TruncateAt.MARQUEE) { if (!this.compressText(ellipsisWidth)) { const height:number = this.mLayoutParams.height; // start the marquee immediately if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { this.startMarquee(); } else { // Defer the start of the marquee until we know our width (see setFrame()) this.mRestartMarquee = true; } } } // CursorControllers need a non-null mLayout //if (this.mEditor != null) // this.mEditor.prepareCursorControllers(); } private makeSingleLayout(wantWidth:number, boring:BoringLayout.Metrics, ellipsisWidth:number, alignment:Layout.Alignment, shouldEllipsize:boolean, effectiveEllipsize:TruncateAt, useSaved:boolean):Layout { let result:Layout = null; if (Spannable.isImpl(this.mText)) { result = new DynamicLayout(this.mText, this.mTransformed, this.mTextPaint, wantWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad, this.getKeyListener() == null ? effectiveEllipsize : null, ellipsisWidth); } else { if (boring == TextView.UNKNOWN_BORING) { boring = BoringLayout.isBoring(this.mTransformed, this.mTextPaint, this.mTextDir, this.mBoring); if (boring != null) { this.mBoring = boring; } } if (boring != null) { if (boring.width <= wantWidth && (effectiveEllipsize == null || boring.width <= ellipsisWidth)) { if (useSaved && this.mSavedLayout != null) { result = this.mSavedLayout.replaceOrMake(this.mTransformed, this.mTextPaint, wantWidth, alignment, this.mSpacingMult, this.mSpacingAdd, boring, this.mIncludePad); } else { result = BoringLayout.make(this.mTransformed, this.mTextPaint, wantWidth, alignment, this.mSpacingMult, this.mSpacingAdd, boring, this.mIncludePad); } if (useSaved) { this.mSavedLayout = <BoringLayout> result; } } else if (shouldEllipsize && boring.width <= wantWidth) { if (useSaved && this.mSavedLayout != null) { result = this.mSavedLayout.replaceOrMake(this.mTransformed, this.mTextPaint, wantWidth, alignment, this.mSpacingMult, this.mSpacingAdd, boring, this.mIncludePad, effectiveEllipsize, ellipsisWidth); } else { result = BoringLayout.make(this.mTransformed, this.mTextPaint, wantWidth, alignment, this.mSpacingMult, this.mSpacingAdd, boring, this.mIncludePad, effectiveEllipsize, ellipsisWidth); } } else if (shouldEllipsize) { result = new StaticLayout(this.mTransformed, 0, this.mTransformed.length, this.mTextPaint, wantWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad, effectiveEllipsize, ellipsisWidth, this.mMaxMode == TextView.LINES ? this.mMaximum : Integer.MAX_VALUE); } else { result = new StaticLayout(this.mTransformed, 0, this.mTransformed.length, this.mTextPaint, wantWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad); } } else if (shouldEllipsize) { result = new StaticLayout(this.mTransformed, 0, this.mTransformed.length, this.mTextPaint, wantWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad, effectiveEllipsize, ellipsisWidth, this.mMaxMode == TextView.LINES ? this.mMaximum : Integer.MAX_VALUE); } else { result = new StaticLayout(this.mTransformed, 0, this.mTransformed.length, this.mTextPaint, wantWidth, alignment, this.mTextDir, this.mSpacingMult, this.mSpacingAdd, this.mIncludePad); } } return result; } private compressText(width:number):boolean { if (this.isHardwareAccelerated()) return false; // Only compress the text if it hasn't been compressed by the previous pass if (width > 0.0 && this.mLayout != null && this.getLineCount() == 1 && !this.mUserSetTextScaleX && this.mTextPaint.getTextScaleX() == 1.0) { const textWidth:number = this.mLayout.getLineWidth(0); const overflow:number = (textWidth + 1.0 - width) / width; if (overflow > 0.0 && overflow <= TextView.Marquee.MARQUEE_DELTA_MAX) { this.mTextPaint.setTextScaleX(1.0 - overflow - 0.005); this.post((()=>{ const inner_this=this; class _Inner implements Runnable { run():void { inner_this.requestLayout(); } } return new _Inner(); })()); return true; } } return false; } private static desired(layout:Layout):number { let n:number = layout.getLineCount(); let text:String = layout.getText(); let max:number = 0; for (let i:number = 0; i < n - 1; i++) { if (text.charAt(layout.getLineEnd(i) - 1) != '\n') return -1; } for (let i:number = 0; i < n; i++) { max = Math.max(max, layout.getLineWidth(i)); } return Math.floor(Math.ceil(max)); } /** * Set whether the TextView includes extra top and bottom padding to make * room for accents that go above the normal ascent and descent. * The default is true. * * @see #getIncludeFontPadding() * * @attr ref android.R.styleable#TextView_includeFontPadding */ setIncludeFontPadding(includepad:boolean):void { if (this.mIncludePad != includepad) { this.mIncludePad = includepad; if (this.mLayout != null) { this.nullLayouts(); this.requestLayout(); this.invalidate(); } } } /** * Gets whether the TextView includes extra top and bottom padding to make * room for accents that go above the normal ascent and descent. * * @see #setIncludeFontPadding(boolean) * * @attr ref android.R.styleable#TextView_includeFontPadding */ getIncludeFontPadding():boolean { return this.mIncludePad; } private static UNKNOWN_BORING:BoringLayout.Metrics = new BoringLayout.Metrics(); protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { let widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec); let heightMode:number = View.MeasureSpec.getMode(heightMeasureSpec); let widthSize:number = View.MeasureSpec.getSize(widthMeasureSpec); let heightSize:number = View.MeasureSpec.getSize(heightMeasureSpec); let width:number; let height:number; let boring:BoringLayout.Metrics = TextView.UNKNOWN_BORING; let hintBoring:BoringLayout.Metrics = TextView.UNKNOWN_BORING; if (this.mTextDir == null) { this.mTextDir = this.getTextDirectionHeuristic(); } let des:number = -1; let fromexisting:boolean = false; if (widthMode == View.MeasureSpec.EXACTLY) { // Parent has told us how big to be. So be it. width = widthSize; } else { if (this.mLayout != null && this.mEllipsize == null) { des = TextView.desired(this.mLayout); } if (des < 0) { boring = BoringLayout.isBoring(this.mTransformed, this.mTextPaint, this.mTextDir, this.mBoring); if (boring != null) { this.mBoring = boring; } } else { fromexisting = true; } if (boring == null || boring == TextView.UNKNOWN_BORING) { if (des < 0) { des = Math.floor(Math.ceil(Layout.getDesiredWidth(this.mTransformed, this.mTextPaint))); } width = des; } else { width = boring.width; } const dr:TextView.Drawables = this.mDrawables; if (dr != null) { width = Math.max(width, dr.mDrawableWidthTop); width = Math.max(width, dr.mDrawableWidthBottom); } if (this.mHint != null) { let hintDes:number = -1; let hintWidth:number; if (this.mHintLayout != null && this.mEllipsize == null) { hintDes = TextView.desired(this.mHintLayout); } if (hintDes < 0) { hintBoring = BoringLayout.isBoring(this.mHint, this.mTextPaint, this.mTextDir, this.mHintBoring); if (hintBoring != null) { this.mHintBoring = hintBoring; } } if (hintBoring == null || hintBoring == TextView.UNKNOWN_BORING) { if (hintDes < 0) { hintDes = Math.floor(Math.ceil(Layout.getDesiredWidth(this.mHint, this.mTextPaint))); } hintWidth = hintDes; } else { hintWidth = hintBoring.width; } if (hintWidth > width) { width = hintWidth; } } width += this.getCompoundPaddingLeft() + this.getCompoundPaddingRight(); if (this.mMaxWidthMode == TextView.EMS) { width = Math.min(width, this.mMaxWidthValue * this.getLineHeight()); } else { width = Math.min(width, this.mMaxWidthValue); } if (this.mMinWidthMode == TextView.EMS) { width = Math.max(width, this.mMinWidthValue * this.getLineHeight()); } else { width = Math.max(width, this.mMinWidthValue); } // Check against our minimum width width = Math.max(width, this.getSuggestedMinimumWidth()); if (widthMode == View.MeasureSpec.AT_MOST) { width = Math.min(widthSize, width); } } let want:number = width - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(); let unpaddedWidth:number = want; if (this.mHorizontallyScrolling) want = TextView.VERY_WIDE; let hintWant:number = want; let hintWidth:number = (this.mHintLayout == null) ? hintWant : this.mHintLayout.getWidth(); if (this.mLayout == null) { this.makeNewLayout(want, hintWant, boring, hintBoring, width - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(), false); } else { const layoutChanged:boolean = (this.mLayout.getWidth() != want) || (hintWidth != hintWant) || (this.mLayout.getEllipsizedWidth() != width - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight()); const widthChanged:boolean = (this.mHint == null) && (this.mEllipsize == null) && (want > this.mLayout.getWidth()) && (this.mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want)); const maximumChanged:boolean = (this.mMaxMode != this.mOldMaxMode) || (this.mMaximum != this.mOldMaximum); if (layoutChanged || maximumChanged) { if (!maximumChanged && widthChanged) { this.mLayout.increaseWidthTo(want); } else { this.makeNewLayout(want, hintWant, boring, hintBoring, width - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(), false); } } else { // Nothing has changed } } if (heightMode == View.MeasureSpec.EXACTLY) { // Parent has told us how big to be. So be it. height = heightSize; this.mDesiredHeightAtMeasure = -1; } else { let desired:number = this.getDesiredHeight(); height = desired; this.mDesiredHeightAtMeasure = desired; if (heightMode == View.MeasureSpec.AT_MOST) { height = Math.min(desired, heightSize); } } let unpaddedHeight:number = height - this.getCompoundPaddingTop() - this.getCompoundPaddingBottom(); if (this.mMaxMode == TextView.LINES && this.mLayout.getLineCount() > this.mMaximum) { unpaddedHeight = Math.min(unpaddedHeight, this.mLayout.getLineTop(this.mMaximum)); } /* * We didn't let makeNewLayout() register to bring the cursor into view, * so do it here if there is any possibility that it is needed. */ if (this.mMovement != null || this.mLayout.getWidth() > unpaddedWidth || this.mLayout.getHeight() > unpaddedHeight) { this.registerForPreDraw(); } else { this.scrollTo(0, 0); } this.setMeasuredDimension(width, height); } private getDesiredHeight(layout?:Layout, cap=true):number { if(arguments.length===0){ return Math.max(this.getDesiredHeight(this.mLayout, true), this.getDesiredHeight(this.mHintLayout, this.mEllipsize != null)); } if (layout == null) { return 0; } let linecount:number = layout.getLineCount(); let pad:number = this.getCompoundPaddingTop() + this.getCompoundPaddingBottom(); let desired:number = layout.getLineTop(linecount); const dr:TextView.Drawables = this.mDrawables; if (dr != null) { desired = Math.max(desired, dr.mDrawableHeightLeft); desired = Math.max(desired, dr.mDrawableHeightRight); } desired += pad; if (this.mMaxMode == TextView.LINES) { /* * Don't cap the hint to a certain number of lines. * (Do cap it, though, if we have a maximum pixel height.) */ if (cap) { if (linecount > this.mMaximum) { desired = layout.getLineTop(this.mMaximum); if (dr != null) { desired = Math.max(desired, dr.mDrawableHeightLeft); desired = Math.max(desired, dr.mDrawableHeightRight); } desired += pad; linecount = this.mMaximum; } } } else { desired = Math.min(desired, this.mMaximum); } if (this.mMinMode == TextView.LINES) { if (linecount < this.mMinimum) { desired += this.getLineHeight() * (this.mMinimum - linecount); } } else { desired = Math.max(desired, this.mMinimum); } // Check against our minimum height desired = Math.max(desired, this.getSuggestedMinimumHeight()); return desired; } /** * Check whether a change to the existing text layout requires a * new view layout. */ private checkForResize():void { let sizeChanged:boolean = false; if (this.mLayout != null) { // Check if our width changed if (this.mLayoutParams.width == LayoutParams.WRAP_CONTENT) { sizeChanged = true; this.invalidate(); } // Check if our height changed if (this.mLayoutParams.height == LayoutParams.WRAP_CONTENT) { let desiredHeight:number = this.getDesiredHeight(); if (desiredHeight != this.getHeight()) { sizeChanged = true; } } else if (this.mLayoutParams.height == LayoutParams.MATCH_PARENT) { if (this.mDesiredHeightAtMeasure >= 0) { let desiredHeight:number = this.getDesiredHeight(); if (desiredHeight != this.mDesiredHeightAtMeasure) { sizeChanged = true; } } } } if (sizeChanged) { this.requestLayout(); // caller will have already invalidated } } /** * Check whether entirely new text requires a new view layout * or merely a new text layout. */ private checkForRelayout():void { if ((this.mLayoutParams.width != LayoutParams.WRAP_CONTENT || (this.mMaxWidthMode == this.mMinWidthMode && this.mMaxWidthValue == this.mMinWidthValue)) && (this.mHint == null || this.mHintLayout != null) && (this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight() > 0)) { // Static width, so try making a new text layout. let oldht:number = this.mLayout.getHeight(); let want:number = this.mLayout.getWidth(); let hintWant:number = this.mHintLayout == null ? 0 : this.mHintLayout.getWidth(); /* * No need to bring the text into view, since the size is not * changing (unless we do the requestLayout(), in which case it * will happen at measure). */ this.makeNewLayout(want, hintWant, TextView.UNKNOWN_BORING, TextView.UNKNOWN_BORING, this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(), false); if (this.mEllipsize != TextUtils.TruncateAt.MARQUEE) { // In a fixed-height view, so use our new text layout. if (this.mLayoutParams.height != LayoutParams.WRAP_CONTENT && this.mLayoutParams.height != LayoutParams.MATCH_PARENT) { this.invalidate(); return; } // so use our new text layout. if (this.mLayout.getHeight() == oldht && (this.mHintLayout == null || this.mHintLayout.getHeight() == oldht)) { this.invalidate(); return; } } // We lose: the height has changed and we have a dynamic height. // Request a new view layout using our new text layout. this.requestLayout(); this.invalidate(); } else { // Dynamic width, so we have no choice but to request a new // view layout with a new text layout. this.nullLayouts(); this.requestLayout(); this.invalidate(); } } protected onLayout(changed:boolean, left:number, top:number, right:number, bottom:number):void { super.onLayout(changed, left, top, right, bottom); if (this.mDeferScroll >= 0) { let curs:number = this.mDeferScroll; this.mDeferScroll = -1; this.bringPointIntoView(Math.min(curs, this.mText.length)); } } private isShowingHint():boolean { return TextUtils.isEmpty(this.mText) && !TextUtils.isEmpty(this.mHint); } /** * Returns true if anything changed. */ private bringTextIntoView():boolean { let layout:Layout = this.isShowingHint() ? this.mHintLayout : this.mLayout; let line:number = 0; if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { line = layout.getLineCount() - 1; } let a:Layout.Alignment = layout.getParagraphAlignment(line); let dir:number = layout.getParagraphDirection(line); let hspace:number = this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(); let vspace:number = this.mBottom - this.mTop - this.getExtendedPaddingTop() - this.getExtendedPaddingBottom(); let ht:number = layout.getHeight(); let scrollx:number, scrolly:number; // Convert to left, center, or right alignment. if (a == Layout.Alignment.ALIGN_NORMAL) { a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; } else if (a == Layout.Alignment.ALIGN_OPPOSITE) { a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; } if (a == Layout.Alignment.ALIGN_CENTER) { /* * Keep centered if possible, or, if it is too wide to fit, * keep leading edge in view. */ let left:number = Math.floor(Math.floor(layout.getLineLeft(line))); let right:number = Math.floor(Math.ceil(layout.getLineRight(line))); if (right - left < hspace) { scrollx = (right + left) / 2 - hspace / 2; } else { if (dir < 0) { scrollx = right - hspace; } else { scrollx = left; } } } else if (a == Layout.Alignment.ALIGN_RIGHT) { let right:number = Math.floor(Math.ceil(layout.getLineRight(line))); scrollx = right - hspace; } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) scrollx = Math.floor(Math.floor(layout.getLineLeft(line))); } if (ht < vspace) { scrolly = 0; } else { if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { scrolly = ht - vspace; } else { scrolly = 0; } } if (scrollx != this.mScrollX || scrolly != this.mScrollY) { this.scrollTo(scrollx, scrolly); return true; } else { return false; } } /** * Move the point, specified by the offset, into the view if it is needed. * This has to be called after layout. Returns true if anything changed. */ bringPointIntoView(offset:number):boolean { if (this.isLayoutRequested()) { this.mDeferScroll = offset; return false; } let changed:boolean = false; let layout:Layout = this.isShowingHint() ? this.mHintLayout : this.mLayout; if (layout == null) return changed; let line:number = layout.getLineForOffset(offset); let grav:number; switch(layout.getParagraphAlignment(line)) { case Layout.Alignment.ALIGN_LEFT: grav = 1; break; case Layout.Alignment.ALIGN_RIGHT: grav = -1; break; case Layout.Alignment.ALIGN_NORMAL: grav = layout.getParagraphDirection(line); break; case Layout.Alignment.ALIGN_OPPOSITE: grav = -layout.getParagraphDirection(line); break; case Layout.Alignment.ALIGN_CENTER: default: grav = 0; break; } // We only want to clamp the cursor to fit within the layout width // in left-to-right modes, because in a right to left alignment, // we want to scroll to keep the line-right on the screen, as other // lines are likely to have text flush with the right margin, which // we want to keep visible. // A better long-term solution would probably be to measure both // the full line and a blank-trimmed version, and, for example, use // the latter measurement for centering and right alignment, but for // the time being we only implement the cursor clamping in left to // right where it is most likely to be annoying. const clamped:boolean = grav > 0; // FIXME: Is it okay to truncate this, or should we round? const x:number = Math.floor(layout.getPrimaryHorizontal(offset, clamped)); const top:number = layout.getLineTop(line); const bottom:number = layout.getLineTop(line + 1); let left:number = Math.floor(Math.floor(layout.getLineLeft(line))); let right:number = Math.floor(Math.ceil(layout.getLineRight(line))); let ht:number = layout.getHeight(); let hspace:number = this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(); let vspace:number = this.mBottom - this.mTop - this.getExtendedPaddingTop() - this.getExtendedPaddingBottom(); if (!this.mHorizontallyScrolling && right - left > hspace && right > x) { // If cursor has been clamped, make sure we don't scroll. right = Math.max(x, left + hspace); } let hslack:number = (bottom - top) / 2; let vslack:number = hslack; if (vslack > vspace / 4) vslack = vspace / 4; if (hslack > hspace / 4) hslack = hspace / 4; let hs:number = this.mScrollX; let vs:number = this.mScrollY; if (top - vs < vslack) vs = top - vslack; if (bottom - vs > vspace - vslack) vs = bottom - (vspace - vslack); if (ht - vs < vspace) vs = ht - vspace; if (0 - vs > 0) vs = 0; if (grav != 0) { if (x - hs < hslack) { hs = x - hslack; } if (x - hs > hspace - hslack) { hs = x - (hspace - hslack); } } if (grav < 0) { if (left - hs > 0) hs = left; if (right - hs < hspace) hs = right - hspace; } else if (grav > 0) { if (right - hs < hspace) hs = right - hspace; if (left - hs > 0) hs = left; } else /* grav == 0 */ { if (right - left <= hspace) { /* * If the entire text fits, center it exactly. */ hs = left - (hspace - (right - left)) / 2; } else if (x > right - hslack) { /* * If we are near the right edge, keep the right edge * at the edge of the view. */ hs = right - hspace; } else if (x < left + hslack) { /* * If we are near the left edge, keep the left edge * at the edge of the view. */ hs = left; } else if (left > hs) { /* * Is there whitespace visible at the left? Fix it if so. */ hs = left; } else if (right < hs + hspace) { /* * Is there whitespace visible at the right? Fix it if so. */ hs = right - hspace; } else { /* * Otherwise, float as needed. */ if (x - hs < hslack) { hs = x - hslack; } if (x - hs > hspace - hslack) { hs = x - (hspace - hslack); } } } if (hs != this.mScrollX || vs != this.mScrollY) { if (this.mScroller == null) { this.scrollTo(hs, vs); } else { let duration:number = AnimationUtils.currentAnimationTimeMillis() - this.mLastScroll; let dx:number = hs - this.mScrollX; let dy:number = vs - this.mScrollY; if (duration > TextView.ANIMATED_SCROLL_GAP) { this.mScroller.startScroll(this.mScrollX, this.mScrollY, dx, dy); this.awakenScrollBars(this.mScroller.getDuration()); this.invalidate(); } else { if (!this.mScroller.isFinished()) { this.mScroller.abortAnimation(); } this.scrollBy(dx, dy); } this.mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } changed = true; } if (this.isFocused()) { // will be ignored. if (this.mTempRect == null) this.mTempRect = new Rect(); this.mTempRect.set(x - 2, top, x + 2, bottom); this.getInterestingRect(this.mTempRect, line); this.mTempRect.offset(this.mScrollX, this.mScrollY); //if (this.requestRectangleOnScreen(this.mTempRect)) { // changed = true; //} } return changed; } /** * Move the cursor, if needed, so that it is at an offset that is visible * to the user. This will not move the cursor if it represents more than * one character (a selection range). This will only work if the * TextView contains spannable text; otherwise it will do nothing. * * @return True if the cursor was actually moved, false otherwise. */ moveCursorToVisibleOffset():boolean { //if (!(this.mText instanceof Spannable)) { // return false; //} //let start:number = this.getSelectionStart(); //let end:number = this.getSelectionEnd(); //if (start != end) { // return false; //} //// First: make sure the line is visible on screen: //let line:number = this.mLayout.getLineForOffset(start); //const top:number = this.mLayout.getLineTop(line); //const bottom:number = this.mLayout.getLineTop(line + 1); //const vspace:number = this.mBottom - this.mTop - this.getExtendedPaddingTop() - this.getExtendedPaddingBottom(); //let vslack:number = (bottom - top) / 2; //if (vslack > vspace / 4) // vslack = vspace / 4; //const vs:number = this.mScrollY; //if (top < (vs + vslack)) { // line = this.mLayout.getLineForVertical(vs + vslack + (bottom - top)); //} else if (bottom > (vspace + vs - vslack)) { // line = this.mLayout.getLineForVertical(vspace + vs - vslack - (bottom - top)); //} //// Next: make sure the character is visible on screen: //const hspace:number = this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(); //const hs:number = this.mScrollX; //const leftChar:number = this.mLayout.getOffsetForHorizontal(line, hs); //const rightChar:number = this.mLayout.getOffsetForHorizontal(line, hspace + hs); //// line might contain bidirectional text //const lowChar:number = leftChar < rightChar ? leftChar : rightChar; //const highChar:number = leftChar > rightChar ? leftChar : rightChar; //let newStart:number = start; //if (newStart < lowChar) { // newStart = lowChar; //} else if (newStart > highChar) { // newStart = highChar; //} //if (newStart != start) { // Selection.setSelection(<Spannable> this.mText, newStart); // return true; //} return false; } computeScroll():void { if (this.mScroller != null) { if (this.mScroller.computeScrollOffset()) { this.mScrollX = this.mScroller.getCurrX(); this.mScrollY = this.mScroller.getCurrY(); this.invalidateParentCaches(); // So we draw again this.postInvalidate(); } } } private getInterestingRect(r:Rect, line:number):void { this.convertFromViewportToContentCoordinates(r); // TODO Take left/right padding into account too? if (line == 0) r.top -= this.getExtendedPaddingTop(); if (line == this.mLayout.getLineCount() - 1) r.bottom += this.getExtendedPaddingBottom(); } private convertFromViewportToContentCoordinates(r:Rect):void { const horizontalOffset:number = this.viewportToContentHorizontalOffset(); r.left += horizontalOffset; r.right += horizontalOffset; const verticalOffset:number = this.viewportToContentVerticalOffset(); r.top += verticalOffset; r.bottom += verticalOffset; } viewportToContentHorizontalOffset():number { return this.getCompoundPaddingLeft() - this.mScrollX; } viewportToContentVerticalOffset():number { let offset:number = this.getExtendedPaddingTop() - this.mScrollY; if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { offset += this.getVerticalOffset(false); } return offset; } //debug(depth:number):void { // super.debug(depth); // let output:string = TextView.debugIndent(depth); // output += "frame={" + this.mLeft + ", " + this.mTop + ", " + this.mRight + ", " + this.mBottom + "} scroll={" + this.mScrollX + ", " + this.mScrollY + "} "; // if (this.mText != null) { // output += "mText=\"" + this.mText + "\" "; // if (this.mLayout != null) { // output += "mLayout width=" + this.mLayout.getWidth() + " height=" + this.mLayout.getHeight(); // } // } else { // output += "mText=NULL"; // } // Log.d(TextView.VIEW_LOG_TAG, output); //} /** * Convenience for {@link Selection#getSelectionStart}. */ getSelectionStart():number { return -1; //return Selection.getSelectionStart(this.getText()); } /** * Convenience for {@link Selection#getSelectionEnd}. */ getSelectionEnd():number { return -1; //return Selection.getSelectionEnd(this.getText()); } /** * Return true iff there is a selection inside this text view. */ hasSelection():boolean { const selectionStart:number = this.getSelectionStart(); const selectionEnd:number = this.getSelectionEnd(); return selectionStart >= 0 && selectionStart != selectionEnd; } ///** // * Sets the properties of this field (lines, horizontally scrolling, // * transformation method) to be for a single-line input. // * // * @attr ref android.R.styleable#TextView_singleLine // */ //setSingleLine():void { // this.setSingleLine(true); //} /** * Sets the properties of this field to transform input to ALL CAPS * display. This may use a "small caps" formatting if available. * This setting will be ignored if this field is editable or selectable. * * This call replaces the current transformation method. Disabling this * will not necessarily restore the previous behavior from before this * was enabled. * * @see #setTransformationMethod(TransformationMethod) * @attr ref android.R.styleable#TextView_textAllCaps */ setAllCaps(allCaps:boolean):void { if (allCaps) { this.setTransformationMethod(new AllCapsTransformationMethod()); } else { this.setTransformationMethod(null); } } /** * If true, sets the properties of this field (number of lines, horizontally scrolling, * transformation method) to be for a single-line input; if false, restores these to the default * conditions. * * Note that the default conditions are not necessarily those that were in effect prior this * method, and you may want to reset these properties to your custom values. * * @attr ref android.R.styleable#TextView_singleLine */ setSingleLine(singleLine = true):void { // Could be used, but may break backward compatibility. if (this.mSingleLine == singleLine) return; this.setInputTypeSingleLine(singleLine); this.applySingleLine(singleLine, true, true); } /** * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. * @param singleLine */ private setInputTypeSingleLine(singleLine:boolean):void { //if (this.mEditor != null && (this.mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { // if (singleLine) { // this.mEditor.mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; // } else { // this.mEditor.mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; // } //} } private applySingleLine(singleLine:boolean, applyTransformation:boolean, changeMaxLines:boolean):void { this.mSingleLine = singleLine; if (singleLine) { this.setLines(1); this.setHorizontallyScrolling(true); if (applyTransformation) { this.setTransformationMethod(SingleLineTransformationMethod.getInstance()); } } else { if (changeMaxLines) { this.setMaxLines(Integer.MAX_VALUE); } this.setHorizontallyScrolling(false); if (applyTransformation) { this.setTransformationMethod(null); } } } /** * Causes words in the text that are longer than the view is wide * to be ellipsized instead of broken in the middle. You may also * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} * to constrain the text to a single line. Use <code>null</code> * to turn off ellipsizing. * * If {@link #setMaxLines} has been used to set two or more lines, * {@link android.text.TextUtils.TruncateAt#END} and * {@link android.text.TextUtils.TruncateAt#MARQUEE}* are only supported * (other ellipsizing types will not do anything). * * @attr ref android.R.styleable#TextView_ellipsize */ setEllipsize(where:TextUtils.TruncateAt):void { // TruncateAt is an enum. != comparison is ok between these singleton objects. if (this.mEllipsize != where) { this.mEllipsize = where; if (this.mLayout != null) { this.nullLayouts(); this.requestLayout(); this.invalidate(); } } } /** * Sets how many times to repeat the marquee animation. Only applied if the * TextView has marquee enabled. Set to -1 to repeat indefinitely. * * @see #getMarqueeRepeatLimit() * * @attr ref android.R.styleable#TextView_marqueeRepeatLimit */ setMarqueeRepeatLimit(marqueeLimit:number):void { this.mMarqueeRepeatLimit = marqueeLimit; } /** * Gets the number of times the marquee animation is repeated. Only meaningful if the * TextView has marquee enabled. * * @return the number of times the marquee animation is repeated. -1 if the animation * repeats indefinitely * * @see #setMarqueeRepeatLimit(int) * * @attr ref android.R.styleable#TextView_marqueeRepeatLimit */ getMarqueeRepeatLimit():number { return this.mMarqueeRepeatLimit; } /** * Returns where, if anywhere, words that are longer than the view * is wide should be ellipsized. */ getEllipsize():TextUtils.TruncateAt { return this.mEllipsize; } /** * Set the TextView so that when it takes focus, all the text is * selected. * * @attr ref android.R.styleable#TextView_selectAllOnFocus */ setSelectAllOnFocus(selectAllOnFocus:boolean):void { this.createEditorIfNeeded(); this.mEditor.mSelectAllOnFocus = selectAllOnFocus; if (selectAllOnFocus && !Spannable.isImpl(this.mText)) { this.setText(this.mText, TextView.BufferType.SPANNABLE); } } /** * Set whether the cursor is visible. The default is true. Note that this property only * makes sense for editable TextView. * * @see #isCursorVisible() * * @attr ref android.R.styleable#TextView_cursorVisible */ setCursorVisible(visible:boolean):void { // visible is the default value with no edit data //if (visible && this.mEditor == null) // return; //this.createEditorIfNeeded(); //if (this.mEditor.mCursorVisible != visible) { // this.mEditor.mCursorVisible = visible; // this.invalidate(); // this.mEditor.makeBlink(); // // InsertionPointCursorController depends on mCursorVisible // this.mEditor.prepareCursorControllers(); //} } /** * @return whether or not the cursor is visible (assuming this TextView is editable) * * @see #setCursorVisible(boolean) * * @attr ref android.R.styleable#TextView_cursorVisible */ isCursorVisible():boolean { // true is the default value return null; //return this.mEditor == null ? true : this.mEditor.mCursorVisible; } private canMarquee():boolean { let width:number = (this.mRight - this.mLeft - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight()); return width > 0 && (this.mLayout.getLineWidth(0) > width || (this.mMarqueeFadeMode != TextView.MARQUEE_FADE_NORMAL && this.mSavedMarqueeModeLayout != null && this.mSavedMarqueeModeLayout.getLineWidth(0) > width)); } private startMarquee():void { // Do not ellipsize EditText if (this.getKeyListener() != null) return; if (this.compressText(this.getWidth() - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight())) { return; } if ((this.mMarquee == null || this.mMarquee.isStopped()) && (this.isFocused() || this.isSelected()) && this.getLineCount() == 1 && this.canMarquee()) { if (this.mMarqueeFadeMode == TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { this.mMarqueeFadeMode = TextView.MARQUEE_FADE_SWITCH_SHOW_FADE; const tmp:Layout = this.mLayout; this.mLayout = this.mSavedMarqueeModeLayout; this.mSavedMarqueeModeLayout = tmp; this.setHorizontalFadingEdgeEnabled(true); this.requestLayout(); this.invalidate(); } if (this.mMarquee == null) this.mMarquee = new TextView.Marquee(this); this.mMarquee.start(this.mMarqueeRepeatLimit); } } private stopMarquee():void { if (this.mMarquee != null && !this.mMarquee.isStopped()) { this.mMarquee.stop(); } if (this.mMarqueeFadeMode == TextView.MARQUEE_FADE_SWITCH_SHOW_FADE) { this.mMarqueeFadeMode = TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; const tmp:Layout = this.mSavedMarqueeModeLayout; this.mSavedMarqueeModeLayout = this.mLayout; this.mLayout = tmp; this.setHorizontalFadingEdgeEnabled(false); this.requestLayout(); this.invalidate(); } } private startStopMarquee(start:boolean):void { if (this.mEllipsize == TextUtils.TruncateAt.MARQUEE) { if (start) { this.startMarquee(); } else { this.stopMarquee(); } } } /** * This method is called when the text is changed, in case any subclasses * would like to know. * * Within <code>text</code>, the <code>lengthAfter</code> characters * beginning at <code>start</code> have just replaced old text that had * length <code>lengthBefore</code>. It is an error to attempt to make * changes to <code>text</code> from this callback. * * @param text The text the TextView is displaying * @param start The offset of the start of the range of the text that was * modified * @param lengthBefore The length of the former text that has been replaced * @param lengthAfter The length of the replacement modified text */ protected onTextChanged(text:String, start:number, lengthBefore:number, lengthAfter:number):void { // intentionally empty, template pattern method can be overridden by subclasses } /** * This method is called when the selection has changed, in case any * subclasses would like to know. * * @param selStart The new selection start location. * @param selEnd The new selection end location. */ protected onSelectionChanged(selStart:number, selEnd:number):void { //this.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); } /** * Adds a TextWatcher to the list of those whose methods are called * whenever this TextView's text changes. * <p> * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously * not called after {@link #setText} calls. Now, doing {@link #setText} * if there are any text changed listeners forces the buffer type to * Editable if it would not otherwise be and does call this method. */ addTextChangedListener(watcher:TextWatcher):void { if (this.mListeners == null) { this.mListeners = new ArrayList<TextWatcher>(); } this.mListeners.add(watcher); } /** * Removes the specified TextWatcher from the list of those whose * methods are called * whenever this TextView's text changes. */ removeTextChangedListener(watcher:TextWatcher):void { if (this.mListeners != null) { let i:number = this.mListeners.indexOf(watcher); if (i >= 0) { this.mListeners.remove(i); } } } private sendBeforeTextChanged(text:String, start:number, before:number, after:number):void { if (this.mListeners != null) { const list:ArrayList<TextWatcher> = this.mListeners; const count:number = list.size(); for (let i:number = 0; i < count; i++) { list.get(i).beforeTextChanged(text, start, before, after); } } // The spans that are inside or intersect the modified region no longer make sense //this.removeIntersectingNonAdjacentSpans(start, start + before, SpellCheckSpan.class); //this.removeIntersectingNonAdjacentSpans(start, start + before, SuggestionSpan.class); } // Removes all spans that are inside or actually overlap the start..end range //private removeIntersectingNonAdjacentSpans<T> (start:number, end:number, type:Class<T>):void { // if (!(this.mText instanceof Editable)) // return; // let text:Editable = <Editable> this.mText; // let spans:T[] = text.getSpans(start, end, type); // const length:number = spans.length; // for (let i:number = 0; i < length; i++) { // const spanStart:number = text.getSpanStart(spans[i]); // const spanEnd:number = text.getSpanEnd(spans[i]); // if (spanEnd == start || spanStart == end) // break; // text.removeSpan(spans[i]); // } //} removeAdjacentSuggestionSpans(pos:number):void { //if (!(this.mText instanceof Editable)) // return; //const text:Editable = <Editable> this.mText; //const spans:SuggestionSpan[] = text.getSpans(pos, pos, SuggestionSpan.class); //const length:number = spans.length; //for (let i:number = 0; i < length; i++) { // const spanStart:number = text.getSpanStart(spans[i]); // const spanEnd:number = text.getSpanEnd(spans[i]); // if (spanEnd == pos || spanStart == pos) { // if (SpellChecker.haveWordBoundariesChanged(text, pos, pos, spanStart, spanEnd)) { // text.removeSpan(spans[i]); // } // } //} } /** * Not private so it can be called from an inner class without going * through a thunk. */ sendOnTextChanged(text:String, start:number, before:number, after:number):void { if (this.mListeners != null) { const list:ArrayList<TextWatcher> = this.mListeners; const count:number = list.size(); for (let i:number = 0; i < count; i++) { list.get(i).onTextChanged(text, start, before, after); } } //if (this.mEditor != null) // this.mEditor.sendOnTextChanged(start, after); } /** * Not private so it can be called from an inner class without going * through a thunk. */ sendAfterTextChanged(text:any):void { if (this.mListeners != null) { const list:ArrayList<TextWatcher> = this.mListeners; const count:number = list.size(); for (let i:number = 0; i < count; i++) { list.get(i).afterTextChanged(text+''); } } } updateAfterEdit():void { this.invalidate(); let curs:number = this.getSelectionStart(); if (curs >= 0 || (this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { this.registerForPreDraw(); } this.checkForResize(); if (curs >= 0) { this.mHighlightPathBogus = true; //if (this.mEditor != null) // this.mEditor.makeBlink(); this.bringPointIntoView(curs); } } /** * Not private so it can be called from an inner class without going * through a thunk. */ handleTextChanged(buffer:String, start:number, before:number, after:number):void { //const ims:Editor.InputMethodState = this.mEditor == null ? null : this.mEditor.mInputMethodState; //if (ims == null || ims.mBatchEditNesting == 0) { this.updateAfterEdit(); //} //if (ims != null) { // ims.mContentChanged = true; // if (ims.mChangedStart < 0) { // ims.mChangedStart = start; // ims.mChangedEnd = start + before; // } else { // ims.mChangedStart = Math.min(ims.mChangedStart, start); // ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); // } // ims.mChangedDelta += after - before; //} this.sendOnTextChanged(buffer, start, before, after); this.onTextChanged(buffer, start, before, after); } /** * Not private so it can be called from an inner class without going * through a thunk. */ spanChange(buf:Spanned, what:any, oldStart:number, newStart:number, oldEnd:number, newEnd:number):void { // XXX Make the start and end move together if this ends up // spending too much time invalidating. let selChanged:boolean = false; let newSelStart:number = -1, newSelEnd:number = -1; //const ims:Editor.InputMethodState = this.mEditor == null ? null : this.mEditor.mInputMethodState; //if (what == Selection.SELECTION_END) { // selChanged = true; // newSelEnd = newStart; // if (oldStart >= 0 || newStart >= 0) { // this.invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); // this.checkForResize(); // this.registerForPreDraw(); // if (this.mEditor != null) // this.mEditor.makeBlink(); // } //} //if (what == Selection.SELECTION_START) { // selChanged = true; // newSelStart = newStart; // if (oldStart >= 0 || newStart >= 0) { // let end:number = Selection.getSelectionEnd(buf); // this.invalidateCursor(end, oldStart, newStart); // } //} //if (selChanged) { // this.mHighlightPathBogus = true; // if (this.mEditor != null && !this.isFocused()) // this.mEditor.mSelectionMoved = true; // if ((buf.getSpanFlags(what) & Spanned.SPAN_INTERMEDIATE) == 0) { // if (newSelStart < 0) { // newSelStart = Selection.getSelectionStart(buf); // } // if (newSelEnd < 0) { // newSelEnd = Selection.getSelectionEnd(buf); // } // this.onSelectionChanged(newSelStart, newSelEnd); // } //} //if (what instanceof UpdateAppearance || what instanceof ParagraphStyle || what instanceof CharacterStyle) { //if (ims == null || ims.mBatchEditNesting == 0) { this.invalidate(); this.mHighlightPathBogus = true; this.checkForResize(); //} else { // ims.mContentChanged = true; //} //if (this.mEditor != null) { // if (oldStart >= 0) // this.mEditor.invalidateTextDisplayList(this.mLayout, oldStart, oldEnd); // if (newStart >= 0) // this.mEditor.invalidateTextDisplayList(this.mLayout, newStart, newEnd); //} //} //if (MetaKeyKeyListener.isMetaTracker(buf, what)) { // this.mHighlightPathBogus = true; // if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { // ims.mSelectionModeChanged = true; // } // if (Selection.getSelectionStart(buf) >= 0) { // if (ims == null || ims.mBatchEditNesting == 0) { // this.invalidateCursor(); // } else { // ims.mCursorChanged = true; // } // } //} //if (what instanceof ParcelableSpan) { // // the current extract editor would be interested in it. // if (ims != null && ims.mExtractedTextRequest != null) { // if (ims.mBatchEditNesting != 0) { // if (oldStart >= 0) { // if (ims.mChangedStart > oldStart) { // ims.mChangedStart = oldStart; // } // if (ims.mChangedStart > oldEnd) { // ims.mChangedStart = oldEnd; // } // } // if (newStart >= 0) { // if (ims.mChangedStart > newStart) { // ims.mChangedStart = newStart; // } // if (ims.mChangedStart > newEnd) { // ims.mChangedStart = newEnd; // } // } // } else { // if (TextView.DEBUG_EXTRACT) // Log.v(TextView.LOG_TAG, "Span change outside of batch: " + oldStart + "-" + oldEnd + "," + newStart + "-" + newEnd + " " + what); // ims.mContentChanged = true; // } // } //} //if (this.mEditor != null && this.mEditor.mSpellChecker != null && newStart < 0 && what instanceof SpellCheckSpan) { // this.mEditor.mSpellChecker.onSpellCheckSpanRemoved(<SpellCheckSpan> what); //} } /** * @hide */ dispatchFinishTemporaryDetach():void { this.mDispatchTemporaryDetach = true; super.dispatchFinishTemporaryDetach(); this.mDispatchTemporaryDetach = false; } onStartTemporaryDetach():void { super.onStartTemporaryDetach(); // usually because this instance is an editable field in a list if (!this.mDispatchTemporaryDetach) this.mTemporaryDetach = true; // selection state as needed. //if (this.mEditor != null) // this.mEditor.mTemporaryDetach = true; } onFinishTemporaryDetach():void { super.onFinishTemporaryDetach(); // usually because this instance is an editable field in a list if (!this.mDispatchTemporaryDetach) this.mTemporaryDetach = false; //if (this.mEditor != null) // this.mEditor.mTemporaryDetach = false; } protected onFocusChanged(focused:boolean, direction:number, previouslyFocusedRect:Rect):void { if (this.mTemporaryDetach) { // If we are temporarily in the detach state, then do nothing. super.onFocusChanged(focused, direction, previouslyFocusedRect); return; } //if (this.mEditor != null) // this.mEditor.onFocusChanged(focused, direction); //if (focused) { // if (this.mText instanceof Spannable) { // let sp:Spannable = <Spannable> this.mText; // MetaKeyKeyListener.resetMetaState(sp); // } //} this.startStopMarquee(focused); if (this.mTransformation != null) { this.mTransformation.onFocusChanged(this, this.mText, focused, direction, previouslyFocusedRect); } super.onFocusChanged(focused, direction, previouslyFocusedRect); } onWindowFocusChanged(hasWindowFocus:boolean):void { super.onWindowFocusChanged(hasWindowFocus); //if (this.mEditor != null) // this.mEditor.onWindowFocusChanged(hasWindowFocus); this.startStopMarquee(hasWindowFocus); } protected onVisibilityChanged(changedView:View, visibility:number):void { super.onVisibilityChanged(changedView, visibility); //if (this.mEditor != null && visibility != TextView.VISIBLE) { // this.mEditor.hideControllers(); //} } /** * Use {@link BaseInputConnection#removeComposingSpans * BaseInputConnection.removeComposingSpans()} to remove any IME composing * state from this text view. */ clearComposingText():void { //if (this.mText instanceof Spannable) { // BaseInputConnection.removeComposingSpans(<Spannable> this.mText); //} } setSelected(selected:boolean):void { let wasSelected:boolean = this.isSelected(); super.setSelected(selected); if (selected != wasSelected && this.mEllipsize == TextUtils.TruncateAt.MARQUEE) { if (selected) { this.startMarquee(); } else { this.stopMarquee(); } } } onTouchEvent(event:MotionEvent):boolean { const action:number = event.getActionMasked(); //if (this.mEditor != null) // this.mEditor.onTouchEvent(event); const superResult:boolean = super.onTouchEvent(event); /* * Don't handle the release after a long press, because it will * move the selection away from whatever the menu action was * trying to affect. */ //if (this.mEditor != null && this.mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { // this.mEditor.mDiscardNextActionUp = false; // return superResult; //} const touchIsFinished:boolean = (action == MotionEvent.ACTION_UP) //&& (this.mEditor == null || !this.mEditor.mIgnoreActionUpEvent) && this.isFocused(); if ((this.mMovement != null || this.onCheckIsTextEditor()) && this.isEnabled() && Spannable.isImpl(this.mText) && this.mLayout != null) { let handled:boolean = false; if (this.mMovement != null) { handled = this.mMovement.onTouchEvent(this, <Spannable> this.mText, event) || handled; } //const textIsSelectable:boolean = this.isTextSelectable(); //if (touchIsFinished && this.mLinksClickable && this.mAutoLinkMask != 0 && textIsSelectable) { // // The LinkMovementMethod which should handle taps on links has not been installed // // on non editable text that support text selection. // // We reproduce its behavior here to open links for these. // let links:ClickableSpan[] = (<Spannable> this.mText).getSpans(this.getSelectionStart(), this.getSelectionEnd(), ClickableSpan.class); // if (links.length > 0) { // links[0].onClick(this); // handled = true; // } //} //if (touchIsFinished && (this.isTextEditable() || textIsSelectable)) { // // Show the IME, except when selecting in read-only text. // const imm:InputMethodManager = InputMethodManager.peekInstance(); // this.viewClicked(imm); // if (!textIsSelectable && this.mEditor.mShowSoftInputOnFocus) { // handled |= imm != null && imm.showSoftInput(this, 0); // } // // The above condition ensures that the mEditor is not null // this.mEditor.onTouchUpEvent(event); // handled = true; //} if (handled) { return true; } } return superResult; } onGenericMotionEvent(event:MotionEvent):boolean { if (this.mMovement != null && Spannable.isImpl(this.mText) && this.mLayout != null) { try { if (this.mMovement.onGenericMotionEvent(this, <Spannable> this.mText, event)) { return true; } } catch (e){ } } return super.onGenericMotionEvent(event); } /** * @return True iff this TextView contains a text that can be edited, or if this is * a selectable TextView. */ isTextEditable():boolean { return false; //return this.mText instanceof Editable && this.onCheckIsTextEditor() && this.isEnabled(); } /** * Returns true, only while processing a touch gesture, if the initial * touch down event caused focus to move to the text view and as a result * its selection changed. Only valid while processing the touch gesture * of interest, in an editable text view. */ didTouchFocusSelect():boolean { return false; //return this.mEditor != null && this.mEditor.mTouchFocusSelected; } cancelLongPress():void { super.cancelLongPress(); //if (this.mEditor != null) // this.mEditor.mIgnoreActionUpEvent = true; } //onTrackballEvent(event:MotionEvent):boolean { // if (this.mMovement != null && Spannable.isImpl(this.mText) && this.mLayout != null) { // if (this.mMovement.onTrackballEvent(this, <Spannable> this.mText, event)) { // return true; // } // } // return super.onTrackballEvent(event); //} setScroller(s:OverScroller):void { this.mScroller = s; } protected getLeftFadingEdgeStrength():number { if (this.mEllipsize == TextUtils.TruncateAt.MARQUEE && this.mMarqueeFadeMode != TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { if (this.mMarquee != null && !this.mMarquee.isStopped()) { const marquee:TextView.Marquee = this.mMarquee; if (marquee.shouldDrawLeftFade()) { const scroll:number = marquee.getScroll(); return scroll / this.getHorizontalFadingEdgeLength(); } else { return 0.0; } } else if (this.getLineCount() == 1) { //const layoutDirection:number = this.getLayoutDirection(); const absoluteGravity:number = this.mGravity;//Gravity.getAbsoluteGravity(this.mGravity, layoutDirection); switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: return 0.0; case Gravity.RIGHT: return (this.mLayout.getLineRight(0) - (this.mRight - this.mLeft) - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight() - this.mLayout.getLineLeft(0)) / this.getHorizontalFadingEdgeLength(); case Gravity.CENTER_HORIZONTAL: case Gravity.FILL_HORIZONTAL: const textDirection:number = this.mLayout.getParagraphDirection(0); if (textDirection == Layout.DIR_LEFT_TO_RIGHT) { return 0.0; } else { return (this.mLayout.getLineRight(0) - (this.mRight - this.mLeft) - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight() - this.mLayout.getLineLeft(0)) / this.getHorizontalFadingEdgeLength(); } } } } return super.getLeftFadingEdgeStrength(); } protected getRightFadingEdgeStrength():number { if (this.mEllipsize == TextUtils.TruncateAt.MARQUEE && this.mMarqueeFadeMode != TextView.MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { if (this.mMarquee != null && !this.mMarquee.isStopped()) { const marquee:TextView.Marquee = this.mMarquee; const maxFadeScroll:number = marquee.getMaxFadeScroll(); const scroll:number = marquee.getScroll(); return (maxFadeScroll - scroll) / this.getHorizontalFadingEdgeLength(); } else if (this.getLineCount() == 1) { //const layoutDirection:number = this.getLayoutDirection(); const absoluteGravity:number = this.mGravity;//Gravity.getAbsoluteGravity(this.mGravity, layoutDirection); switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: const textWidth:number = (this.mRight - this.mLeft) - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight(); const lineWidth:number = this.mLayout.getLineWidth(0); return (lineWidth - textWidth) / this.getHorizontalFadingEdgeLength(); case Gravity.RIGHT: return 0.0; case Gravity.CENTER_HORIZONTAL: case Gravity.FILL_HORIZONTAL: const textDirection:number = this.mLayout.getParagraphDirection(0); if (textDirection == Layout.DIR_RIGHT_TO_LEFT) { return 0.0; } else { return (this.mLayout.getLineWidth(0) - ((this.mRight - this.mLeft) - this.getCompoundPaddingLeft() - this.getCompoundPaddingRight())) / this.getHorizontalFadingEdgeLength(); } } } } return super.getRightFadingEdgeStrength(); } protected computeHorizontalScrollRange():number { if (this.mLayout != null) { return this.mSingleLine && (this.mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? Math.floor(this.mLayout.getLineWidth(0)) : this.mLayout.getWidth(); } return super.computeHorizontalScrollRange(); } protected computeVerticalScrollRange():number { if (this.mLayout != null) return this.mLayout.getHeight(); return super.computeVerticalScrollRange(); } protected computeVerticalScrollExtent():number { return this.getHeight() - this.getCompoundPaddingTop() - this.getCompoundPaddingBottom(); } //findViewsWithText(outViews:ArrayList<View>, searched:String, flags:number):void { // super.findViewsWithText(outViews, searched, flags); // if (!outViews.contains(this) && (flags & TextView.FIND_VIEWS_WITH_TEXT) != 0 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(this.mText)) { // let searchedLowerCase:string = searched.toString().toLowerCase(); // let textLowerCase:string = this.mText.toString().toLowerCase(); // if (textLowerCase.contains(searchedLowerCase)) { // outViews.add(this); // } // } //} /** * Returns the TextView_textColor attribute from the * TypedArray, if set, or the TextAppearance_textColor * from the TextView_textAppearance attribute, if TextView_textColor * was not set directly. */ static getTextColors():ColorStateList { return android.R.color.textView_textColor; } /** * Returns the default color from the TextView_textColor attribute * from the AttributeSet, if set, or the default color from the * TextAppearance_textColor from the TextView_textAppearance attribute, * if TextView_textColor was not set directly. */ static getTextColor(def:number):number { let colors:ColorStateList = this.getTextColors(); if (colors == null) { return def; } else { return colors.getDefaultColor(); } } //onKeyShortcut(keyCode:number, event:KeyEvent):boolean { // const filteredMetaState:number = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; // if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { // switch(keyCode) { // case KeyEvent.KEYCODE_A: // if (this.canSelectText()) { // return this.onTextContextMenuItem(TextView.ID_SELECT_ALL); // } // break; // case KeyEvent.KEYCODE_X: // if (this.canCut()) { // return this.onTextContextMenuItem(TextView.ID_CUT); // } // break; // case KeyEvent.KEYCODE_C: // if (this.canCopy()) { // return this.onTextContextMenuItem(TextView.ID_COPY); // } // break; // case KeyEvent.KEYCODE_V: // if (this.canPaste()) { // return this.onTextContextMenuItem(TextView.ID_PASTE); // } // break; // } // } // return super.onKeyShortcut(keyCode, event); //} /** * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have * a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not * sufficient. */ private canSelectText():boolean { return false; //return this.mText.length() != 0 && this.mEditor != null && this.mEditor.hasSelectionController(); } /** * Test based on the <i>intrinsic</i> charateristics of the TextView. * The text must be spannable and the movement method must allow for arbitary selection. * * See also {@link #canSelectText()}. */ textCanBeSelected():boolean { return false; //// the value of this condition might be changed. //if (this.mMovement == null || !this.mMovement.canSelectArbitrarily()) // return false; //return this.isTextEditable() || (this.isTextSelectable() && this.mText instanceof Spannable && this.isEnabled()); } //private getTextServicesLocale(allowNullLocale:boolean):Locale { // // Start fetching the text services locale asynchronously. // this.updateTextServicesLocaleAsync(); // // locale. // return (this.mCurrentSpellCheckerLocaleCache == null && !allowNullLocale) ? Locale.getDefault() : this.mCurrentSpellCheckerLocaleCache; //} // ///** // * This is a temporary method. Future versions may support multi-locale text. // * Caveat: This method may not return the latest text services locale, but this should be // * acceptable and it's more important to make this method asynchronous. // * // * @return The locale that should be used for a word iterator // * in this TextView, based on the current spell checker settings, // * the current IME's locale, or the system default locale. // * Please note that a word iterator in this TextView is different from another word iterator // * used by SpellChecker.java of TextView. This method should be used for the former. // * @hide // */ //// TODO: Support multi-locale //// TODO: Update the text services locale immediately after the keyboard locale is switched //// by catching intent of keyboard switch event //getTextServicesLocale():Locale { // return this.getTextServicesLocale(false); //} // ///** // * This is a temporary method. Future versions may support multi-locale text. // * Caveat: This method may not return the latest spell checker locale, but this should be // * acceptable and it's more important to make this method asynchronous. // * // * @return The locale that should be used for a spell checker in this TextView, // * based on the current spell checker settings, the current IME's locale, or the system default // * locale. // * @hide // */ //getSpellCheckerLocale():Locale { // return this.getTextServicesLocale(true); //} // //private updateTextServicesLocaleAsync():void { // // AsyncTask.execute() uses a serial executor which means we don't have // // to lock around updateTextServicesLocaleLocked() to prevent it from // // being executed n times in parallel. // AsyncTask.execute((()=>{ // const inner_this=this; // class _Inner extends Runnable { // // run():void { // inner_this.updateTextServicesLocaleLocked(); // } // } // return new _Inner(); // })()); //} // //private updateTextServicesLocaleLocked():void { // const textServicesManager:TextServicesManager = <TextServicesManager> this.mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); // const subtype:SpellCheckerSubtype = textServicesManager.getCurrentSpellCheckerSubtype(true); // let locale:Locale; // if (subtype != null) { // locale = SpellCheckerSubtype.constructLocaleFromString(subtype.getLocale()); // } else { // locale = null; // } // this.mCurrentSpellCheckerLocaleCache = locale; //} //onLocaleChanged():void { // // Will be re-created on demand in getWordIterator with the proper new locale // this.mEditor.mWordIterator = null; //} // ///** // * This method is used by the ArrowKeyMovementMethod to jump from one word to the other. // * Made available to achieve a consistent behavior. // * @hide // */ //getWordIterator():WordIterator { // if (this.mEditor != null) { // return this.mEditor.getWordIterator(); // } else { // return null; // } //} // //onPopulateAccessibilityEvent(event:AccessibilityEvent):void { // super.onPopulateAccessibilityEvent(event); // const isPassword:boolean = this.hasPasswordTransformationMethod(); // if (!isPassword || this.shouldSpeakPasswordsForAccessibility()) { // const text:CharSequence = this.getTextForAccessibility(); // if (!TextUtils.isEmpty(text)) { // event.getText().add(text); // } // } //} // ///** // * @return true if the user has explicitly allowed accessibility services // * to speak passwords. // */ //private shouldSpeakPasswordsForAccessibility():boolean { // return (Settings.Secure.getInt(this.mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0) == 1); //} // //onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(TextView.class.getName()); // const isPassword:boolean = this.hasPasswordTransformationMethod(); // event.setPassword(isPassword); // if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { // event.setFromIndex(Selection.getSelectionStart(this.mText)); // event.setToIndex(Selection.getSelectionEnd(this.mText)); // event.setItemCount(this.mText.length()); // } //} // //onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(TextView.class.getName()); // const isPassword:boolean = this.hasPasswordTransformationMethod(); // info.setPassword(isPassword); // if (!isPassword) { // info.setText(this.getTextForAccessibility()); // } // if (this.mBufferType == TextView.BufferType.EDITABLE) { // info.setEditable(true); // } // if (this.mEditor != null) { // info.setInputType(this.mEditor.mInputType); // if (this.mEditor.mError != null) { // info.setContentInvalid(true); // } // } // if (!TextUtils.isEmpty(this.mText)) { // info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); // info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); // info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE); // } // if (this.isFocused()) { // if (this.canSelectText()) { // info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); // } // if (this.canCopy()) { // info.addAction(AccessibilityNodeInfo.ACTION_COPY); // } // if (this.canPaste()) { // info.addAction(AccessibilityNodeInfo.ACTION_PASTE); // } // if (this.canCut()) { // info.addAction(AccessibilityNodeInfo.ACTION_CUT); // } // } // if (!this.isSingleLine()) { // info.setMultiLine(true); // } //} //performAccessibilityAction(action:number, arguments:Bundle):boolean { // switch(action) { // case AccessibilityNodeInfo.ACTION_COPY: // { // if (this.isFocused() && this.canCopy()) { // if (this.onTextContextMenuItem(TextView.ID_COPY)) { // return true; // } // } // } // return false; // case AccessibilityNodeInfo.ACTION_PASTE: // { // if (this.isFocused() && this.canPaste()) { // if (this.onTextContextMenuItem(TextView.ID_PASTE)) { // return true; // } // } // } // return false; // case AccessibilityNodeInfo.ACTION_CUT: // { // if (this.isFocused() && this.canCut()) { // if (this.onTextContextMenuItem(TextView.ID_CUT)) { // return true; // } // } // } // return false; // case AccessibilityNodeInfo.ACTION_SET_SELECTION: // { // if (this.isFocused() && this.canSelectText()) { // let text:CharSequence = this.getIterableTextForAccessibility(); // if (text == null) { // return false; // } // const start:number = (arguments != null) ? arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; // const end:number = (arguments != null) ? arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; // if ((this.getSelectionStart() != start || this.getSelectionEnd() != end)) { // // No arguments clears the selection. // if (start == end && end == -1) { // Selection.removeSelection(<Spannable> text); // return true; // } // if (start >= 0 && start <= end && end <= text.length()) { // Selection.setSelection(<Spannable> text, start, end); // // Make sure selection mode is engaged. // if (this.mEditor != null) { // this.mEditor.startSelectionActionMode(); // } // return true; // } // } // } // } // return false; // default: // { // return super.performAccessibilityAction(action, arguments); // } // } //} // //sendAccessibilityEvent(eventType:number):void { // // For details see the implementation of bringTextIntoView(). // if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) { // return; // } // super.sendAccessibilityEvent(eventType); //} // ///** // * Gets the text reported for accessibility purposes. // * // * @return The accessibility text. // * // * @hide // */ //getTextForAccessibility():CharSequence { // let text:CharSequence = this.getText(); // if (TextUtils.isEmpty(text)) { // text = this.getHint(); // } // return text; //} // //sendAccessibilityEventTypeViewTextChanged(beforeText:CharSequence, fromIndex:number, removedCount:number, addedCount:number):void { // let event:AccessibilityEvent = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); // event.setFromIndex(fromIndex); // event.setRemovedCount(removedCount); // event.setAddedCount(addedCount); // event.setBeforeText(beforeText); // this.sendAccessibilityEventUnchecked(event); //} // ///** // * Returns whether this text view is a current input method target. The // * default implementation just checks with {@link InputMethodManager}. // */ //isInputMethodTarget():boolean { // let imm:InputMethodManager = InputMethodManager.peekInstance(); // return imm != null && imm.isActive(this); //} // //static ID_SELECT_ALL:number = android.R.id.selectAll; // //static ID_CUT:number = android.R.id.cut; // //static ID_COPY:number = android.R.id.copy; // //static ID_PASTE:number = android.R.id.paste; // ///** // * Called when a context menu option for the text view is selected. Currently // * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut}, // * {@link android.R.id#copy} or {@link android.R.id#paste}. // * // * @return true if the context menu item action was performed. // */ //onTextContextMenuItem(id:number):boolean { // let min:number = 0; // let max:number = this.mText.length(); // if (this.isFocused()) { // const selStart:number = this.getSelectionStart(); // const selEnd:number = this.getSelectionEnd(); // min = Math.max(0, Math.min(selStart, selEnd)); // max = Math.max(0, Math.max(selStart, selEnd)); // } // switch(id) { // case TextView.ID_SELECT_ALL: // // This does not enter text selection mode. Text is highlighted, so that it can be // // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. // this.selectAllText(); // return true; // case TextView.ID_PASTE: // this.paste(min, max); // return true; // case TextView.ID_CUT: // this.setPrimaryClip(ClipData.newPlainText(null, this.getTransformedText(min, max))); // this.deleteText_internal(min, max); // this.stopSelectionActionMode(); // return true; // case TextView.ID_COPY: // this.setPrimaryClip(ClipData.newPlainText(null, this.getTransformedText(min, max))); // this.stopSelectionActionMode(); // return true; // } // return false; //} getTransformedText(start:number, end:number):String { return this.removeSuggestionSpans(this.mTransformed.substring(start, end)); } performLongClick():boolean { let handled:boolean = false; if (super.performLongClick()) { handled = true; } //if (this.mEditor != null) { // handled |= this.mEditor.performLongClick(handled); //} if (handled) { this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); //if (this.mEditor != null) // this.mEditor.mDiscardNextActionUp = true; } return handled; } //protected onScrollChanged(horiz:number, vert:number, oldHoriz:number, oldVert:number):void { // super.onScrollChanged(horiz, vert, oldHoriz, oldVert); // if (this.mEditor != null) { // this.mEditor.onScrollChanged(); // } //} /** * Return whether or not suggestions are enabled on this TextView. The suggestions are generated * by the IME or by the spell checker as the user types. This is done by adding * {@link SuggestionSpan}s to the text. * * When suggestions are enabled (default), this list of suggestions will be displayed when the * user asks for them on these parts of the text. This value depends on the inputType of this * TextView. * * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}. * * In addition, the type variation must be one of * {@link InputType#TYPE_TEXT_VARIATION_NORMAL}, * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. * * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set. * * @return true if the suggestions popup window is enabled, based on the inputType. */ isSuggestionsEnabled():boolean { return false; //if (this.mEditor == null) // return false; //if ((this.mEditor.mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) { // return false; //} //if ((this.mEditor.mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) // return false; //const variation:number = this.mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; //return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT || variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE || variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE || variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT); } /** * If provided, this ActionMode.Callback will be used to create the ActionMode when text * selection is initiated in this View. * * The standard implementation populates the menu with a subset of Select All, Cut, Copy and * Paste actions, depending on what this View supports. * * A custom implementation can add new entries in the default menu in its * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} * or {@link android.R.id#paste} ids as parameters. * * Returning false from * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent * the action mode from being started. * * Action click events should be handled by the custom implementation of * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. * * Note that text selection mode is not started when a TextView receives focus and the * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in * that case, to allow for quick replacement. */ setCustomSelectionActionModeCallback(actionModeCallback:any):void { this.createEditorIfNeeded(); //this.mEditor.mCustomSelectionActionModeCallback = actionModeCallback; } /** * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. * * @return The current custom selection callback. */ getCustomSelectionActionModeCallback():any { return null; //return this.mEditor == null ? null : this.mEditor.mCustomSelectionActionModeCallback; } /** * @hide */ protected stopSelectionActionMode():void { //this.mEditor.stopSelectionActionMode(); } canCut():boolean { //if (this.hasPasswordTransformationMethod()) { // return false; //} //if (this.mText.length() > 0 && this.hasSelection() && this.mText instanceof Editable && this.mEditor != null && this.mEditor.mKeyListener != null) { // return true; //} return false; } canCopy():boolean { return true; //if (this.hasPasswordTransformationMethod()) { // return false; //} //if (this.mText.length() > 0 && this.hasSelection()) { // return true; //} //return false; } canPaste():boolean { return false; //return (this.mText instanceof Editable && this.mEditor != null && this.mEditor.mKeyListener != null //&& this.getSelectionStart() >= 0 && this.getSelectionEnd() >= 0 //&& (<ClipboardManager> this.getContext().getSystemService(Context.CLIPBOARD_SERVICE)).hasPrimaryClip()); } selectAllText():boolean { return false; //const length:number = this.mText.length(); //Selection.setSelection(<Spannable> this.mText, 0, length); //return length > 0; } ///** // * Prepare text so that there are not zero or two spaces at beginning and end of region defined // * by [min, max] when replacing this region by paste. // * Note that if there were two spaces (or more) at that position before, they are kept. We just // * make sure we do not add an extra one from the paste content. // */ //prepareSpacesAroundPaste(min:number, max:number, paste:String):number { // if (paste.length() > 0) { // if (min > 0) { // const charBefore:string = this.mTransformed.charAt(min - 1); // const charAfter:string = paste.charAt(0); // if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { // // Two spaces at beginning of paste: remove one // const originalLength:number = this.mText.length(); // this.deleteText_internal(min - 1, min); // // Due to filters, there is no guarantee that exactly one character was // // removed: count instead. // const delta:number = this.mText.length() - originalLength; // min += delta; // max += delta; // } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && !Character.isSpaceChar(charAfter) && charAfter != '\n') { // // No space at beginning of paste: add one // const originalLength:number = this.mText.length(); // this.replaceText_internal(min, min, " "); // // Taking possible filters into account as above. // const delta:number = this.mText.length() - originalLength; // min += delta; // max += delta; // } // } // if (max < this.mText.length()) { // const charBefore:string = paste.charAt(paste.length() - 1); // const charAfter:string = this.mTransformed.charAt(max); // if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { // // Two spaces at end of paste: remove one // this.deleteText_internal(max, max + 1); // } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && !Character.isSpaceChar(charAfter) && charAfter != '\n') { // // No space at end of paste: add one // this.replaceText_internal(max, max, " "); // } // } // } // return TextUtils.packRangeInLong(min, max); //} // ///** // * Paste clipboard content between min and max positions. // */ //private paste(min:number, max:number):void { // let clipboard:ClipboardManager = <ClipboardManager> this.getContext().getSystemService(Context.CLIPBOARD_SERVICE); // let clip:ClipData = clipboard.getPrimaryClip(); // if (clip != null) { // let didFirst:boolean = false; // for (let i:number = 0; i < clip.getItemCount(); i++) { // let paste:CharSequence = clip.getItemAt(i).coerceToStyledText(this.getContext()); // if (paste != null) { // if (!didFirst) { // let minMax:number = this.prepareSpacesAroundPaste(min, max, paste); // min = TextUtils.unpackRangeStartFromLong(minMax); // max = TextUtils.unpackRangeEndFromLong(minMax); // Selection.setSelection(<Spannable> this.mText, max); // (<Editable> this.mText).replace(min, max, paste); // didFirst = true; // } else { // (<Editable> this.mText).insert(this.getSelectionEnd(), "\n"); // (<Editable> this.mText).insert(this.getSelectionEnd(), paste); // } // } // } // this.stopSelectionActionMode(); // TextView.LAST_CUT_OR_COPY_TIME = 0; // } //} //private setPrimaryClip(clip:ClipData):void { // let clipboard:ClipboardManager = <ClipboardManager> this.getContext().getSystemService(Context.CLIPBOARD_SERVICE); // clipboard.setPrimaryClip(clip); // TextView.LAST_CUT_OR_COPY_TIME = SystemClock.uptimeMillis(); //} /** * Get the character offset closest to the specified absolute position. A typical use case is to * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. * * @param x The horizontal absolute position of a point on screen * @param y The vertical absolute position of a point on screen * @return the character offset for the character whose position is closest to the specified * position. Returns -1 if there is no layout. */ getOffsetForPosition(x:number, y:number):number { if (this.getLayout() == null) return -1; const line:number = this.getLineAtCoordinate(y); const offset:number = this.getOffsetAtCoordinate(line, x); return offset; } convertToLocalHorizontalCoordinate(x:number):number { x -= this.getTotalPaddingLeft(); // Clamp the position to inside of the view. x = Math.max(0.0, x); x = Math.min(this.getWidth() - this.getTotalPaddingRight() - 1, x); x += this.getScrollX(); return x; } getLineAtCoordinate(y:number):number { y -= this.getTotalPaddingTop(); // Clamp the position to inside of the view. y = Math.max(0.0, y); y = Math.min(this.getHeight() - this.getTotalPaddingBottom() - 1, y); y += this.getScrollY(); return this.getLayout().getLineForVertical(Math.floor(y)); } private getOffsetAtCoordinate(line:number, x:number):number { x = this.convertToLocalHorizontalCoordinate(x); return this.getLayout().getOffsetForHorizontal(line, x); } //onDragEvent(event:DragEvent):boolean { // switch(event.getAction()) { // case DragEvent.ACTION_DRAG_STARTED: // return this.mEditor != null && this.mEditor.hasInsertionController(); // case DragEvent.ACTION_DRAG_ENTERED: // TextView.this.requestFocus(); // return true; // case DragEvent.ACTION_DRAG_LOCATION: // const offset:number = this.getOffsetForPosition(event.getX(), event.getY()); // Selection.setSelection(<Spannable> this.mText, offset); // return true; // case DragEvent.ACTION_DROP: // if (this.mEditor != null) // this.mEditor.onDrop(event); // return true; // case DragEvent.ACTION_DRAG_ENDED: // case DragEvent.ACTION_DRAG_EXITED: // default: // return true; // } //} isInBatchEditMode():boolean { //if (this.mEditor == null) return false; //const ims:Editor.InputMethodState = this.mEditor.mInputMethodState; //if (ims != null) { // return ims.mBatchEditNesting > 0; //} //return this.mEditor.mInBatchEditControllers; } //onRtlPropertiesChanged(layoutDirection:number):void { // super.onRtlPropertiesChanged(layoutDirection); // this.mTextDir = this.getTextDirectionHeuristic(); //} getTextDirectionHeuristic():TextDirectionHeuristic { return TextDirectionHeuristics.LTR; //if (this.hasPasswordTransformationMethod()) { // // passwords fields should be LTR // return TextDirectionHeuristics.LTR; //} //// Always need to resolve layout direction first //const defaultIsRtl:boolean = (this.getLayoutDirection() == TextView.LAYOUT_DIRECTION_RTL); //// Now, we can select the heuristic //switch(this.getTextDirection()) { // default: // case TextView.TEXT_DIRECTION_FIRST_STRONG: // return (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL : TextDirectionHeuristics.FIRSTSTRONG_LTR); // case TextView.TEXT_DIRECTION_ANY_RTL: // return TextDirectionHeuristics.ANYRTL_LTR; // case TextView.TEXT_DIRECTION_LTR: // return TextDirectionHeuristics.LTR; // case TextView.TEXT_DIRECTION_RTL: // return TextDirectionHeuristics.RTL; // case TextView.TEXT_DIRECTION_LOCALE: // return TextDirectionHeuristics.LOCALE; //} } /** * @hide */ onResolveDrawables(layoutDirection:number):void { // No need to resolve twice if (this.mLastLayoutDirection == layoutDirection) { return; } this.mLastLayoutDirection = layoutDirection; // Resolve drawables if (this.mDrawables != null) { this.mDrawables.resolveWithLayoutDirection(layoutDirection); } } /** * @hide */ protected resetResolvedDrawables():void { //super.resetResolvedDrawables(); this.mLastLayoutDirection = -1; } ///** // * @hide // */ //protected viewClicked(imm:InputMethodManager):void { // if (imm != null) { // imm.viewClicked(this); // } //} /** * Deletes the range of text [start, end[. * @hide */ protected deleteText_internal(start:number, end:number):void { //(<Editable> this.mText).delete(start, end); } /** * Replaces the range of text [start, end[ by replacement text * @hide */ protected replaceText_internal(start:number, end:number, text:String):void { //(<Editable> this.mText).replace(start, end, text); } /** * Sets a span on the specified range of text * @hide */ protected setSpan_internal(span:any, start:number, end:number, flags:number):void { //(<Editable> this.mText).setSpan(span, start, end, flags); } /** * Moves the cursor to the specified offset position in text * @hide */ protected setCursorPosition_internal(start:number, end:number):void { //Selection.setSelection((<Editable> this.mText), start, end); } /** * An Editor should be created as soon as any of the editable-specific fields (grouped * inside the Editor object) is assigned to a non-default value. * This method will create the Editor if needed. * * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will * have a null Editor, unlike an EditText. Inconsistent in-between states will have an * Editor for backward compatibility, as soon as one of these fields is assigned. * * Also note that for performance reasons, the mEditor is created when needed, but not * reset when no more edit-specific fields are needed. */ private createEditorIfNeeded():void { //if (this.mEditor == null) { // this.mEditor = new Editor(this); //} } ///** // * @hide // */ //getIterableTextForAccessibility():CharSequence { // if (!(this.mText instanceof Spannable)) { // this.setText(this.mText, TextView.BufferType.SPANNABLE); // } // return this.mText; //} // ///** // * @hide // */ //getIteratorForGranularity(granularity:number):TextSegmentIterator { // switch(granularity) { // case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: // { // let text:Spannable = <Spannable> this.getIterableTextForAccessibility(); // if (!TextUtils.isEmpty(text) && this.getLayout() != null) { // let iterator:AccessibilityIterators.LineTextSegmentIterator = AccessibilityIterators.LineTextSegmentIterator.getInstance(); // iterator.initialize(text, this.getLayout()); // return iterator; // } // } // break; // case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: // { // let text:Spannable = <Spannable> this.getIterableTextForAccessibility(); // if (!TextUtils.isEmpty(text) && this.getLayout() != null) { // let iterator:AccessibilityIterators.PageTextSegmentIterator = AccessibilityIterators.PageTextSegmentIterator.getInstance(); // iterator.initialize(this); // return iterator; // } // } // break; // } // return super.getIteratorForGranularity(granularity); //} // ///** // * @hide // */ //getAccessibilitySelectionStart():number { // return this.getSelectionStart(); //} // ///** // * @hide // */ //isAccessibilitySelectionExtendable():boolean { // return true; //} // ///** // * @hide // */ //getAccessibilitySelectionEnd():number { // return this.getSelectionEnd(); //} // ///** // * @hide // */ //setAccessibilitySelection(start:number, end:number):void { // if (this.getAccessibilitySelectionStart() == start && this.getAccessibilitySelectionEnd() == end) { // return; // } // // controllers interact with how selection behaves. // if (this.mEditor != null) { // this.mEditor.hideControllers(); // } // let text:CharSequence = this.getIterableTextForAccessibility(); // if (Math.min(start, end) >= 0 && Math.max(start, end) <= text.length()) { // Selection.setSelection(<Spannable> text, start, end); // } else { // Selection.removeSelection(<Spannable> text); // } //} } export module TextView{ export class Drawables { static DRAWABLE_NONE:number = -1; static DRAWABLE_RIGHT:number = 0; static DRAWABLE_LEFT:number = 1; mCompoundRect:Rect = new Rect(); mDrawableTop:Drawable; mDrawableBottom:Drawable; mDrawableLeft:Drawable; mDrawableRight:Drawable; mDrawableStart:Drawable; mDrawableEnd:Drawable; mDrawableError:Drawable; mDrawableTemp:Drawable; mDrawableLeftInitial:Drawable; mDrawableRightInitial:Drawable; mIsRtlCompatibilityMode:boolean; mOverride:boolean; mDrawableSizeTop:number = 0; mDrawableSizeBottom:number = 0; mDrawableSizeLeft:number = 0; mDrawableSizeRight:number = 0; mDrawableSizeStart:number = 0; mDrawableSizeEnd:number = 0; mDrawableSizeError:number = 0; mDrawableSizeTemp:number = 0; mDrawableWidthTop:number = 0; mDrawableWidthBottom:number = 0; mDrawableHeightLeft:number = 0; mDrawableHeightRight:number = 0; mDrawableHeightStart:number = 0; mDrawableHeightEnd:number = 0; mDrawableHeightError:number = 0; mDrawableHeightTemp:number = 0; mDrawablePadding:number = 0; mDrawableSaved:number = Drawables.DRAWABLE_NONE; constructor( context?:any) { //const targetSdkVersion:number = context.getApplicationInfo().targetSdkVersion; this.mIsRtlCompatibilityMode = false;//(targetSdkVersion < JELLY_BEAN_MR1 || !context.getApplicationInfo().hasRtlSupport()); this.mOverride = false; } resolveWithLayoutDirection(layoutDirection:number):void { // First reset "left" and "right" drawables to their initial values this.mDrawableLeft = this.mDrawableLeftInitial; this.mDrawableRight = this.mDrawableRightInitial; //if (this.mIsRtlCompatibilityMode) { // // Use "start" drawable as "left" drawable if the "left" drawable was not defined // if (this.mDrawableStart != null && this.mDrawableLeft == null) { // this.mDrawableLeft = this.mDrawableStart; // this.mDrawableSizeLeft = this.mDrawableSizeStart; // this.mDrawableHeightLeft = this.mDrawableHeightStart; // } // // Use "end" drawable as "right" drawable if the "right" drawable was not defined // if (this.mDrawableEnd != null && this.mDrawableRight == null) { // this.mDrawableRight = this.mDrawableEnd; // this.mDrawableSizeRight = this.mDrawableSizeEnd; // this.mDrawableHeightRight = this.mDrawableHeightEnd; // } //} else { // // drawable if and only if they have been defined // switch(layoutDirection) { // case TextView.LAYOUT_DIRECTION_RTL: // if (this.mOverride) { // this.mDrawableRight = this.mDrawableStart; // this.mDrawableSizeRight = this.mDrawableSizeStart; // this.mDrawableHeightRight = this.mDrawableHeightStart; // this.mDrawableLeft = this.mDrawableEnd; // this.mDrawableSizeLeft = this.mDrawableSizeEnd; // this.mDrawableHeightLeft = this.mDrawableHeightEnd; // } // break; // case TextView.LAYOUT_DIRECTION_LTR: // default: if (this.mOverride) { this.mDrawableLeft = this.mDrawableStart; this.mDrawableSizeLeft = this.mDrawableSizeStart; this.mDrawableHeightLeft = this.mDrawableHeightStart; this.mDrawableRight = this.mDrawableEnd; this.mDrawableSizeRight = this.mDrawableSizeEnd; this.mDrawableHeightRight = this.mDrawableHeightEnd; } // break; // } //} this.applyErrorDrawableIfNeeded(layoutDirection); this.updateDrawablesLayoutDirection(layoutDirection); } private updateDrawablesLayoutDirection(layoutDirection:number):void { //if (this.mDrawableLeft != null) { // this.mDrawableLeft.setLayoutDirection(layoutDirection); //} //if (this.mDrawableRight != null) { // this.mDrawableRight.setLayoutDirection(layoutDirection); //} //if (this.mDrawableTop != null) { // this.mDrawableTop.setLayoutDirection(layoutDirection); //} //if (this.mDrawableBottom != null) { // this.mDrawableBottom.setLayoutDirection(layoutDirection); //} } setErrorDrawable(dr:Drawable, tv:TextView):void { if (this.mDrawableError != dr && this.mDrawableError != null) { this.mDrawableError.setCallback(null); } this.mDrawableError = dr; const compoundRect:Rect = this.mCompoundRect; let state:number[] = tv.getDrawableState(); if (this.mDrawableError != null) { this.mDrawableError.setState(state); this.mDrawableError.copyBounds(compoundRect); this.mDrawableError.setCallback(tv); this.mDrawableSizeError = compoundRect.width(); this.mDrawableHeightError = compoundRect.height(); } else { this.mDrawableSizeError = this.mDrawableHeightError = 0; } } private applyErrorDrawableIfNeeded(layoutDirection:number):void { // first restore the initial state if needed switch(this.mDrawableSaved) { case Drawables.DRAWABLE_LEFT: this.mDrawableLeft = this.mDrawableTemp; this.mDrawableSizeLeft = this.mDrawableSizeTemp; this.mDrawableHeightLeft = this.mDrawableHeightTemp; break; case Drawables.DRAWABLE_RIGHT: this.mDrawableRight = this.mDrawableTemp; this.mDrawableSizeRight = this.mDrawableSizeTemp; this.mDrawableHeightRight = this.mDrawableHeightTemp; break; case Drawables.DRAWABLE_NONE: default: } // then, if needed, assign the Error drawable to the correct location //if (this.mDrawableError != null) { // switch(layoutDirection) { // case TextView.LAYOUT_DIRECTION_RTL: // this.mDrawableSaved = Drawables.DRAWABLE_LEFT; // this.mDrawableTemp = this.mDrawableLeft; // this.mDrawableSizeTemp = this.mDrawableSizeLeft; // this.mDrawableHeightTemp = this.mDrawableHeightLeft; // this.mDrawableLeft = this.mDrawableError; // this.mDrawableSizeLeft = this.mDrawableSizeError; // this.mDrawableHeightLeft = this.mDrawableHeightError; // break; // case TextView.LAYOUT_DIRECTION_LTR: // default: this.mDrawableSaved = Drawables.DRAWABLE_RIGHT; this.mDrawableTemp = this.mDrawableRight; this.mDrawableSizeTemp = this.mDrawableSizeRight; this.mDrawableHeightTemp = this.mDrawableHeightRight; this.mDrawableRight = this.mDrawableError; this.mDrawableSizeRight = this.mDrawableSizeError; this.mDrawableHeightRight = this.mDrawableHeightError; // break; // } //} } } /** * Interface definition for a callback to be invoked when an action is * performed on the editor. */ export interface OnEditorActionListener { /** * Called when an action is being performed. * * @param v The view that was clicked. * @param actionId Identifier of the action. This will be either the * identifier you supplied, or {@link EditorInfo#IME_NULL * EditorInfo.IME_NULL} if being called due to the enter key * being pressed. * @param event If triggered by an enter key, this is the event; * otherwise, this is null. * @return Return true if you have consumed the action, else false. */ onEditorAction(v:TextView, actionId:number, event:KeyEvent):boolean ; } ///** // * User interface state that is stored by TextView for implementing // * {@link View#onSaveInstanceState}. // */ //export class SavedState extends View.BaseSavedState { // // selStart:number = 0; // // selEnd:number = 0; // // text:CharSequence; // // frozenWithFocus:boolean; // // error:CharSequence; // // constructor( superState:Parcelable) { // super(superState); // } // // writeToParcel(out:Parcel, flags:number):void { // super.writeToParcel(out, flags); // out.writeInt(this.selStart); // out.writeInt(this.selEnd); // out.writeInt(this.frozenWithFocus ? 1 : 0); // TextUtils.writeToParcel(this.text, out, flags); // if (this.error == null) { // out.writeInt(0); // } else { // out.writeInt(1); // TextUtils.writeToParcel(this.error, out, flags); // } // } // // toString():string { // let str:string = "TextView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " start=" + this.selStart + " end=" + this.selEnd; // if (this.text != null) { // str += " text=" + this.text; // } // return str + "}"; // } // // static CREATOR:Parcelable.Creator<SavedState> = (()=>{ // const inner_this=this; // class _Inner extends Parcelable.Creator<SavedState> { // // createFromParcel(_in:Parcel):SavedState { // return new SavedState(_in); // } // // newArray(size:number):SavedState[] { // return new Array<SavedState>(size); // } // } // return new _Inner(); // })(); // // constructor( _in:Parcel) { // super(_in); // this.selStart = _in.readInt(); // this.selEnd = _in.readInt(); // this.frozenWithFocus = (_in.readInt() != 0); // this.text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(_in); // if (_in.readInt() != 0) { // this.error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(_in); // } // } //} //export class CharWrapper implements CharSequence, GetChars, GraphicsOperations { // // private mChars:string[]; // // private mStart:number = 0; // private mLength:number = 0; // // constructor( chars:string[], start:number, len:number) { // this.mChars = chars; // this.mStart = start; // this.mLength = len; // } // // /* package */ // set(chars:string[], start:number, len:number):void { // this.mChars = chars; // this.mStart = start; // this.mLength = len; // } // // length():number { // return this.mLength; // } // // charAt(off:number):string { // return this.mChars[off + this.mStart]; // } // // toString():string { // return new string(this.mChars, this.mStart, this.mLength); // } // // subSequence(start:number, end:number):CharSequence { // if (start < 0 || end < 0 || start > this.mLength || end > this.mLength) { // throw Error(`new IndexOutOfBoundsException(start + ", " + end)`); // } // return new string(this.mChars, start + this.mStart, end - start); // } // // getChars(start:number, end:number, buf:string[], off:number):void { // if (start < 0 || end < 0 || start > this.mLength || end > this.mLength) { // throw Error(`new IndexOutOfBoundsException(start + ", " + end)`); // } // System.arraycopy(this.mChars, start + this.mStart, buf, off, end - start); // } // // drawText(c:Canvas, start:number, end:number, x:number, y:number, p:Paint):void { // c.drawText(this.mChars, start + this.mStart, end - start, x, y, p); // } // // drawTextRun(c:Canvas, start:number, end:number, contextStart:number, contextEnd:number, x:number, y:number, flags:number, p:Paint):void { // let count:number = end - start; // let contextCount:number = contextEnd - contextStart; // c.drawTextRun(this.mChars, start + this.mStart, count, contextStart + this.mStart, contextCount, x, y, flags, p); // } // // measureText(start:number, end:number, p:Paint):number { // return p.measureText(this.mChars, start + this.mStart, end - start); // } // // getTextWidths(start:number, end:number, widths:number[], p:Paint):number { // return p.getTextWidths(this.mChars, start + this.mStart, end - start, widths); // } // // getTextRunAdvances(start:number, end:number, contextStart:number, contextEnd:number, flags:number, advances:number[], advancesIndex:number, p:Paint):number { // let count:number = end - start; // let contextCount:number = contextEnd - contextStart; // return p.getTextRunAdvances(this.mChars, start + this.mStart, count, contextStart + this.mStart, contextCount, flags, advances, advancesIndex); // } // // getTextRunCursor(contextStart:number, contextEnd:number, flags:number, offset:number, cursorOpt:number, p:Paint):number { // let contextCount:number = contextEnd - contextStart; // return p.getTextRunCursor(this.mChars, contextStart + this.mStart, contextCount, flags, offset + this.mStart, cursorOpt); // } //} export class Marquee extends Handler { // TODO: Add an option to configure this private static MARQUEE_DELTA_MAX:number = 0.07; private static MARQUEE_DELAY:number = 1200; private static MARQUEE_RESTART_DELAY:number = 1200; private static MARQUEE_RESOLUTION:number = 1000 / 30; private static MARQUEE_PIXELS_PER_SECOND:number = 30; private static MARQUEE_STOPPED:number = 0x0; private static MARQUEE_STARTING:number = 0x1; private static MARQUEE_RUNNING:number = 0x2; private static MESSAGE_START:number = 0x1; private static MESSAGE_TICK:number = 0x2; private static MESSAGE_RESTART:number = 0x3; private mView:WeakReference<TextView>; private mStatus:number = Marquee.MARQUEE_STOPPED; private mScrollUnit:number = 0; private mMaxScroll:number = 0; private mMaxFadeScroll:number = 0; private mGhostStart:number = 0; private mGhostOffset:number = 0; private mFadeStop:number = 0; private mRepeatLimit:number = 0; private mScroll:number = 0; constructor(v:TextView) { super(); const density:number = v.getResources().getDisplayMetrics().density; this.mScrollUnit = (Marquee.MARQUEE_PIXELS_PER_SECOND * density) / Marquee.MARQUEE_RESOLUTION; this.mView = new WeakReference<TextView>(v); } handleMessage(msg:Message):void { switch(msg.what) { case Marquee.MESSAGE_START: this.mStatus = Marquee.MARQUEE_RUNNING; this.tick(); break; case Marquee.MESSAGE_TICK: this.tick(); break; case Marquee.MESSAGE_RESTART: if (this.mStatus == Marquee.MARQUEE_RUNNING) { if (this.mRepeatLimit >= 0) { this.mRepeatLimit--; } this.start(this.mRepeatLimit); } break; } } tick():void { if (this.mStatus != Marquee.MARQUEE_RUNNING) { return; } this.removeMessages(Marquee.MESSAGE_TICK); const textView:TextView = this.mView.get(); if (textView != null && (textView.isFocused() || textView.isSelected())) { this.mScroll += this.mScrollUnit; if (this.mScroll > this.mMaxScroll) { this.mScroll = this.mMaxScroll; this.sendEmptyMessageDelayed(Marquee.MESSAGE_RESTART, Marquee.MARQUEE_RESTART_DELAY); } else { this.sendEmptyMessageDelayed(Marquee.MESSAGE_TICK, Marquee.MARQUEE_RESOLUTION); } textView.invalidate(); } } stop():void { this.mStatus = Marquee.MARQUEE_STOPPED; this.removeMessages(Marquee.MESSAGE_START); this.removeMessages(Marquee.MESSAGE_RESTART); this.removeMessages(Marquee.MESSAGE_TICK); this.resetScroll(); } private resetScroll():void { this.mScroll = 0.0; const textView:TextView = this.mView.get(); if (textView != null) textView.invalidate(); } start(repeatLimit:number):void { if (repeatLimit == 0) { this.stop(); return; } this.mRepeatLimit = repeatLimit; const textView:TextView = this.mView.get(); if (textView != null && textView.mLayout != null) { this.mStatus = Marquee.MARQUEE_STARTING; this.mScroll = 0.0; const textWidth:number = textView.getWidth() - textView.getCompoundPaddingLeft() - textView.getCompoundPaddingRight(); const lineWidth:number = textView.mLayout.getLineWidth(0); const gap:number = textWidth / 3.0; this.mGhostStart = lineWidth - textWidth + gap; this.mMaxScroll = this.mGhostStart + textWidth; this.mGhostOffset = lineWidth + gap; this.mFadeStop = lineWidth + textWidth / 6.0; this.mMaxFadeScroll = this.mGhostStart + lineWidth + lineWidth; textView.invalidate(); this.sendEmptyMessageDelayed(Marquee.MESSAGE_START, Marquee.MARQUEE_DELAY); } } getGhostOffset():number { return this.mGhostOffset; } getScroll():number { return this.mScroll; } getMaxFadeScroll():number { return this.mMaxFadeScroll; } shouldDrawLeftFade():boolean { return this.mScroll <= this.mFadeStop; } shouldDrawGhost():boolean { return this.mStatus == Marquee.MARQUEE_RUNNING && this.mScroll > this.mGhostStart; } isRunning():boolean { return this.mStatus == Marquee.MARQUEE_RUNNING; } isStopped():boolean { return this.mStatus == Marquee.MARQUEE_STOPPED; } } export class ChangeWatcher implements TextWatcher, SpanWatcher { _TextView_this:TextView; constructor(arg:TextView){ this._TextView_this = arg; } private mBeforeText:String; beforeTextChanged(buffer:String, start:number, before:number, after:number):void { if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, "beforeTextChanged start=" + start + " before=" + before + " after=" + after + ": " + buffer); //if (AccessibilityManager.getInstance(this._TextView_this.mContext).isEnabled() && ((!TextView.isPasswordInputType(this._TextView_this.getInputType()) && !this._TextView_this.hasPasswordTransformationMethod()) || this._TextView_this.shouldSpeakPasswordsForAccessibility())) { // this.mBeforeText = buffer.toString(); //} this._TextView_this.sendBeforeTextChanged(buffer, start, before, after); } onTextChanged(buffer:String, start:number, before:number, after:number):void { if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, "onTextChanged start=" + start + " before=" + before + " after=" + after + ": " + buffer); this._TextView_this.handleTextChanged(buffer, start, before, after); //if (AccessibilityManager.getInstance(this._TextView_this.mContext).isEnabled() && (this._TextView_this.isFocused() || this._TextView_this.isSelected() && this._TextView_this.isShown())) { // this._TextView_this.sendAccessibilityEventTypeViewTextChanged(this.mBeforeText, start, before, after); // this.mBeforeText = null; //} } afterTextChanged(buffer:String):void { if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, "afterTextChanged: " + buffer); this._TextView_this.sendAfterTextChanged(buffer); //if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { // MetaKeyKeyListener.stopSelecting(this._TextView_this, buffer); //} } onSpanChanged(buf:Spannable, what:any, s:number, e:number, st:number, en:number):void { if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, "onSpanChanged s=" + s + " e=" + e + " st=" + st + " en=" + en + " what=" + what + ": " + buf); this._TextView_this.spanChange(buf, what, s, st, e, en); } onSpanAdded(buf:Spannable, what:any, s:number, e:number):void { if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, "onSpanAdded s=" + s + " e=" + e + " what=" + what + ": " + buf); this._TextView_this.spanChange(buf, what, -1, s, -1, e); } onSpanRemoved(buf:Spannable, what:any, s:number, e:number):void { if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, "onSpanRemoved s=" + s + " e=" + e + " what=" + what + ": " + buf); this._TextView_this.spanChange(buf, what, s, -1, e, -1); } } export enum BufferType { NORMAL /*() { } */, SPANNABLE /*() { } */, EDITABLE /*() { } */ /*; */}} }
the_stack
import {computed, Computed, computedArray} from 'grainjs'; import {MutableObsArray, obsArray, ObsArray, observable, Observable} from 'grainjs'; import {dom, LiveIndex, makeLiveIndex, styled} from 'grainjs'; // Grist client libs import {DocComm} from 'app/client/components/DocComm'; import {selectFiles, uploadFiles} from 'app/client/lib/uploads'; import {DocData} from 'app/client/models/DocData'; import {TableData} from 'app/client/models/TableData'; import {basicButton, basicButtonLink, cssButtonGroup} from 'app/client/ui2018/buttons'; import {colors, testId, vars} from 'app/client/ui2018/cssVars'; import {editableLabel} from 'app/client/ui2018/editableLabel'; import {icon} from 'app/client/ui2018/icons'; import {IModalControl, modal} from 'app/client/ui2018/modals'; import {renderFileType} from 'app/client/widgets/AttachmentsWidget'; import {NewBaseEditor, Options} from 'app/client/widgets/NewBaseEditor'; import {CellValue} from 'app/common/DocActions'; import {clamp, encodeQueryParams} from 'app/common/gutil'; import {UploadResult} from 'app/common/uploads'; import * as mimeTypes from 'mime-types'; interface Attachment { rowId: number; // Checksum of the file content, with extension, which identifies the file data in the _gristsys_Files table. fileIdent: string; // MIME type of the data (looked up from fileIdent's extension). fileType: string; // User-defined filename of the attachment. An observable to support renaming. filename: Observable<string>; // Whether the attachment is an image, indicated by the presence of imageHeight in the record. hasPreview: boolean; // The download URL of the attachment; served with Content-Disposition of "attachment". url: Observable<string>; // The inline URL of the attachment; served with Content-Disposition of "inline". inlineUrl: Observable<string>; } /** * An AttachmentsEditor shows a full-screen modal with attachment previews, and options to rename, * download, add or remove attachments in the edited cell. */ export class AttachmentsEditor extends NewBaseEditor { private _attachmentsTable: TableData; private _docComm: DocComm; private _rowIds: MutableObsArray<number>; private _attachments: ObsArray<Attachment>; private _index: LiveIndex; private _selected: Computed<Attachment|null>; constructor(options: Options) { super(options); const docData: DocData = options.gristDoc.docData; const cellValue: CellValue = options.cellValue; // editValue is abused slightly to indicate a 1-based index of the attachment. const initRowIndex: number|undefined = (options.editValue && parseInt(options.editValue, 0) - 1) || 0; this._attachmentsTable = docData.getTable('_grist_Attachments')!; this._docComm = docData.docComm; this._rowIds = obsArray(Array.isArray(cellValue) ? cellValue.slice(1) as number[] : []); this._attachments = computedArray(this._rowIds, (val: number): Attachment => { const fileIdent: string = this._attachmentsTable.getValue(val, 'fileIdent') as string; const fileType = mimeTypes.lookup(fileIdent) || 'application/octet-stream'; const filename: Observable<string> = observable(this._attachmentsTable.getValue(val, 'fileName') as string); return { rowId: val, fileIdent, fileType, filename, hasPreview: Boolean(this._attachmentsTable.getValue(val, 'imageHeight')), url: computed((use) => this._getUrl(fileIdent, use(filename))), inlineUrl: computed((use) => this._getUrl(fileIdent, use(filename), true)) }; }); this._index = makeLiveIndex(this, this._attachments, initRowIndex); this._selected = this.autoDispose(computed((use) => { const index = use(this._index); return index === null ? null : use(this._attachments)[index]; })); } // This "attach" is not about "attachments", but about attaching this widget to the page DOM. public attach(cellElem: Element) { modal((ctl, owner) => { // If FieldEditor is disposed externally (e.g. on navigation), be sure to close the modal. this.onDispose(ctl.close); return [ cssFullScreenModal.cls(''), dom.onKeyDown({ Enter: (ev) => { ctl.close(); this.options.commands.fieldEditSaveHere(); }, Escape: (ev) => { ctl.close(); this.options.commands.fieldEditCancel(); }, ArrowLeft$: (ev) => !isInEditor(ev) && this._moveIndex(-1), ArrowRight$: (ev) => !isInEditor(ev) && this._moveIndex(1), }), // Close if clicking into the background. (The default modal's behavior for this isn't // triggered because our content covers the whole screen.) dom.on('click', (ev, elem) => { if (ev.target === elem) { ctl.close(); } }), ...this._buildDom(ctl) ]; }, {noEscapeKey: true}); } public getCellValue() { return ["L", ...this._rowIds.get()] as CellValue; } public getCursorPos(): number { return 0; } public getTextValue(): string { return ''; } // Builds the attachment preview modal. private _buildDom(ctl: IModalControl) { return [ cssHeader( cssFlexExpand(dom.text(use => { const len = use(this._attachments).length; return len ? `${(use(this._index) || 0) + 1} of ${len}` : ''; }), testId('pw-counter') ), dom.maybe(this._selected, selected => cssTitle( cssEditableLabel(selected.filename, (val) => this._renameAttachment(selected, val), testId('pw-name')) ) ), cssFlexExpand( cssFileButtons( dom.maybe(this._selected, selected => basicButtonLink(cssButton.cls(''), cssButtonIcon('Download'), 'Download', dom.attr('href', selected.url), dom.attr('target', '_blank'), dom.attr('download', selected.filename), testId('pw-download') ), ), this.options.readonly ? null : [ cssButton(cssButtonIcon('FieldAttachment'), 'Add', dom.on('click', () => this._select()), testId('pw-add') ), dom.maybe(this._selected, () => cssButton(cssButtonIcon('Remove'), 'Delete', dom.on('click', () => this._remove()), testId('pw-remove') ), ) ] ), cssCloseButton(cssBigIcon('CrossBig'), dom.on('click', () => ctl.close()), testId('pw-close')), ) ), cssNextArrow(cssNextArrow.cls('-left'), cssBigIcon('Expand'), testId('pw-left'), dom.hide(use => !use(this._attachments).length || use(this._index) === 0), dom.on('click', () => this._moveIndex(-1)) ), cssNextArrow(cssNextArrow.cls('-right'), cssBigIcon('Expand'), testId('pw-right'), dom.hide(use => !use(this._attachments).length || use(this._index) === use(this._attachments).length - 1), dom.on('click', () => this._moveIndex(1)) ), dom.domComputed(this._selected, selected => renderContent(selected, this.options.readonly)), // Drag-over logic (elem: HTMLElement) => dragOverClass(elem, cssDropping.className), cssDragArea(this.options.readonly ? null : cssWarning('Drop files here to attach')), this.options.readonly ? null : dom.on('drop', ev => this._upload(ev.dataTransfer!.files)), testId('pw-modal') ]; } private async _renameAttachment(att: Attachment, fileName: string): Promise<void> { await this._attachmentsTable.sendTableAction(['UpdateRecord', att.rowId, {fileName}]); // Update the observable, since it's not on its own observing changes. att.filename.set(this._attachmentsTable.getValue(att.rowId, 'fileName') as string); } private _getUrl(fileIdent: string, filename: string, inline?: boolean): string { return this._docComm.docUrl('attachment') + '?' + encodeQueryParams({ ...this._docComm.getUrlParams(), ident: fileIdent, name: filename, ...(inline ? {inline: 1} : {}) }); } private _moveIndex(dir: -1|1): void { const next = this._index.get()! + dir; this._index.set(clamp(next, 0, this._attachments.get().length)); } // Removes the attachment being previewed from the cell (but not the document). private _remove(): void { this._rowIds.splice(this._index.get()!, 1); } private async _select(): Promise<void> { const uploadResult = await selectFiles({docWorkerUrl: this._docComm.docWorkerUrl, multiple: true, sizeLimit: 'attachment'}); return this._add(uploadResult); } private async _upload(files: FileList): Promise<void> { const uploadResult = await uploadFiles(Array.from(files), {docWorkerUrl: this._docComm.docWorkerUrl, sizeLimit: 'attachment'}); return this._add(uploadResult); } private async _add(uploadResult: UploadResult|null): Promise<void> { if (!uploadResult) { return; } const rowIds = await this._docComm.addAttachments(uploadResult.uploadId); const len = this._rowIds.get().length; if (rowIds.length > 0) { this._rowIds.push(...rowIds); this._index.set(len); } } } function isInEditor(ev: KeyboardEvent): boolean { return (ev.target as HTMLElement).tagName === 'INPUT'; } function renderContent(att: Attachment|null, readonly: boolean): HTMLElement { const commonArgs = [cssContent.cls(''), testId('pw-attachment-content')]; if (!att) { return cssWarning('No attachments', readonly ? null : cssDetails('Drop files here to attach.'), ...commonArgs); } else if (att.hasPreview) { return dom('img', dom.attr('src', att.url), ...commonArgs); } else if (att.fileType.startsWith('video/')) { return dom('video', dom.attr('src', att.inlineUrl), {autoplay: false, controls: true}, ...commonArgs); } else if (att.fileType.startsWith('audio/')) { return dom('audio', dom.attr('src', att.inlineUrl), {autoplay: false, controls: true}, ...commonArgs); } else if (att.fileType.startsWith('text/') || att.fileType === 'application/json') { // Rendering text/html is risky. Things like text/plain and text/csv we could render though, // but probably not using object tag (which needs work to look acceptable). return dom('div', ...commonArgs, cssWarning(cssContent.cls(''), renderFileType(att.filename.get(), att.fileIdent), cssDetails('Preview not available.'))); } else { // Setting 'type' attribute is important to avoid a download prompt from Chrome. return dom('object', {type: att.fileType}, dom.attr('data', att.inlineUrl), ...commonArgs, cssWarning(cssContent.cls(''), renderFileType(att.filename.get(), att.fileIdent), cssDetails('Preview not available.')) ); } } function dragOverClass(target: HTMLElement, className: string): void { let enterTarget: EventTarget|null = null; function toggle(ev: DragEvent, onOff: boolean) { enterTarget = onOff ? ev.target : null; ev.stopPropagation(); ev.preventDefault(); target.classList.toggle(className, onOff); } dom.onElem(target, 'dragenter', (ev) => toggle(ev, true)); dom.onElem(target, 'dragleave', (ev) => (ev.target === enterTarget) && toggle(ev, false)); dom.onElem(target, 'drop', (ev) => toggle(ev, false)); } const cssFullScreenModal = styled('div', ` background-color: initial; width: 100%; height: 100%; border: none; border-radius: 0px; box-shadow: none; padding: 0px; `); const cssHeader = styled('div', ` padding: 16px 24px; position: fixed; width: 100%; display: flex; align-items: center; justify-content: center; color: white; `); const cssCloseButton = styled('div', ` padding: 6px; border-radius: 32px; cursor: pointer; background-color: ${colors.light}; --icon-color: ${colors.lightGreen}; &:hover { background-color: ${colors.mediumGreyOpaque}; --icon-color: ${colors.darkGreen}; } `); const cssBigIcon = styled(icon, ` padding: 10px; `); const cssTitle = styled('div', ` display: inline-block; padding: 8px 16px; margin-right: 8px; min-width: 0px; overflow: hidden; &:hover { outline: 1px solid ${colors.slate}; } &:focus-within { outline: 1px solid ${colors.darkGreen}; } `); const cssEditableLabel = styled(editableLabel, ` font-size: ${vars.mediumFontSize}; font-weight: bold; color: white; `); const cssFlexExpand = styled('div', ` flex: 1; display: flex; `); const cssFileButtons = styled(cssButtonGroup, ` margin-left: auto; margin-right: 16px; height: 32px; flex: none; `); const cssButton = styled(basicButton, ` background-color: ${colors.light}; font-weight: normal; padding: 0 16px; border-top: none; border-right: none; border-bottom: none; border-left: 1px solid ${colors.darkGrey}; display: flex; align-items: center; &:first-child { border: none; } &:hover { background-color: ${colors.mediumGreyOpaque}; border-color: ${colors.darkGrey}; } `); const cssButtonIcon = styled(icon, ` --icon-color: ${colors.slate}; margin-right: 4px; `); const cssNextArrow = styled('div', ` position: fixed; height: 32px; margin: auto 24px; top: 0px; bottom: 0px; z-index: 1; padding: 6px; border-radius: 32px; cursor: pointer; background-color: ${colors.lightGreen}; --icon-color: ${colors.light}; &:hover { background-color: ${colors.darkGreen}; } &-left { transform: rotateY(180deg); left: 0px; } &-right { right: 0px; } `); const cssDropping = styled('div', ''); const cssContent = styled('div', ` display: block; height: calc(100% - 72px); width: calc(100% - 64px); max-width: 800px; margin-left: auto; margin-right: auto; margin-top: 64px; margin-bottom: 8px; outline: none; img& { width: max-content; height: unset; } audio& { padding-bottom: 64px; } .${cssDropping.className} > & { display: none; } `); const cssWarning = styled('div', ` display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: ${vars.mediumFontSize}; font-weight: bold; color: white; padding: 0px; `); const cssDetails = styled('div', ` font-weight: normal; margin-top: 24px; `); const cssDragArea = styled(cssContent, ` border: 2px dashed ${colors.mediumGreyOpaque}; height: calc(100% - 96px); margin-top: 64px; padding: 0px; justify-content: center; display: none; .${cssDropping.className} > & { display: flex; } `);
the_stack
import { localize } from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { VSBuffer } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { normalize } from 'vs/base/common/path'; import { isLinux } from 'vs/base/common/platform'; import { extUri, extUriIgnorePathCase } from 'vs/base/common/resources'; import { newWriteableStream, ReadableStreamEvents } from 'vs/base/common/stream'; import { createFileSystemProviderError, FileDeleteOptions, FileOverwriteOptions, FileReadStreamOptions, FileSystemProviderCapabilities, FileSystemProviderError, FileSystemProviderErrorCode, FileType, FileWriteOptions, IFileSystemProviderWithFileReadStreamCapability, IFileSystemProviderWithFileReadWriteCapability, IStat, IWatchOptions } from 'vs/platform/files/common/files'; export class HTMLFileSystemProvider implements IFileSystemProviderWithFileReadWriteCapability, IFileSystemProviderWithFileReadStreamCapability { //#region Events (unsupported) readonly onDidChangeCapabilities = Event.None; readonly onDidChangeFile = Event.None; readonly onDidErrorOccur = Event.None; //#endregion //#region File Capabilities private extUri = isLinux ? extUri : extUriIgnorePathCase; private _capabilities: FileSystemProviderCapabilities | undefined; get capabilities(): FileSystemProviderCapabilities { if (!this._capabilities) { this._capabilities = FileSystemProviderCapabilities.FileReadWrite | FileSystemProviderCapabilities.FileReadStream; if (isLinux) { this._capabilities |= FileSystemProviderCapabilities.PathCaseSensitive; } } return this._capabilities; } //#endregion //#region File Metadata Resolving async stat(resource: URI): Promise<IStat> { try { const handle = await this.getHandle(resource); if (!handle) { throw this.createFileSystemProviderError(resource, 'No such file or directory, stat', FileSystemProviderErrorCode.FileNotFound); } if (handle.kind === 'file') { const file = await handle.getFile(); return { type: FileType.File, mtime: file.lastModified, ctime: 0, size: file.size }; } return { type: FileType.Directory, mtime: 0, ctime: 0, size: 0 }; } catch (error) { throw this.toFileSystemProviderError(error); } } async readdir(resource: URI): Promise<[string, FileType][]> { try { const handle = await this.getDirectoryHandle(resource); if (!handle) { throw this.createFileSystemProviderError(resource, 'No such file or directory, readdir', FileSystemProviderErrorCode.FileNotFound); } const result: [string, FileType][] = []; for await (const [name, child] of handle) { result.push([name, child.kind === 'file' ? FileType.File : FileType.Directory]); } return result; } catch (error) { throw this.toFileSystemProviderError(error); } } //#endregion //#region File Reading/Writing readFileStream(resource: URI, opts: FileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array> { const stream = newWriteableStream<Uint8Array>(data => VSBuffer.concat(data.map(data => VSBuffer.wrap(data))).buffer, { // Set a highWaterMark to prevent the stream // for file upload to produce large buffers // in-memory highWaterMark: 10 }); (async () => { try { const handle = await this.getFileHandle(resource); if (!handle) { throw this.createFileSystemProviderError(resource, 'No such file or directory, readFile', FileSystemProviderErrorCode.FileNotFound); } const file = await handle.getFile(); // Partial file: implemented simply via `readFile` if (typeof opts.length === 'number' || typeof opts.position === 'number') { let buffer = new Uint8Array(await file.arrayBuffer()); if (typeof opts?.position === 'number') { buffer = buffer.slice(opts.position); } if (typeof opts?.length === 'number') { buffer = buffer.slice(0, opts.length); } stream.end(buffer); } // Entire file else { const reader: ReadableStreamDefaultReader<Uint8Array> = file.stream().getReader(); let res = await reader.read(); while (!res.done) { if (token.isCancellationRequested) { break; } // Write buffer into stream but make sure to wait // in case the `highWaterMark` is reached await stream.write(res.value); if (token.isCancellationRequested) { break; } res = await reader.read(); } stream.end(undefined); } } catch (error) { stream.error(this.toFileSystemProviderError(error)); stream.end(); } })(); return stream; } async readFile(resource: URI): Promise<Uint8Array> { try { const handle = await this.getFileHandle(resource); if (!handle) { throw this.createFileSystemProviderError(resource, 'No such file or directory, readFile', FileSystemProviderErrorCode.FileNotFound); } const file = await handle.getFile(); return new Uint8Array(await file.arrayBuffer()); } catch (error) { throw this.toFileSystemProviderError(error); } } async writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> { try { let handle = await this.getFileHandle(resource); // Validate target unless { create: true, overwrite: true } if (!opts.create || !opts.overwrite) { if (handle) { if (!opts.overwrite) { throw this.createFileSystemProviderError(resource, 'File already exists, writeFile', FileSystemProviderErrorCode.FileExists); } } else { if (!opts.create) { throw this.createFileSystemProviderError(resource, 'No such file, writeFile', FileSystemProviderErrorCode.FileNotFound); } } } // Create target as needed if (!handle) { const parent = await this.getDirectoryHandle(this.extUri.dirname(resource)); if (!parent) { throw this.createFileSystemProviderError(resource, 'No such parent directory, writeFile', FileSystemProviderErrorCode.FileNotFound); } handle = await parent.getFileHandle(this.extUri.basename(resource), { create: true }); if (!handle) { throw this.createFileSystemProviderError(resource, 'Unable to create file , writeFile', FileSystemProviderErrorCode.Unknown); } } // Write to target overwriting any existing contents const writable = await handle.createWritable(); await writable.write(content); await writable.close(); } catch (error) { throw this.toFileSystemProviderError(error); } } //#endregion //#region Move/Copy/Delete/Create Folder async mkdir(resource: URI): Promise<void> { try { const parent = await this.getDirectoryHandle(this.extUri.dirname(resource)); if (!parent) { throw this.createFileSystemProviderError(resource, 'No such parent directory, mkdir', FileSystemProviderErrorCode.FileNotFound); } await parent.getDirectoryHandle(this.extUri.basename(resource), { create: true }); } catch (error) { throw this.toFileSystemProviderError(error); } } async delete(resource: URI, opts: FileDeleteOptions): Promise<void> { try { const parent = await this.getDirectoryHandle(this.extUri.dirname(resource)); if (!parent) { throw this.createFileSystemProviderError(resource, 'No such parent directory, delete', FileSystemProviderErrorCode.FileNotFound); } return parent.removeEntry(this.extUri.basename(resource), { recursive: opts.recursive }); } catch (error) { throw this.toFileSystemProviderError(error); } } async rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { try { if (this.extUri.isEqual(from, to)) { return; // no-op if the paths are the same } // Implement file rename by write + delete let fileHandle = await this.getFileHandle(from); if (fileHandle) { const file = await fileHandle.getFile(); const contents = new Uint8Array(await file.arrayBuffer()); await this.writeFile(to, contents, { create: true, overwrite: opts.overwrite, unlock: false }); await this.delete(from, { recursive: false, useTrash: false }); } // File API does not support any real rename otherwise else { throw this.createFileSystemProviderError(from, localize('fileSystemRenameError', "Rename is only supported for files."), FileSystemProviderErrorCode.Unavailable); } } catch (error) { throw this.toFileSystemProviderError(error); } } //#endregion //#region File Watching (unsupported) watch(resource: URI, opts: IWatchOptions): IDisposable { return Disposable.None; } //#endregion //#region File/Directoy Handle Registry private readonly files = new Map<string, FileSystemFileHandle>(); private readonly directories = new Map<string, FileSystemDirectoryHandle>(); registerFileHandle(handle: FileSystemFileHandle): URI { return this.registerHandle(handle, this.files); } registerDirectoryHandle(handle: FileSystemDirectoryHandle): URI { return this.registerHandle(handle, this.directories); } private registerHandle(handle: FileSystemHandle, map: Map<string, FileSystemHandle>): URI { let handleId = `/${handle.name}`; // Compute a valid handle ID in case this exists already if (map.has(handleId)) { let handleIdCounter = 2; do { handleId = `/${handle.name}-${handleIdCounter++}`; } while (map.has(handleId)); } map.set(handleId, handle); return URI.from({ scheme: Schemas.file, path: handleId }); } async getHandle(resource: URI): Promise<FileSystemHandle | undefined> { // First: try to find a well known handle first let handle = this.getHandleSync(resource); // Second: walk up parent directories and resolve handle if possible if (!handle) { const parent = await this.getDirectoryHandle(this.extUri.dirname(resource)); if (parent) { const name = extUri.basename(resource); try { handle = await parent.getFileHandle(name); } catch (error) { try { handle = await parent.getDirectoryHandle(name); } catch (error) { // Ignore } } } } return handle; } private getHandleSync(resource: URI): FileSystemHandle | undefined { // We store file system handles with the `handle.name` // and as such require the resource to be on the root if (this.extUri.dirname(resource).path !== '/') { return undefined; } const handleId = resource.path.replace(/\/$/, ''); // remove potential slash from the end of the path const handle = this.files.get(handleId) ?? this.directories.get(handleId); if (!handle) { throw this.createFileSystemProviderError(resource, 'No file system handle registered', FileSystemProviderErrorCode.Unavailable); } return handle; } private async getFileHandle(resource: URI): Promise<FileSystemFileHandle | undefined> { const handle = this.getHandleSync(resource); if (handle instanceof FileSystemFileHandle) { return handle; } const parent = await this.getDirectoryHandle(this.extUri.dirname(resource)); try { return await parent?.getFileHandle(extUri.basename(resource)); } catch (error) { return undefined; // guard against possible DOMException } } private async getDirectoryHandle(resource: URI): Promise<FileSystemDirectoryHandle | undefined> { const handle = this.getHandleSync(resource); if (handle instanceof FileSystemDirectoryHandle) { return handle; } const parent = await this.getDirectoryHandle(this.extUri.dirname(resource)); try { return await parent?.getDirectoryHandle(extUri.basename(resource)); } catch (error) { return undefined; // guard against possible DOMException } } //#endregion private toFileSystemProviderError(error: Error): FileSystemProviderError { if (error instanceof FileSystemProviderError) { return error; // avoid double conversion } let code = FileSystemProviderErrorCode.Unknown; if (error.name === 'NotAllowedError') { error = new Error(localize('fileSystemNotAllowedError', "Insufficient permissions. Please retry and allow the operation.")); code = FileSystemProviderErrorCode.Unavailable; } return createFileSystemProviderError(error, code); } private createFileSystemProviderError(resource: URI, msg: string, code: FileSystemProviderErrorCode): FileSystemProviderError { return createFileSystemProviderError(new Error(`${msg} (${normalize(resource.path)})`), code); } }
the_stack
import { Autowired, Bean, Optional } from "../../context/context"; import { GridOptions } from "../../entities/gridOptions"; import { FrameworkComponentWrapper } from "./frameworkComponentWrapper"; import { ColDef, ColGroupDef, CellEditorSelectorFunc, CellRendererSelectorFunc, CellEditorSelectorResult } from "../../entities/colDef"; import { UserComponentRegistry } from "./userComponentRegistry"; import { AgComponentUtils } from "./agComponentUtils"; import { ComponentMetadata, ComponentMetadataProvider } from "./componentMetadataProvider"; import { ISetFilterParams } from "../../interfaces/iSetFilterParams"; import { IRichCellEditorParams } from "../../interfaces/iRichCellEditorParams"; import { ToolPanelDef } from "../../entities/sideBar"; import { AgPromise } from "../../utils"; import { IDateComp, IDateParams } from "../../rendering/dateComponent"; import { ICellRendererComp, ICellRendererParams, ISetFilterCellRendererParams } from "../../rendering/cellRenderers/iCellRenderer"; import { ILoadingOverlayComp, ILoadingOverlayParams } from "../../rendering/overlays/loadingOverlayComponent"; import { INoRowsOverlayComp, INoRowsOverlayParams } from "../../rendering/overlays/noRowsOverlayComponent"; import { ITooltipComp, ITooltipParams } from "../../rendering/tooltipComponent"; import { IFilterComp, IFilterParams, IFilterDef } from "../../interfaces/iFilter"; import { IFloatingFilterComp, IFloatingFilterParams } from "../../filter/floating/floatingFilter"; import { ICellEditorComp, ICellEditorParams } from "../../interfaces/iCellEditor"; import { IToolPanelComp, IToolPanelParams } from "../../interfaces/iToolPanel"; import { IStatusPanelComp, IStatusPanelParams, StatusPanelDef } from "../../interfaces/iStatusPanel"; import { CellEditorComponent, CellRendererComponent, ComponentType, DateComponent, FilterComponent, FloatingFilterComponent, HeaderComponent, HeaderGroupComponent, InnerRendererComponent, LoadingOverlayComponent, NoRowsOverlayComponent, StatusPanelComponent, ToolPanelComponent, TooltipComponent } from "./componentTypes"; import { BeanStub } from "../../context/beanStub"; import { cloneObject, mergeDeep } from '../../utils/object'; import { GroupCellRendererParams } from "../../rendering/cellRenderers/groupCellRendererCtrl"; import { IHeaderGroupComp, IHeaderGroupParams } from "../../headerRendering/cells/columnGroup/headerGroupComp"; import { IHeaderComp, IHeaderParams } from "../../headerRendering/cells/column/headerComp"; export type DefinitionObject = GridOptions | ColDef | ColGroupDef | IFilterDef | ISetFilterParams | IRichCellEditorParams | ToolPanelDef | StatusPanelDef; export interface UserCompDetails { componentClass: any; componentFromFramework: boolean; params: any; type: ComponentType; } @Bean('userComponentFactory') export class UserComponentFactory extends BeanStub { @Autowired('gridOptions') private readonly gridOptions: GridOptions; @Autowired('agComponentUtils') private readonly agComponentUtils: AgComponentUtils; @Autowired('componentMetadataProvider') private readonly componentMetadataProvider: ComponentMetadataProvider; @Autowired('userComponentRegistry') private readonly userComponentRegistry: UserComponentRegistry; @Optional('frameworkComponentWrapper') private readonly frameworkComponentWrapper: FrameworkComponentWrapper; //////// NEW (after React UI) public getHeaderCompDetails(colDef: ColDef, params: IHeaderParams): UserCompDetails | undefined { return this.getCompDetails(colDef, HeaderComponent, 'agColumnHeader', params); } public getHeaderGroupCompDetails(params: IHeaderGroupParams): UserCompDetails | undefined { const colGroupDef = params.columnGroup.getColGroupDef()!; return this.getCompDetails(colGroupDef, HeaderGroupComponent, 'agColumnGroupHeader', params); } // this one is unusual, as it can be LoadingCellRenderer, DetailCellRenderer, FullWidthCellRenderer or GroupRowRenderer. // so we have to pass the type in. public getFullWidthCellRendererDetails(params: ICellRendererParams, cellRendererType: string, cellRendererName: string): UserCompDetails | undefined { return this.getCompDetails(this.gridOptions, { propertyName: cellRendererType, isCellRenderer: () => true }, cellRendererName, params); } // CELL RENDERER public getInnerRendererDetails(def: GroupCellRendererParams, params: ICellRendererParams): UserCompDetails | undefined { return this.getCompDetails(def, InnerRendererComponent, null, params); } public getFullWidthGroupRowInnerCellRenderer(def: any, params: ICellRendererParams): UserCompDetails | undefined { return this.getCompDetails(def, InnerRendererComponent, null, params); } public getCellRendererDetails(def: ColDef | IRichCellEditorParams, params: ICellRendererParams): UserCompDetails | undefined { return this.getCompDetails(def, CellRendererComponent, null, params); } // CELL EDITOR public getCellEditorDetails(def: ColDef, params: ICellEditorParams): UserCompDetails | undefined { return this.getCompDetails(def, CellEditorComponent, 'agCellEditor', params, true); } //////// OLD (before React UI) public newCellRenderer( def: ColDef | IRichCellEditorParams, params: ICellRendererParams): AgPromise<ICellRendererComp> | null { return this.lookupAndCreateComponent(def, params, CellRendererComponent, null, true); } public newDateComponent(params: IDateParams): AgPromise<IDateComp> | null { return this.lookupAndCreateComponent(this.gridOptions, params, DateComponent, 'agDateInput'); } public newLoadingOverlayComponent(params: ILoadingOverlayParams): AgPromise<ILoadingOverlayComp> | null { return this.lookupAndCreateComponent(this.gridOptions, params, LoadingOverlayComponent, 'agLoadingOverlay'); } public newNoRowsOverlayComponent(params: INoRowsOverlayParams): AgPromise<INoRowsOverlayComp> | null { return this.lookupAndCreateComponent(this.gridOptions, params, NoRowsOverlayComponent, 'agNoRowsOverlay'); } public newTooltipComponent(params: ITooltipParams): AgPromise<ITooltipComp> | null { return this.lookupAndCreateComponent(params.colDef!, params, TooltipComponent, 'agTooltipComponent'); } public newFilterComponent(def: IFilterDef, params: IFilterParams, defaultFilter: string): AgPromise<IFilterComp> | null { return this.lookupAndCreateComponent(def, params, FilterComponent, defaultFilter, false); } public newSetFilterCellRenderer( def: ISetFilterParams, params: ISetFilterCellRendererParams): AgPromise<ICellRendererComp> | null { return this.lookupAndCreateComponent(def, params, CellRendererComponent, null, true); } public newFloatingFilterComponent( def: IFilterDef, params: IFloatingFilterParams, defaultFloatingFilter: string | null): AgPromise<IFloatingFilterComp> | null { return this.lookupAndCreateComponent(def, params, FloatingFilterComponent, defaultFloatingFilter, true); } public newToolPanelComponent(toolPanelDef: ToolPanelDef, params: IToolPanelParams): AgPromise<IToolPanelComp> | null { return this.lookupAndCreateComponent(toolPanelDef, params, ToolPanelComponent); } public newStatusPanelComponent(def: StatusPanelDef, params: IStatusPanelParams): AgPromise<IStatusPanelComp> | null { return this.lookupAndCreateComponent(def, params, StatusPanelComponent); } private lookupComponent(defObject: DefinitionObject, type: ComponentType, params: any = null, defaultComponentName?: string | null): UserCompDetails | null { const propertyName = type.propertyName; let paramsFromSelector: any; let comp: any; let frameworkComp: any; // pull from defObject if available if (defObject) { let defObjectAny = defObject as any; // if selector, use this const selectorFunc: CellEditorSelectorFunc | CellRendererSelectorFunc = defObjectAny[propertyName + 'Selector']; const selectorRes = selectorFunc ? selectorFunc(params) : null; if (selectorRes) { comp = selectorRes.component; frameworkComp = selectorRes.frameworkComponent; paramsFromSelector = selectorRes.params; } else { // if no selector, or result of selector is empty, take from defObject comp = defObjectAny[propertyName]; frameworkComp = defObjectAny[propertyName + 'Framework']; } // for filters only, we allow 'true' for the component, which means default filter to be used if (comp === true) { comp = undefined; } } const lookupFromRegistry = (key: string) => { const item = this.userComponentRegistry.retrieve(key); if (item) { comp = !item.componentFromFramework ? item.component : undefined; frameworkComp = item.componentFromFramework ? item.component : undefined; } else { comp = undefined; frameworkComp = undefined; } }; // if compOption is a string, means we need to look the item up if (typeof comp === 'string') { lookupFromRegistry(comp); } // if lookup brought nothing back, and we have a default, lookup the default if (comp == null && frameworkComp == null && defaultComponentName != null) { lookupFromRegistry(defaultComponentName); } // if we have a comp option, and it's a function, replace it with an object equivalent adaptor if (comp && !this.agComponentUtils.doesImplementIComponent(comp)) { comp = this.agComponentUtils.adaptFunction(propertyName, comp); } if (!comp && !frameworkComp) { return null; } return { componentFromFramework: comp == null, componentClass: comp ? comp : frameworkComp, params: paramsFromSelector, type: type }; } public createInstanceFromCompDetails(compDetails: UserCompDetails, defaultComponentName?: string | null): AgPromise<any> | null { if (!compDetails) { return null; } const { params, componentClass, componentFromFramework } = compDetails; // Create the component instance const instance = this.createComponentInstance(compDetails.type, defaultComponentName, componentClass, componentFromFramework); if (!instance) { return null; } this.addReactHacks(params); const deferredInit = this.initComponent(instance, params); if (deferredInit == null) { return AgPromise.resolve(instance); } return (deferredInit as AgPromise<void>).then(() => instance); } /** * This method creates a component given everything needed to guess what sort of component needs to be instantiated * It takes * @param CompClass: The class to instantiate, * @param agGridParams: Params to be passed to the component and passed by AG Grid. This will get merged with any params * specified by the user in the configuration * @param modifyParamsCallback: A chance to customise the params passed to the init method. It receives what the current * params are and the component that init is about to get called for */ public createUserComponentFromConcreteClass(CompClass: any, agGridParams: any): any { const internalComponent = new CompClass(); this.initComponent(internalComponent, agGridParams); return internalComponent; } /** * Useful to check what would be the resultant params for a given object * @param definitionObject: This is the context for which this component needs to be created, it can be gridOptions * (global) or columnDef mostly. * @param propertyName: The name of the property used in ag-grid as a convention to refer to the component, it can be: * 'floatingFilter', 'cellRenderer', is used to find if the user is specifying a custom component * @param paramsFromGrid: Params to be passed to the component and passed by AG Grid. This will get merged with any params * specified by the user in the configuration * @returns {TParams} It merges the user agGridParams with the actual params specified by the user. */ public mergeParamsWithApplicationProvidedParams( definitionObject: DefinitionObject, propertyName: string, paramsFromGrid: any, paramsFromSelector: any = null): any { const params = {} as any; mergeDeep(params, paramsFromGrid); const userParams = definitionObject ? (definitionObject as any)[propertyName + "Params"] : null; if (userParams != null) { if (typeof userParams === 'function') { const userParamsFromFunc = userParams(paramsFromGrid); mergeDeep(params, userParamsFromFunc); } else if (typeof userParams === 'object') { mergeDeep(params, userParams); } } mergeDeep(params, paramsFromSelector); return params; } private getCompDetails(defObject: DefinitionObject, type: ComponentType, defaultName: string | null | undefined, params: any, mandatory = false): UserCompDetails | undefined { const propName = type.propertyName; const compDetails = this.lookupComponent(defObject, type, params, defaultName); if (!compDetails || !compDetails.componentClass) { if (mandatory) { this.logComponentMissing(defObject, propName); } return undefined; } const paramsMerged = this.mergeParamsWithApplicationProvidedParams( defObject, propName, params, compDetails.params); return { ...compDetails, params: paramsMerged }; } /** * This method creates a component given everything needed to guess what sort of component needs to be instantiated * It takes * @param definitionObject: This is the context for which this component needs to be created, it can be gridOptions * (global) or columnDef mostly. * @param paramsFromGrid: Params to be passed to the component and passed by AG Grid. This will get merged with any params * specified by the user in the configuration * @param propertyName: The name of the property used in ag-grid as a convention to refer to the component, it can be: * 'floatingFilter', 'cellRenderer', is used to find if the user is specifying a custom component * @param defaultComponentName: The actual name of the component to instantiate, this is usually the same as propertyName, but in * some cases is not, like floatingFilter, if it is the same is not necessary to specify * @param optional: Handy method to tell if this should return a component ALWAYS. if that is the case, but there is no * component found, it throws an error, by default all components are MANDATORY */ private lookupAndCreateComponent( def: DefinitionObject, paramsFromGrid: any, componentType: ComponentType, defaultComponentName?: string | null, // optional items are: FloatingFilter, CellComp (for cellRenderer) optional = false ): AgPromise<any> | null { const compDetails = this.getCompDetails( def, componentType, defaultComponentName, paramsFromGrid, !optional); if (!compDetails) { return null; } return this.createInstanceFromCompDetails(compDetails, defaultComponentName); } private addReactHacks(params: any): void { // a temporary fix for AG-1574 // AG-1715 raised to do a wider ranging refactor to improve this const agGridReact = this.context.getBean('agGridReact'); if (agGridReact) { params.agGridReact = cloneObject(agGridReact); } // AG-1716 - directly related to AG-1574 and AG-1715 const frameworkComponentWrapper = this.context.getBean('frameworkComponentWrapper'); if (frameworkComponentWrapper) { params.frameworkComponentWrapper = frameworkComponentWrapper; } } private logComponentMissing(holder: any, propertyName: string, defaultComponentName?: string | null): void { // to help the user, we print out the name they are looking for, rather than the default name. // i don't know why the default name was originally printed out (that doesn't help the user) const overrideName = holder ? (holder as any)[propertyName] : defaultComponentName; const nameToReport = overrideName ? overrideName : defaultComponentName; console.error(`Could not find component ${nameToReport}, did you forget to configure this component?`); } private createComponentInstance( componentType: ComponentType, defaultComponentName: string | null | undefined, component: any, componentFromFramework: boolean ): any { const propertyName = componentType.propertyName; // using javascript component const jsComponent = !componentFromFramework; if (jsComponent) { return new component!(); } if (!this.frameworkComponentWrapper) { console.warn(`AG Grid - Because you are using our new React UI (property reactUi=true), it is not possible to use a React Component for ${componentType.propertyName}. This is work in progress and we plan to support this soon. In the meantime, please either set reactUi=false, or replace this component with one written in JavaScript.`); return null; } // Using framework component const FrameworkComponentRaw: any = component; const thisComponentConfig: ComponentMetadata = this.componentMetadataProvider.retrieve(propertyName); return this.frameworkComponentWrapper.wrap( FrameworkComponentRaw, thisComponentConfig.mandatoryMethodList, thisComponentConfig.optionalMethodList, componentType, defaultComponentName ); } private initComponent(component: any, params: any): AgPromise<void> | void { this.context.createBean(component); if (component.init == null) { return; } return component.init(params); } }
the_stack
import { buildSchema, GraphQLSchema, GraphQLString, GraphQLObjectType, GraphQLNonNull, } from 'graphql' import { Hono } from '../../hono' import { errorMessages, graphqlServer } from '.' // Do not show `console.error` messages jest.spyOn(console, 'error').mockImplementation() describe('errorMessages', () => { const messages = errorMessages(['message a', 'message b']) expect(messages).toEqual({ errors: [ { message: 'message a', }, { message: 'message b', }, ], }) }) describe('GraphQL Middleware - Simple way', () => { // Construct a schema, using GraphQL schema language const schema = buildSchema(` type Query { hello: String } `) // The root provides a resolver function for each API endpoint const rootValue = { hello: () => 'Hello world!', } const app = new Hono() app.use( '/graphql', graphqlServer({ schema, rootValue, }) ) app.all('*', (c) => { c.header('foo', 'bar') return c.text('fallback') }) it('Should return GraphQL response', async () => { const query = 'query { hello }' const body = { query: query, } const res = await app.request('http://localhost/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"hello":"Hello world!"}}') expect(res.headers.get('foo')).toBeNull() // GraphQL Server middleware should be Handler }) }) const QueryRootType = new GraphQLObjectType({ name: 'QueryRoot', fields: { test: { type: GraphQLString, args: { who: { type: GraphQLString }, }, resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'), }, thrower: { type: GraphQLString, resolve() { throw new Error('Throws!') }, }, }, }) const TestSchema = new GraphQLSchema({ query: QueryRootType, mutation: new GraphQLObjectType({ name: 'MutationRoot', fields: { writeTest: { type: QueryRootType, resolve: () => ({}), }, }, }), }) const urlString = (query?: Record<string, string>): string => { const base = 'http://localhost/graphql' if (!query) return base const queryString = new URLSearchParams(query).toString() return `${base}?${queryString}` } describe('GraphQL Middleware - GET functionality', () => { const app = new Hono() app.use( '/graphql', graphqlServer({ schema: TestSchema, }) ) it('Allows GET with variable values', async () => { const query = { query: 'query helloWho($who: String){ test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}') }) it('Allows GET with operation name', async () => { const query = { query: ` query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } `, operationName: 'helloWorld', } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ data: { test: 'Hello World', shared: 'Hello Everyone', }, }) }) it('Reports validation errors', async () => { const query = { query: '{ test, unknownOne, unknownTwo }' } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(400) }) it('Errors when missing operation name', async () => { const query = { query: ` query TestQuery { test } mutation TestMutation { writeTest { test } } `, } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(500) }) it('Errors when sending a mutation via GET', async () => { const query = { query: 'mutation TestMutation { writeTest { test } }', } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(405) }) it('Errors when selecting a mutation within a GET', async () => { const query = { operationName: 'TestMutation', query: ` query TestQuery { test } mutation TestMutation { writeTest { test } } `, } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(405) }) it('Allows a mutation to exist within a GET', async () => { const query = { operationName: 'TestQuery', query: ` mutation TestMutation { writeTest { test } } query TestQuery { test } `, } const res = await app.request(urlString(query), { method: 'GET', }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ data: { test: 'Hello World', }, }) }) }) describe('GraphQL Middleware - POST functionality', () => { const app = new Hono() app.use( '/graphql', graphqlServer({ schema: TestSchema, }) ) it('Allows POST with JSON encoding', async () => { const query = { query: '{test}' } const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(query), }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello World"}}') }) it('Allows sending a mutation via POST', async () => { const query = { query: 'mutation TestMutation { writeTest { test } }' } const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(query), }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"writeTest":{"test":"Hello World"}}}') }) it('Allows POST with url encoding', async () => { const query = { query: '{test}', } const res = await app.request(urlString(query), { method: 'POST', }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello World"}}') }) it('Supports POST JSON query with string variables', async () => { const query = { query: 'query helloWho($who: String){ test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), } const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(query), }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}') }) it('Supports POST url encoded query with string variables', async () => { const searchParams = new URLSearchParams({ query: 'query helloWho($who: String){ test(who: $who) }', variables: JSON.stringify({ who: 'Dolly' }), }) const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: searchParams.toString(), }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}') }) it('Supports POST JSON query with GET variable values', async () => { const variables = { variables: JSON.stringify({ who: 'Dolly' }), } const query = { query: 'query helloWho($who: String){ test(who: $who) }' } const res = await app.request(urlString(variables), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(query), }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}') }) it('Supports POST url encoded query with GET variable values', async () => { const searchParams = new URLSearchParams({ query: 'query helloWho($who: String){ test(who: $who) }', }) const variables = { variables: JSON.stringify({ who: 'Dolly' }), } const res = await app.request(urlString(variables), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: searchParams.toString(), }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}') }) it('Supports POST raw text query with GET variable values', async () => { const variables = { variables: JSON.stringify({ who: 'Dolly' }), } const res = await app.request(urlString(variables), { method: 'POST', headers: { 'Content-Type': 'application/graphql', }, body: 'query helloWho($who: String){ test(who: $who) }', }) expect(res.status).toBe(200) expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}') }) it('Allows POST with operation name', async () => { const query = { query: ` query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } `, operationName: 'helloWorld', } const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(query), }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ data: { test: 'Hello World', shared: 'Hello Everyone', }, }) }) it('Allows POST with GET operation name', async () => { const res = await app.request( urlString({ operationName: 'helloWorld', }), { method: 'POST', headers: { 'Content-Type': 'application/graphql', }, body: ` query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } `, } ) expect(res.status).toBe(200) expect(await res.json()).toEqual({ data: { test: 'Hello World', shared: 'Hello Everyone', }, }) }) }) describe('Pretty printing', () => { it('Supports pretty printing', async () => { const app = new Hono() app.use( '/graphql', graphqlServer({ schema: TestSchema, pretty: true, }) ) const res = await app.request(urlString({ query: '{test}' })) expect(await res.text()).toEqual( [ // Pretty printed JSON '{', ' "data": {', ' "test": "Hello World"', ' }', '}', ].join('\n') ) }) }) describe('Error handling functionality', () => { const app = new Hono() app.use( '/graphql', graphqlServer({ schema: TestSchema, }) ) it('Handles query errors from non-null top field errors', async () => { const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { test: { type: new GraphQLNonNull(GraphQLString), resolve() { throw new Error('Throws!') }, }, }, }), }) const app = new Hono() app.use('/graphql', graphqlServer({ schema })) const res = await app.request( urlString({ query: '{ test }', }) ) expect(res.status).toBe(500) }) it('Handles syntax errors caught by GraphQL', async () => { const res = await app.request( urlString({ query: 'syntax_error', }), { method: 'GET', } ) expect(res.status).toBe(400) }) it('Handles errors caused by a lack of query', async () => { const res = await app.request(urlString(), { method: 'GET', }) expect(res.status).toBe(400) }) it('Handles invalid JSON bodies', async () => { const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify([]), }) expect(res.status).toBe(400) }) it('Handles incomplete JSON bodies', async () => { const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: '{"query":', }) expect(res.status).toBe(400) }) it('Handles plain POST text', async () => { const res = await app.request( urlString({ variables: JSON.stringify({ who: 'Dolly' }), }), { method: 'POST', headers: { 'Content-Type': 'text/plain', }, body: 'query helloWho($who: String){ test(who: $who) }', } ) expect(res.status).toBe(400) }) it('Handles poorly formed variables', async () => { const res = await app.request( urlString({ variables: 'who:You', query: 'query helloWho($who: String){ test(who: $who) }', }), { method: 'GET', } ) expect(res.status).toBe(400) }) it('Handles invalid variables', async () => { const res = await app.request(urlString(), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: 'query helloWho($who: String){ test(who: $who) }', variables: { who: ['John', 'Jane'] }, }), }) expect(res.status).toBe(500) }) it('Handles unsupported HTTP methods', async () => { const res = await app.request(urlString({ query: '{test}' }), { method: 'PUT', }) expect(res.status).toBe(405) expect(res.headers.get('allow')).toBe('GET, POST') expect(await res.json()).toEqual({ errors: [{ message: 'GraphQL only supports GET and POST requests.' }], }) }) })
the_stack
import * as assert from 'assert'; import { IExtensionManifest, ExtensionUntrustedWorkspaceSupportType } from 'vs/platform/extensions/common/extensions'; import { ExtensionManifestPropertiesService } from 'vs/workbench/services/extensions/common/extensionManifestPropertiesService'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestProductService } from 'vs/workbench/test/common/workbenchTestServices'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IProductService } from 'vs/platform/product/common/productService'; import { isWeb } from 'vs/base/common/platform'; import { TestWorkspaceTrustEnablementService } from 'vs/workbench/services/workspaces/test/common/testWorkspaceTrustService'; import { IWorkspaceTrustEnablementService } from 'vs/platform/workspace/common/workspaceTrust'; import { NullLogService } from 'vs/platform/log/common/log'; suite('ExtensionManifestPropertiesService - ExtensionKind', () => { let testObject = new ExtensionManifestPropertiesService(TestProductService, new TestConfigurationService(), new TestWorkspaceTrustEnablementService(), new NullLogService()); test('declarative with extension dependencies', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ extensionDependencies: ['ext1'] }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('declarative extension pack', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ extensionPack: ['ext1', 'ext2'] }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('declarative extension pack and extension dependencies', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ extensionPack: ['ext1', 'ext2'], extensionDependencies: ['ext1', 'ext2'] }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('declarative with unknown contribution point => workspace, web in web and => workspace in desktop', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ contributes: <any>{ 'unknownPoint': { something: true } } }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('declarative extension pack with unknown contribution point', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ extensionPack: ['ext1', 'ext2'], contributes: <any>{ 'unknownPoint': { something: true } } }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('simple declarative => ui, workspace, web', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{}), ['ui', 'workspace', 'web']); }); test('only browser => web', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ browser: 'main.browser.js' }), ['web']); }); test('only main => workspace', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ main: 'main.js' }), ['workspace']); }); test('main and browser => workspace, web in web and workspace in desktop', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ main: 'main.js', browser: 'main.browser.js' }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('browser entry point with workspace extensionKind => workspace, web in web and workspace in desktop', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ main: 'main.js', browser: 'main.browser.js', extensionKind: ['workspace'] }), isWeb ? ['workspace', 'web'] : ['workspace']); }); test('only browser entry point with out extensionKind => web', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ browser: 'main.browser.js' }), ['web']); }); test('simple descriptive with workspace, ui extensionKind => workspace, ui, web in web and workspace, ui in desktop', () => { assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ extensionKind: ['workspace', 'ui'] }), isWeb ? ['workspace', 'ui', 'web'] : ['workspace', 'ui']); }); test('opt out from web through settings even if it can run in web', () => { testObject = new ExtensionManifestPropertiesService(TestProductService, new TestConfigurationService({ remote: { extensionKind: { 'pub.a': ['-web'] } } }), new TestWorkspaceTrustEnablementService(), new NullLogService()); assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ browser: 'main.browser.js', publisher: 'pub', name: 'a' }), ['ui', 'workspace']); }); test('opt out from web and include only workspace through settings even if it can run in web', () => { testObject = new ExtensionManifestPropertiesService(TestProductService, new TestConfigurationService({ remote: { extensionKind: { 'pub.a': ['-web', 'workspace'] } } }), new TestWorkspaceTrustEnablementService(), new NullLogService()); assert.deepStrictEqual(testObject.getExtensionKind(<IExtensionManifest>{ browser: 'main.browser.js', publisher: 'pub', name: 'a' }), ['workspace']); }); test('extension cannot opt out from web', () => { assert.deepStrictEqual(testObject.getExtensionKind(<any>{ browser: 'main.browser.js', extensionKind: ['-web'] }), ['web']); }); test('extension cannot opt into web', () => { assert.deepStrictEqual(testObject.getExtensionKind(<any>{ main: 'main.js', extensionKind: ['web', 'workspace', 'ui'] }), ['workspace', 'ui']); }); test('extension cannot opt into web only', () => { assert.deepStrictEqual(testObject.getExtensionKind(<any>{ main: 'main.js', extensionKind: ['web'] }), ['workspace']); }); }); // Workspace Trust is disabled in web at the moment if (!isWeb) { suite('ExtensionManifestPropertiesService - ExtensionUntrustedWorkspaceSupportType', () => { let testObject: ExtensionManifestPropertiesService; let instantiationService: TestInstantiationService; let testConfigurationService: TestConfigurationService; setup(async () => { instantiationService = new TestInstantiationService(); testConfigurationService = new TestConfigurationService(); instantiationService.stub(IConfigurationService, testConfigurationService); }); teardown(() => testObject.dispose()); function assertUntrustedWorkspaceSupport(extensionMaifest: IExtensionManifest, expected: ExtensionUntrustedWorkspaceSupportType): void { testObject = instantiationService.createInstance(ExtensionManifestPropertiesService); const untrustedWorkspaceSupport = testObject.getExtensionUntrustedWorkspaceSupportType(extensionMaifest); assert.strictEqual(untrustedWorkspaceSupport, expected); } function getExtensionManifest(properties: any = {}): IExtensionManifest { return Object.create({ name: 'a', publisher: 'pub', version: '1.0.0', ...properties }) as IExtensionManifest; } test('test extension workspace trust request when main entry point is missing', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest(); assertUntrustedWorkspaceSupport(extensionMaifest, true); }); test('test extension workspace trust request when workspace trust is disabled', async () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService(false)); const extensionMaifest = getExtensionManifest({ main: './out/extension.js' }); assertUntrustedWorkspaceSupport(extensionMaifest, true); }); test('test extension workspace trust request when "true" override exists in settings.json', async () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); await testConfigurationService.setUserConfiguration('extensions', { supportUntrustedWorkspaces: { 'pub.a': { supported: true } } }); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); assertUntrustedWorkspaceSupport(extensionMaifest, true); }); test('test extension workspace trust request when override (false) exists in settings.json', async () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); await testConfigurationService.setUserConfiguration('extensions', { supportUntrustedWorkspaces: { 'pub.a': { supported: false } } }); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); assertUntrustedWorkspaceSupport(extensionMaifest, false); }); test('test extension workspace trust request when override (true) for the version exists in settings.json', async () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); await testConfigurationService.setUserConfiguration('extensions', { supportUntrustedWorkspaces: { 'pub.a': { supported: true, version: '1.0.0' } } }); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); assertUntrustedWorkspaceSupport(extensionMaifest, true); }); test('test extension workspace trust request when override (false) for the version exists in settings.json', async () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); await testConfigurationService.setUserConfiguration('extensions', { supportUntrustedWorkspaces: { 'pub.a': { supported: false, version: '1.0.0' } } }); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); assertUntrustedWorkspaceSupport(extensionMaifest, false); }); test('test extension workspace trust request when override for a different version exists in settings.json', async () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); await testConfigurationService.setUserConfiguration('extensions', { supportUntrustedWorkspaces: { 'pub.a': { supported: true, version: '2.0.0' } } }); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); assertUntrustedWorkspaceSupport(extensionMaifest, 'limited'); }); test('test extension workspace trust request when default (true) exists in product.json', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{ extensionUntrustedWorkspaceSupport: { 'pub.a': { default: true } } }); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest({ main: './out/extension.js' }); assertUntrustedWorkspaceSupport(extensionMaifest, true); }); test('test extension workspace trust request when default (false) exists in product.json', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{ extensionUntrustedWorkspaceSupport: { 'pub.a': { default: false } } }); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest({ main: './out/extension.js' }); assertUntrustedWorkspaceSupport(extensionMaifest, false); }); test('test extension workspace trust request when override (limited) exists in product.json', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{ extensionUntrustedWorkspaceSupport: { 'pub.a': { override: 'limited' } } }); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: true } } }); assertUntrustedWorkspaceSupport(extensionMaifest, 'limited'); }); test('test extension workspace trust request when override (false) exists in product.json', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{ extensionUntrustedWorkspaceSupport: { 'pub.a': { override: false } } }); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: true } } }); assertUntrustedWorkspaceSupport(extensionMaifest, false); }); test('test extension workspace trust request when value exists in package.json', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest({ main: './out/extension.js', capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); assertUntrustedWorkspaceSupport(extensionMaifest, 'limited'); }); test('test extension workspace trust request when no value exists in package.json', () => { instantiationService.stub(IProductService, <Partial<IProductService>>{}); instantiationService.stub(IWorkspaceTrustEnablementService, new TestWorkspaceTrustEnablementService()); const extensionMaifest = getExtensionManifest({ main: './out/extension.js' }); assertUntrustedWorkspaceSupport(extensionMaifest, false); }); }); }
the_stack
import {assert} from '@esm-bundle/chai'; import { MergedAsyncIterables, relativeUrlPath, resolveUrlPath, classifySpecifier, parseNpmStyleSpecifier, fileExtension, changeFileExtension, charToLineAndChar, } from '../typescript-worker/util.js'; suite('MergedAsyncIterables', () => { const flush = async <T>(iterable: AsyncIterable<T>): Promise<T[]> => { const results: T[] = []; for await (const value of iterable) { results.push(value); } return results; }; const raf = () => new Promise((resolve) => requestAnimationFrame(resolve)); test('zero iterables', async () => { const expected: unknown[] = []; const merged = new MergedAsyncIterables(); const actual = await flush(merged); assert.deepEqual(actual, expected); }); test('one iterable', async () => { const a = (async function* () { yield 'a0'; yield 'a1'; })(); const expected = ['a0', 'a1']; const merged = new MergedAsyncIterables(); merged.add(a); const actual = await flush(merged); assert.deepEqual(actual, expected); }); test('throws if iterator added after complete', async () => { const merged = new MergedAsyncIterables(); merged.add( (async function* () { yield 'a'; })() ); await flush(merged); assert.throws(() => { merged.add( (async function* () { yield 'b'; })() ); }); }); test('two iterables', async () => { const a = (async function* () { await raf(); yield 'a0'; yield 'a1'; })(); const b = (async function* () { yield 'b0'; yield 'b1'; })(); const expected = ['b0', 'b1', 'a0', 'a1']; const merged = new MergedAsyncIterables(); merged.add(a); merged.add(b); const actual = await flush(merged); assert.deepEqual(actual, expected); }); test('three iterables', async () => { const a = (async function* () { await raf(); // 0 await raf(); // 1 yield 'a0'; await raf(); // 2 await raf(); // 3 yield 'a1'; })(); const b = (async function* () { yield 'b0'; await raf(); // 0 await raf(); // 1 await raf(); // 2 await raf(); // 3 await raf(); // 4 yield 'b1'; })(); const c = (async function* () { await raf(); // 0 yield 'c0'; await raf(); // 1 await raf(); // 2 yield 'c1'; })(); const expected = ['b0', 'c0', 'a0', 'c1', 'a1', 'b1']; const merged = new MergedAsyncIterables(); merged.add(a); merged.add(b); merged.add(c); const actual = await flush(merged); assert.deepEqual(actual, expected); }); test('recursively add iterables', async () => { const merged = new MergedAsyncIterables(); const a = (async function* () { yield 'a0'; merged.add( (async function* () { await raf(); yield 'b0'; merged.add( (async function* () { yield 'c0'; })() ); await raf(); yield 'b1'; })() ); yield 'a1'; })(); const expected = ['a0', 'a1', 'b0', 'c0', 'b1']; merged.add(a); const actual = await flush(merged); assert.deepEqual(actual, expected); }); test('notice a new iterator while waiting on an existing one', async () => { const merged = new MergedAsyncIterables<string>(); merged.add( (async function* () { await raf(); yield 'slow'; })() ); // The key thing about this test is that we've started iterating before // adding the second source. const actual: string[] = []; const done = (async () => { for await (const value of merged) { actual.push(value); } })(); merged.add( (async function* () { yield 'fast'; })() ); await done; const expected = ['fast', 'slow']; assert.deepEqual(actual, expected); }); }); suite('relativeUrlPath', () => { const cases: Array<{from: string; to: string; expected: string}> = [ { from: 'index.js', to: 'my-element.js', expected: './my-element.js', }, { from: 'index.js', to: 'node_modules/foo/foo.js', expected: './node_modules/foo/foo.js', }, { from: 'node_modules/foo/foo.js', to: 'node_modules/foo/foo2.js', expected: './foo2.js', }, { from: 'node_modules/foo/foo.js', to: 'node_modules/bar/bar.js', expected: '../bar/bar.js', }, { from: 'node_modules/foo/a/b/c.js', to: 'node_modules/bar/a/b/c.js', expected: '../../../bar/a/b/c.js', }, { from: 'index.js', to: 'index.js', expected: '', }, { from: '', to: 'index.js', expected: './index.js', }, { from: 'index.js', to: '', expected: './', }, { from: '', to: '', expected: '', }, ]; for (const {from, to, expected} of cases) { test(`"${from}" -> "${to}"`, () => { const actual = relativeUrlPath(from, to); assert.equal(actual, expected); }); } }); suite('resolveUrlPath', () => { const cases: Array<{a: string; b: string; expected: string}> = [ { a: 'index.js', b: './my-element.js', expected: '/my-element.js', }, { a: 'index.js', b: './node_modules/foo/foo.js', expected: '/node_modules/foo/foo.js', }, { a: 'node_modules/foo/foo.js', b: './foo2.js', expected: '/node_modules/foo/foo2.js', }, { a: 'node_modules/foo/foo.js', b: '../bar/bar.js', expected: '/node_modules/bar/bar.js', }, { a: 'node_modules/foo/a/b/c.js', b: '../../../bar/a/b/c.js', expected: '/node_modules/bar/a/b/c.js', }, { a: 'index.js', b: '', expected: '/index.js', }, { a: 'node_modules/index.js', b: '.', expected: '/node_modules/', }, { a: 'node_modules/index.js', b: './', expected: '/node_modules/', }, { a: 'node_modules/index.js', b: '../', expected: '/', }, ]; for (const {a, b, expected} of cases) { test(`"${a}" -> "${b}"`, () => { const actual = resolveUrlPath(a, b); assert.equal(actual, expected); }); } }); suite('classifySpecifier', () => { const cases: Array<{specifier: string; expected: string}> = [ { specifier: 'foo', expected: 'bare', }, { specifier: 'foo.js', expected: 'bare', }, { specifier: './foo.js', expected: 'relative', }, { specifier: '../foo.js', expected: 'relative', }, { specifier: '../../foo/bar.js', expected: 'relative', }, { specifier: '/foo.js', expected: 'relative', }, { specifier: 'http://example.com/foo.js', expected: 'url', }, ]; for (const {specifier, expected} of cases) { test(specifier, () => { const actual = classifySpecifier(specifier); assert.equal(actual, expected); }); } }); suite('parseNpmStyleSpecifier', () => { const cases: Array<{ specifier: string; expected: ReturnType<typeof parseNpmStyleSpecifier>; }> = [ { specifier: 'foo', expected: {pkg: 'foo', version: '', path: ''}, }, { specifier: 'foo@^1.2.3', expected: {pkg: 'foo', version: '^1.2.3', path: ''}, }, { specifier: 'foo/bar.js', expected: {pkg: 'foo', version: '', path: 'bar.js'}, }, { specifier: 'foo@^1.2.3/bar.js', expected: {pkg: 'foo', version: '^1.2.3', path: 'bar.js'}, }, { specifier: '@ns/foo', expected: {pkg: '@ns/foo', version: '', path: ''}, }, { specifier: '@ns/foo@^1.2.3', expected: {pkg: '@ns/foo', version: '^1.2.3', path: ''}, }, { specifier: '@ns/foo/bar.js', expected: {pkg: '@ns/foo', version: '', path: 'bar.js'}, }, { specifier: '@ns/foo@^1.2.3/bar.js', expected: {pkg: '@ns/foo', version: '^1.2.3', path: 'bar.js'}, }, { specifier: '', expected: undefined, }, ]; for (const {specifier, expected} of cases) { test(specifier, () => { const actual = parseNpmStyleSpecifier(specifier); assert.deepEqual(actual, expected); }); } }); suite('fileExtension', () => { const cases: Array<{ path: string; expected: string; }> = [ { path: 'foo', expected: '', }, { path: 'foo.js', expected: 'js', }, { path: 'foo.ts', expected: 'ts', }, { path: 'foo.ts/bar.js', expected: 'js', }, ]; for (const {path, expected} of cases) { test(path, () => { const actual = fileExtension(path); assert.equal(actual, expected); }); } }); suite('changeFileExtension', () => { const cases: Array<{ path: string; newExt: string; expected: string; }> = [ { path: 'foo', newExt: 'd.ts', expected: 'foo.d.ts', }, { path: 'foo.js', newExt: 'd.ts', expected: 'foo.d.ts', }, { path: '', newExt: 'd.ts', expected: '.d.ts', }, { path: 'foo.js', newExt: '', expected: 'foo.', }, ]; for (const {path, newExt, expected} of cases) { test(`"${path}" -> "${newExt}"`, () => { const actual = changeFileExtension(path, newExt); assert.equal(actual, expected); }); } }); suite('charToLineAndChar', () => { const cases: Array<{ str: string; char: number; expected: ReturnType<typeof charToLineAndChar>; }> = [ { str: 'foo\nbar\nbaz', // ^ char: 0, expected: {line: 0, character: 0}, }, { str: 'foo\nbar\nbaz', // ^^ char: 3, expected: {line: 0, character: 3}, }, { str: 'foo\nbar\nbaz', // ^ char: 4, expected: {line: 1, character: 0}, }, { str: 'foo\r\nbar\r\nbaz', // ^^ char: 3, expected: {line: 0, character: 3}, }, { str: 'foo\r\nbar\r\nbaz', // ^^ char: 4, expected: {line: 0, character: 4}, }, { str: 'foo\r\nbar\r\nbaz', // ^ char: 5, expected: {line: 1, character: 0}, }, { str: 'foo\nbar\nbaz', // ^ char: 10, expected: {line: 2, character: 2}, }, ]; for (const {str, char, expected} of cases) { test(`${char} in ${JSON.stringify(str)}`, () => { const actual = charToLineAndChar(str, char); assert.deepEqual(actual, expected); }); } });
the_stack
declare module DevExpress { /** @deprecated Use DevExpress.events.EventObject instead */ export type dxEvent = DevExpress.events.EventObject /** @deprecated Use DevExpress.events.event instead */ export type event = DevExpress.events.event } declare module DevExpress.viz { /** @deprecated Use DevExpress.viz.ChartSeries instead */ export type dxChartSeries = DevExpress.viz.ChartSeries; /** @deprecated Use DevExpress.viz.PieChartSeries instead */ export type dxPieChartSeries = DevExpress.viz.PieChartSeries; /** @deprecated Use DevExpress.viz.PolarChartSeries instead */ export type dxPolarChartSeries = DevExpress.viz.PolarChartSeries; /** @deprecated Use DevExpress.viz instead */ export module charts { export type dxChartOptions = DevExpress.viz.dxChartOptions; export type dxChartArgumentAxis = DevExpress.viz.dxChartArgumentAxis; export type dxChartArgumentAxisConstantLines = DevExpress.viz.dxChartArgumentAxisConstantLines; export type dxChartArgumentAxisConstantLinesLabel = DevExpress.viz.dxChartArgumentAxisConstantLinesLabel; export type dxChartArgumentAxisConstantLineStyle = DevExpress.viz.dxChartArgumentAxisConstantLineStyle; export type dxChartArgumentAxisConstantLineStyleLabel = DevExpress.viz.dxChartArgumentAxisConstantLineStyleLabel; export type dxChartArgumentAxisLabel = DevExpress.viz.dxChartArgumentAxisLabel; export type dxChartArgumentAxisStrips = DevExpress.viz.dxChartArgumentAxisStrips; export type dxChartArgumentAxisStripsLabel = DevExpress.viz.dxChartArgumentAxisStripsLabel; export type dxChartArgumentAxisTitle = DevExpress.viz.dxChartArgumentAxisTitle; export type dxChartCommonAxisSettings = DevExpress.viz.dxChartCommonAxisSettings; export type dxChartCommonAxisSettingsConstantLineStyle = DevExpress.viz.dxChartCommonAxisSettingsConstantLineStyle; export type dxChartCommonAxisSettingsConstantLineStyleLabel = DevExpress.viz.dxChartCommonAxisSettingsConstantLineStyleLabel; export type dxChartCommonAxisSettingsLabel = DevExpress.viz.dxChartCommonAxisSettingsLabel; export type dxChartCommonAxisSettingsStripStyle = DevExpress.viz.dxChartCommonAxisSettingsStripStyle; export type dxChartCommonAxisSettingsStripStyleLabel = DevExpress.viz.dxChartCommonAxisSettingsStripStyleLabel; export type dxChartCommonAxisSettingsTitle = DevExpress.viz.dxChartCommonAxisSettingsTitle; export type dxChartCommonPaneSettings = DevExpress.viz.dxChartCommonPaneSettings; export type dxChartCommonSeriesSettings = DevExpress.viz.dxChartCommonSeriesSettings; export type dxChartLegend = DevExpress.viz.dxChartLegend; export type dxChartPanes = DevExpress.viz.dxChartPanes; export type dxChartSeries = DevExpress.viz.dxChartSeries; export type dxChartTooltip = DevExpress.viz.dxChartTooltip; export type dxChartValueAxis = DevExpress.viz.dxChartValueAxis; export type dxChartValueAxisConstantLines = DevExpress.viz.dxChartValueAxisConstantLines; export type dxChartValueAxisConstantLinesLabel = DevExpress.viz.dxChartValueAxisConstantLinesLabel; export type dxChartValueAxisConstantLineStyle = DevExpress.viz.dxChartValueAxisConstantLineStyle; export type dxChartValueAxisConstantLineStyleLabel = DevExpress.viz.dxChartValueAxisConstantLineStyleLabel; export type dxChartValueAxisLabel = DevExpress.viz.dxChartValueAxisLabel; export type dxChartValueAxisStrips = DevExpress.viz.dxChartValueAxisStrips; export type dxChartValueAxisStripsLabel = DevExpress.viz.dxChartValueAxisStripsLabel; export type dxChartValueAxisTitle = DevExpress.viz.dxChartValueAxisTitle; export type dxPieChartOptions = DevExpress.viz.dxPieChartOptions; export type dxPieChartAdaptiveLayout = DevExpress.viz.dxPieChartAdaptiveLayout; export type dxPieChartLegend = DevExpress.viz.dxPieChartLegend; export type dxPieChartSeries = DevExpress.viz.dxPieChartSeries; export type dxPolarChartOptions = DevExpress.viz.dxPolarChartOptions; export type dxPolarChartAdaptiveLayout = DevExpress.viz.dxPolarChartAdaptiveLayout; export type dxPolarChartArgumentAxis = DevExpress.viz.dxPolarChartArgumentAxis; export type dxPolarChartArgumentAxisConstantLines = DevExpress.viz.dxPolarChartArgumentAxisConstantLines; export type dxPolarChartArgumentAxisConstantLinesLabel = DevExpress.viz.dxPolarChartArgumentAxisConstantLinesLabel; export type dxPolarChartArgumentAxisLabel = DevExpress.viz.dxPolarChartArgumentAxisLabel; export type dxPolarChartArgumentAxisStrips = DevExpress.viz.dxPolarChartArgumentAxisStrips; export type dxPolarChartArgumentAxisStripsLabel = DevExpress.viz.dxPolarChartArgumentAxisStripsLabel; export type dxPolarChartCommonAxisSettings = DevExpress.viz.dxPolarChartCommonAxisSettings; export type dxPolarChartCommonAxisSettingsConstantLineStyle = DevExpress.viz.dxPolarChartCommonAxisSettingsConstantLineStyle; export type dxPolarChartCommonAxisSettingsConstantLineStyleLabel = DevExpress.viz.dxPolarChartCommonAxisSettingsConstantLineStyleLabel; export type dxPolarChartCommonAxisSettingsLabel = DevExpress.viz.dxPolarChartCommonAxisSettingsLabel; export type dxPolarChartCommonAxisSettingsStripStyle = DevExpress.viz.dxPolarChartCommonAxisSettingsStripStyle; export type dxPolarChartCommonAxisSettingsStripStyleLabel = DevExpress.viz.dxPolarChartCommonAxisSettingsStripStyleLabel; export type dxPolarChartCommonAxisSettingsTick = DevExpress.viz.dxPolarChartCommonAxisSettingsTick; export type dxPolarChartCommonSeriesSettings = DevExpress.viz.dxPolarChartCommonSeriesSettings; export type dxPolarChartLegend = DevExpress.viz.dxPolarChartLegend; export type dxPolarChartSeries = DevExpress.viz.dxPolarChartSeries; export type dxPolarChartTooltip = DevExpress.viz.dxPolarChartTooltip; export type dxPolarChartValueAxis = DevExpress.viz.dxPolarChartValueAxis; export type dxPolarChartValueAxisConstantLines = DevExpress.viz.dxPolarChartValueAxisConstantLines; export type dxPolarChartValueAxisConstantLinesLabel = DevExpress.viz.dxPolarChartValueAxisConstantLinesLabel; export type dxPolarChartValueAxisLabel = DevExpress.viz.dxPolarChartValueAxisLabel; export type dxPolarChartValueAxisStrips = DevExpress.viz.dxPolarChartValueAxisStrips; export type dxPolarChartValueAxisStripsLabel = DevExpress.viz.dxPolarChartValueAxisStripsLabel; export type dxPolarChartValueAxisTick = DevExpress.viz.dxPolarChartValueAxisTick; } /** @deprecated Use DevExpress.viz instead */ export module funnel { export type dxFunnelOptions = DevExpress.viz.dxFunnelOptions; export type dxFunnelTooltip = DevExpress.viz.dxFunnelTooltip; } /** @deprecated Use DevExpress.viz instead */ export module gauges { export type dxCircularGaugeOptions = DevExpress.viz.dxCircularGaugeOptions; export type dxCircularGaugeRangeContainer = DevExpress.viz.dxCircularGaugeRangeContainer; export type dxCircularGaugeScale = DevExpress.viz.dxCircularGaugeScale; export type dxCircularGaugeScaleLabel = DevExpress.viz.dxCircularGaugeScaleLabel; export type dxLinearGaugeOptions = DevExpress.viz.dxLinearGaugeOptions; export type dxLinearGaugeRangeContainer = DevExpress.viz.dxLinearGaugeRangeContainer; export type dxLinearGaugeScale = DevExpress.viz.dxLinearGaugeScale; export type dxLinearGaugeScaleLabel = DevExpress.viz.dxLinearGaugeScaleLabel; export type dxBarGaugeOptions = DevExpress.viz.dxBarGaugeOptions; export type dxBarGaugeTooltip = DevExpress.viz.dxBarGaugeTooltip; } /** @deprecated Use DevExpress.viz instead */ export module rangeSelector { export type dxRangeSelectorOptions = DevExpress.viz.dxRangeSelectorOptions; } /** @deprecated Use DevExpress.viz instead */ export module sparklines { export type dxSparklineOptions = DevExpress.viz.dxSparklineOptions; export type dxBulletOptions = DevExpress.viz.dxBulletOptions; } /** @deprecated Use DevExpress.viz instead */ export module map { export type dxVectorMapOptions = DevExpress.viz.dxVectorMapOptions; export type dxVectorMapTooltip = DevExpress.viz.dxVectorMapTooltip; } /** @deprecated Use DevExpress.viz instead */ export module treeMap { export type dxTreeMapOptions = DevExpress.viz.dxTreeMapOptions; export type dxTreeMapTooltip = DevExpress.viz.dxTreeMapTooltip; } } declare module DevExpress.ui { /** @deprecated Use DevExpress.ui.dxAccordionItem */ export type dxAccordionItemTemplate = DevExpress.ui.dxAccordionItem; /** @deprecated Use DevExpress.ui.dxActionSheetItem */ export type dxActionSheetItemTemplate = DevExpress.ui.dxActionSheetItem; /** @deprecated Use DevExpress.ui.dxBoxItem */ export type dxBoxItemTemplate = DevExpress.ui.dxBoxItem; /** @deprecated Use DevExpress.ui.dxGalleryItem */ export type dxGalleryItemTemplate = DevExpress.ui.dxGalleryItem; /** @deprecated Use DevExpress.ui.dxMultiViewItem */ export type dxMultiViewItemTemplate = DevExpress.ui.dxMultiViewItem; /** @deprecated Use DevExpress.ui.dxNavBarItem */ export type dxNavBarItemTemplate = DevExpress.ui.dxNavBarItem; /** @deprecated Use DevExpress.ui.dxResponsiveBoxItem */ export type dxResponsiveBoxItemTemplate = DevExpress.ui.dxResponsiveBoxItem; /** @deprecated Use DevExpress.ui.dxSchedulerAppointment */ export type dxSchedulerAppointmentTemplate = DevExpress.ui.dxSchedulerAppointment; /** @deprecated Use DevExpress.ui.dxSlideOutItem */ export type dxSlideOutItemTemplate = DevExpress.ui.dxSlideOutItem; /** @deprecated Use DevExpress.ui.dxTabsItem */ export type dxTabsItemTemplate = DevExpress.ui.dxTabsItem; /** @deprecated Use DevExpress.ui.dxTabPanelItem */ export type dxTabPanelItemTemplate = DevExpress.ui.dxTabPanelItem; /** @deprecated Use DevExpress.ui.dxTileViewItem */ export type dxTileViewItemTemplate = DevExpress.ui.dxTileViewItem; /** @deprecated Use DevExpress.ui.dxToolbarItem */ export type dxToolbarItemTemplate = DevExpress.ui.dxToolbarItem; /** @deprecated Use DevExpress.ui.CollectionWidgetItem */ export type CollectionWidgetItemTemplate = DevExpress.ui.CollectionWidgetItem; /** @deprecated Use DevExpress.ui.dxContextMenuItem */ export type dxContextMenuItemTemplate = DevExpress.ui.dxContextMenuItem; /** @deprecated Use DevExpress.ui.dxMenuBaseItem */ export type dxMenuBaseItemTemplate = DevExpress.ui.dxMenuBaseItem; /** @deprecated Use DevExpress.ui.CollectionWidgetItem */ export type DataExpressionMixinItemTemplate = DevExpress.ui.CollectionWidgetItem; /** @deprecated Use DevExpress.ui.dxListItem */ export type dxListItemTemplate = DevExpress.ui.dxListItem; /** @deprecated Use DevExpress.ui.dxMenuItem */ export type dxMenuItemTemplate = DevExpress.ui.dxMenuItem; /** @deprecated Use DevExpress.ui.dxTreeViewItem */ export type dxTreeViewItemTemplate = DevExpress.ui.dxTreeViewItem; }
the_stack
* Hyperledger Cactus Plugin - Odap Hermes * Implementation for Odap and Hermes * * The version of the OpenAPI document: 0.0.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Configuration } from './configuration'; import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; /** * * @export * @interface AssetProfile */ export interface AssetProfile { /** * * @type {string} * @memberof AssetProfile */ issuer?: string; /** * * @type {string} * @memberof AssetProfile */ assetCode?: string; /** * * @type {string} * @memberof AssetProfile */ assetCodeType?: string; /** * * @type {string} * @memberof AssetProfile */ issuanceDate?: string; /** * * @type {string} * @memberof AssetProfile */ expirationDate: string; /** * * @type {string} * @memberof AssetProfile */ verificationEndPoint?: string; /** * * @type {string} * @memberof AssetProfile */ digitalSignature?: string; /** * * @type {string} * @memberof AssetProfile */ prospectusLink?: string; /** * * @type {Array<any>} * @memberof AssetProfile */ keyInformationLink?: Array<any>; /** * * @type {Array<any>} * @memberof AssetProfile */ keyWord?: Array<any>; /** * * @type {Array<any>} * @memberof AssetProfile */ transferRestriction?: Array<any>; /** * * @type {Array<any>} * @memberof AssetProfile */ ledgerRequirements?: Array<any>; } /** * * @export * @interface ClientV1Request */ export interface ClientV1Request { /** * * @type {string} * @memberof ClientV1Request */ version: string; /** * * @type {string} * @memberof ClientV1Request */ loggingProfile: string; /** * * @type {string} * @memberof ClientV1Request */ accessControlProfile: string; /** * * @type {string} * @memberof ClientV1Request */ assetControlProfile: string; /** * * @type {string} * @memberof ClientV1Request */ applicationProfile: string; /** * * @type {AssetProfile} * @memberof ClientV1Request */ assetProfile: AssetProfile; /** * * @type {PayloadProfile} * @memberof ClientV1Request */ payloadProfile: PayloadProfile; /** * * @type {string} * @memberof ClientV1Request */ sourceGatewayDltSystem: string; /** * * @type {string} * @memberof ClientV1Request */ recipientGatewayDltSystem: string; /** * * @type {string} * @memberof ClientV1Request */ recipientGatewayPubkey: string; /** * * @type {string} * @memberof ClientV1Request */ originatorPubkey: string; /** * * @type {string} * @memberof ClientV1Request */ beneficiaryPubkey: string; /** * * @type {string} * @memberof ClientV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof ClientV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof ClientV1Request */ clientDltSystem: string; /** * * @type {string} * @memberof ClientV1Request */ serverDltSystem: string; /** * * @type {ClientV1RequestClientGatewayConfiguration} * @memberof ClientV1Request */ clientGatewayConfiguration: ClientV1RequestClientGatewayConfiguration; /** * * @type {ClientV1RequestClientGatewayConfiguration} * @memberof ClientV1Request */ serverGatewayConfiguration: ClientV1RequestClientGatewayConfiguration; /** * * @type {number} * @memberof ClientV1Request */ maxRetries: number; /** * * @type {number} * @memberof ClientV1Request */ maxTimeout: number; } /** * * @export * @interface ClientV1RequestClientGatewayConfiguration */ export interface ClientV1RequestClientGatewayConfiguration { /** * * @type {string} * @memberof ClientV1RequestClientGatewayConfiguration */ apiHost: string; } /** * * @export * @interface CommitFinalV1Request */ export interface CommitFinalV1Request { /** * * @type {string} * @memberof CommitFinalV1Request */ sessionID: string; /** * * @type {string} * @memberof CommitFinalV1Request */ messageType: string; /** * * @type {string} * @memberof CommitFinalV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof CommitFinalV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitFinalV1Request */ commitFinalClaim: string; /** * * @type {object} * @memberof CommitFinalV1Request */ commitFinalClaimFormat?: object; /** * * @type {string} * @memberof CommitFinalV1Request */ hashCommitPrepareAck: string; /** * * @type {number} * @memberof CommitFinalV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof CommitFinalV1Request */ signature: string; /** * * @type {number} * @memberof CommitFinalV1Request */ sequenceNumber: number; } /** * * @export * @interface CommitFinalV1Response */ export interface CommitFinalV1Response { /** * * @type {string} * @memberof CommitFinalV1Response */ sessionID: string; /** * * @type {string} * @memberof CommitFinalV1Response */ messageType: string; /** * * @type {string} * @memberof CommitFinalV1Response */ clientIdentityPubkey?: string; /** * * @type {string} * @memberof CommitFinalV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitFinalV1Response */ commitAcknowledgementClaim: string; /** * * @type {object} * @memberof CommitFinalV1Response */ commitAcknowledgementClaimFormat?: object; /** * * @type {string} * @memberof CommitFinalV1Response */ hashCommitFinal: string; /** * * @type {number} * @memberof CommitFinalV1Response */ serverTransferNumber?: number; /** * * @type {string} * @memberof CommitFinalV1Response */ signature: string; /** * * @type {number} * @memberof CommitFinalV1Response */ sequenceNumber: number; } /** * * @export * @interface CommitPreparationV1Request */ export interface CommitPreparationV1Request { /** * * @type {string} * @memberof CommitPreparationV1Request */ sessionID: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ messageType: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ hashLockEvidenceAck: string; /** * * @type {number} * @memberof CommitPreparationV1Request */ clientTransferNumber?: number; /** * * @type {string} * @memberof CommitPreparationV1Request */ signature: string; /** * * @type {number} * @memberof CommitPreparationV1Request */ sequenceNumber: number; } /** * * @export * @interface CommitPreparationV1Response */ export interface CommitPreparationV1Response { /** * * @type {string} * @memberof CommitPreparationV1Response */ sessionID: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ messageType: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ clientIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ hashCommitPrep: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ serverTransferNumber?: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ signature: string; /** * * @type {number} * @memberof CommitPreparationV1Response */ sequenceNumber: number; } /** * * @export * @enum {string} */ export enum CredentialProfile { Saml = 'SAML', Oauth = 'OAUTH', X509 = 'X509' } /** * * @export * @interface History */ export interface History { /** * * @type {Array<object>} * @memberof History */ Transactions?: Array<object>; /** * * @type {Array<object>} * @memberof History */ Actions?: Array<object>; /** * * @type {string} * @memberof History */ Origin?: string; /** * * @type {string} * @memberof History */ Destination?: string; /** * * @type {string} * @memberof History */ Balance?: string; /** * * @type {object} * @memberof History */ CurrentStatus?: object; /** * * @type {object} * @memberof History */ ApplicationSpecificParameters?: object; } /** * * @export * @interface LockEvidenceV1Request */ export interface LockEvidenceV1Request { /** * * @type {string} * @memberof LockEvidenceV1Request */ sessionID: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ lockEvidenceClaim: string; /** * * @type {object} * @memberof LockEvidenceV1Request */ lockEvidenceFormat?: object; /** * * @type {string} * @memberof LockEvidenceV1Request */ lockEvidenceExpiration: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ hashCommenceAckRequest: string; /** * * @type {number} * @memberof LockEvidenceV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof LockEvidenceV1Request */ signature: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ messageType: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ messageHash?: string; /** * * @type {number} * @memberof LockEvidenceV1Request */ sequenceNumber: number; } /** * * @export * @interface LockEvidenceV1Response */ export interface LockEvidenceV1Response { /** * * @type {string} * @memberof LockEvidenceV1Response */ sessionID: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ clientIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ hashLockEvidenceRequest: string; /** * * @type {number} * @memberof LockEvidenceV1Response */ serverTransferNumber?: number | null; /** * * @type {string} * @memberof LockEvidenceV1Response */ signature: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ messageType: string; /** * * @type {number} * @memberof LockEvidenceV1Response */ sequenceNumber: number; } /** * * @export * @interface OdapLocalLog */ export interface OdapLocalLog { /** * * @type {string} * @memberof OdapLocalLog */ key?: string; /** * * @type {string} * @memberof OdapLocalLog */ sessionID: string; /** * * @type {string} * @memberof OdapLocalLog */ data?: string; /** * * @type {string} * @memberof OdapLocalLog */ type: string; /** * * @type {string} * @memberof OdapLocalLog */ operation: string; /** * * @type {string} * @memberof OdapLocalLog */ timestamp?: string; } /** * * @export * @interface OdapMessage */ export interface OdapMessage { /** * * @type {number} * @memberof OdapMessage */ SequenceNumber?: number; /** * * @type {string} * @memberof OdapMessage */ Phase?: OdapMessagePhaseEnum; /** * * @type {string} * @memberof OdapMessage */ ResourceURL?: string; /** * * @type {string} * @memberof OdapMessage */ DeveloperURN?: string; /** * * @type {OdapMessageActionResponse} * @memberof OdapMessage */ ActionResponse?: OdapMessageActionResponse; /** * * @type {string} * @memberof OdapMessage */ CredentialProfile?: OdapMessageCredentialProfileEnum; /** * * @type {Array<any>} * @memberof OdapMessage */ CredentialBlock?: Array<any>; /** * * @type {PayloadProfile} * @memberof OdapMessage */ CredentialsProfile?: PayloadProfile; /** * * @type {object} * @memberof OdapMessage */ ApplicationProfile?: object; /** * * @type {object} * @memberof OdapMessage */ Payload?: object; /** * * @type {string} * @memberof OdapMessage */ PayloadHash?: string; /** * * @type {string} * @memberof OdapMessage */ MessageSignature?: string; } /** * @export * @enum {string} */ export enum OdapMessagePhaseEnum { TransferInitialization = 'TransferInitialization', LockEvidenceVerification = 'LockEvidenceVerification', CommitmentEstablishment = 'CommitmentEstablishment' } /** * @export * @enum {string} */ export enum OdapMessageCredentialProfileEnum { Saml = 'SAML', OAuth = 'OAuth', X509 = 'X509' } /** * * @export * @interface OdapMessageActionResponse */ export interface OdapMessageActionResponse { /** * * @type {string} * @memberof OdapMessageActionResponse */ ResponseCode?: OdapMessageActionResponseResponseCodeEnum; /** * * @type {Array<any>} * @memberof OdapMessageActionResponse */ Arguments?: Array<any>; } /** * @export * @enum {string} */ export enum OdapMessageActionResponseResponseCodeEnum { OK = '200', RESOURCE_NOT_FOUND = '404' } /** * * @export * @interface PayloadProfile */ export interface PayloadProfile { /** * * @type {AssetProfile} * @memberof PayloadProfile */ assetProfile: AssetProfile; /** * * @type {string} * @memberof PayloadProfile */ capabilities?: string; } /** * * @export * @interface RecoverSuccessV1Message */ export interface RecoverSuccessV1Message { /** * * @type {string} * @memberof RecoverSuccessV1Message */ sessionID: string; /** * * @type {boolean} * @memberof RecoverSuccessV1Message */ success: boolean; /** * * @type {string} * @memberof RecoverSuccessV1Message */ signature: string; } /** * * @export * @interface RecoverUpdateAckV1Message */ export interface RecoverUpdateAckV1Message { /** * * @type {string} * @memberof RecoverUpdateAckV1Message */ sessionID: string; /** * * @type {boolean} * @memberof RecoverUpdateAckV1Message */ success: boolean; /** * * @type {Array<string>} * @memberof RecoverUpdateAckV1Message */ changedEntriesHash: Array<string>; /** * * @type {string} * @memberof RecoverUpdateAckV1Message */ signature: string; } /** * * @export * @interface RecoverUpdateV1Message */ export interface RecoverUpdateV1Message { /** * * @type {string} * @memberof RecoverUpdateV1Message */ sessionID: string; /** * * @type {Array<OdapLocalLog>} * @memberof RecoverUpdateV1Message */ recoveredLogs: Array<OdapLocalLog>; /** * * @type {string} * @memberof RecoverUpdateV1Message */ signature: string; } /** * * @export * @interface RecoverV1Message */ export interface RecoverV1Message { /** * * @type {string} * @memberof RecoverV1Message */ sessionID: string; /** * * @type {string} * @memberof RecoverV1Message */ odapPhase: string; /** * * @type {number} * @memberof RecoverV1Message */ sequenceNumber: number; /** * * @type {string} * @memberof RecoverV1Message */ lastLogEntryTimestamp?: string; /** * * @type {boolean} * @memberof RecoverV1Message */ isBackup: boolean; /** * * @type {string} * @memberof RecoverV1Message */ newBasePath: string; /** * * @type {string} * @memberof RecoverV1Message */ newGatewayPubKey?: string; /** * * @type {string} * @memberof RecoverV1Message */ signature: string; } /** * * @export * @interface RollbackAckV1Message */ export interface RollbackAckV1Message { /** * * @type {string} * @memberof RollbackAckV1Message */ sessionID: string; /** * * @type {boolean} * @memberof RollbackAckV1Message */ success: boolean; /** * * @type {string} * @memberof RollbackAckV1Message */ signature: string; } /** * * @export * @interface RollbackV1Message */ export interface RollbackV1Message { /** * * @type {string} * @memberof RollbackV1Message */ sessionID: string; /** * * @type {boolean} * @memberof RollbackV1Message */ success: boolean; /** * * @type {Array<string>} * @memberof RollbackV1Message */ actionPerformed: Array<string>; /** * * @type {Array<string>} * @memberof RollbackV1Message */ proofs: Array<string>; /** * * @type {string} * @memberof RollbackV1Message */ signature: string; } /** * * @export * @interface SessionData */ export interface SessionData { /** * * @type {string} * @memberof SessionData */ id?: string; /** * * @type {number} * @memberof SessionData */ step?: number; /** * * @type {string} * @memberof SessionData */ version?: string; /** * * @type {number} * @memberof SessionData */ lastSequenceNumber?: number; /** * * @type {string} * @memberof SessionData */ loggingProfile?: string; /** * * @type {string} * @memberof SessionData */ accessControlProfile?: string; /** * * @type {string} * @memberof SessionData */ applicationProfile?: string; /** * * @type {PayloadProfile} * @memberof SessionData */ payloadProfile?: PayloadProfile; /** * * @type {AssetProfile} * @memberof SessionData */ assetProfile?: AssetProfile; /** * * @type {Array<string>} * @memberof SessionData */ allowedSourceBackupGateways?: Array<string>; /** * * @type {Array<string>} * @memberof SessionData */ allowedRecipientBackupGateways?: Array<string>; /** * * @type {string} * @memberof SessionData */ sourceBasePath?: string; /** * * @type {string} * @memberof SessionData */ recipientBasePath?: string; /** * * @type {string} * @memberof SessionData */ originatorPubkey?: string; /** * * @type {string} * @memberof SessionData */ beneficiaryPubkey?: string; /** * * @type {string} * @memberof SessionData */ sourceGatewayPubkey?: string; /** * * @type {string} * @memberof SessionData */ sourceGatewayDltSystem?: string; /** * * @type {string} * @memberof SessionData */ recipientGatewayPubkey?: string; /** * * @type {string} * @memberof SessionData */ recipientGatewayDltSystem?: string; /** * * @type {string} * @memberof SessionData */ initializationRequestMessageHash?: string; /** * * @type {string} * @memberof SessionData */ initializationResponseMessageHash?: string; /** * * @type {string} * @memberof SessionData */ initializationRequestMessageRcvTimeStamp?: string; /** * * @type {string} * @memberof SessionData */ initializationRequestMessageProcessedTimeStamp?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureInitializationRequestMessage?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureInitializationResponseMessage?: string; /** * * @type {string} * @memberof SessionData */ transferCommenceMessageRequestHash?: string; /** * * @type {string} * @memberof SessionData */ transferCommenceMessageResponseHash?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureTransferCommenceRequestMessage?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureTransferCommenceResponseMessage?: string; /** * * @type {string} * @memberof SessionData */ lockEvidenceRequestMessageHash?: string; /** * * @type {string} * @memberof SessionData */ lockEvidenceResponseMessageHash?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureLockEvidenceRequestMessage?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureLockEvidenceResponseMessage?: string; /** * * @type {string} * @memberof SessionData */ lockEvidenceClaim?: string; /** * * @type {string} * @memberof SessionData */ commitPrepareRequestMessageHash?: string; /** * * @type {string} * @memberof SessionData */ commitPrepareResponseMessageHash?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureCommitPreparationRequestMessage?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureCommitPreparationResponseMessage?: string; /** * * @type {string} * @memberof SessionData */ commitFinalRequestMessageHash?: string; /** * * @type {string} * @memberof SessionData */ commitFinalResponseMessageHash?: string; /** * * @type {string} * @memberof SessionData */ commitFinalClaim?: string; /** * * @type {string} * @memberof SessionData */ commitFinalClaimFormat?: string; /** * * @type {string} * @memberof SessionData */ commitAcknowledgementClaim?: string; /** * * @type {string} * @memberof SessionData */ commitAcknowledgementClaimFormat?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureCommitFinalRequestMessage?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureCommitFinalResponseMessage?: string; /** * * @type {string} * @memberof SessionData */ transferCompleteMessageHash?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureTransferCompleteMessage?: string; /** * * @type {number} * @memberof SessionData */ maxRetries?: number; /** * * @type {string} * @memberof SessionData */ besuAssetID?: string; /** * * @type {string} * @memberof SessionData */ fabricAssetID?: string; /** * * @type {string} * @memberof SessionData */ fabricAssetSize?: string; /** * * @type {number} * @memberof SessionData */ maxTimeout?: number; /** * * @type {string} * @memberof SessionData */ lastLogEntryTimestamp?: string; /** * * @type {string} * @memberof SessionData */ unlockAssetClaim?: string; /** * * @type {string} * @memberof SessionData */ recreateAssetClaim?: string; /** * * @type {string} * @memberof SessionData */ deleteAssetClaim?: string; /** * * @type {string} * @memberof SessionData */ lastMessageReceivedTimestamp?: string; /** * * @type {boolean} * @memberof SessionData */ rollback?: boolean; /** * * @type {string} * @memberof SessionData */ rollbackMessageHash?: string; /** * * @type {Array<string>} * @memberof SessionData */ rollbackProofs?: Array<string>; /** * * @type {Array<string>} * @memberof SessionData */ rollbackActionsPerformed?: Array<SessionDataRollbackActionsPerformedEnum>; } /** * @export * @enum {string} */ export enum SessionDataRollbackActionsPerformedEnum { Create = 'CREATE', Delete = 'DELETE', Lock = 'LOCK', Unlock = 'UNLOCK' } /** * * @export * @interface TransferCommenceV1Request */ export interface TransferCommenceV1Request { /** * * @type {string} * @memberof TransferCommenceV1Request */ sessionID: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ messageType: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ originatorPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ beneficiaryPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ senderDltSystem: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ recipientDltSystem: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ hashAssetProfile: string; /** * * @type {number} * @memberof TransferCommenceV1Request */ assetUnit?: number; /** * * @type {string} * @memberof TransferCommenceV1Request */ hashPrevMessage: string; /** * * @type {number} * @memberof TransferCommenceV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof TransferCommenceV1Request */ signature: string; /** * * @type {number} * @memberof TransferCommenceV1Request */ sequenceNumber: number; } /** * * @export * @interface TransferCommenceV1Response */ export interface TransferCommenceV1Response { /** * * @type {string} * @memberof TransferCommenceV1Response */ sessionID: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ clientIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ hashCommenceRequest: string; /** * * @type {number} * @memberof TransferCommenceV1Response */ serverTransferNumber?: number | null; /** * * @type {string} * @memberof TransferCommenceV1Response */ signature: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ messageType: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ messageHash?: string; /** * * @type {number} * @memberof TransferCommenceV1Response */ sequenceNumber: number; } /** * * @export * @interface TransferCompleteV1Request */ export interface TransferCompleteV1Request { /** * * @type {string} * @memberof TransferCompleteV1Request */ sessionID: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ messageType: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ hashCommitFinalAck: string; /** * * @type {number} * @memberof TransferCompleteV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof TransferCompleteV1Request */ signature: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ hashTransferCommence: string; /** * * @type {number} * @memberof TransferCompleteV1Request */ sequenceNumber: number; } /** * * @export * @interface TransferInitializationV1Request */ export interface TransferInitializationV1Request { /** * * @type {string} * @memberof TransferInitializationV1Request */ messageType: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ sessionID: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ version?: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ developerURN?: string; /** * * @type {CredentialProfile} * @memberof TransferInitializationV1Request */ credentialProfile?: CredentialProfile; /** * * @type {PayloadProfile} * @memberof TransferInitializationV1Request */ payloadProfile: PayloadProfile; /** * * @type {string} * @memberof TransferInitializationV1Request */ applicationProfile: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ loggingProfile: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ accessControlProfile: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ signature: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ sourceGatewayPubkey: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ sourceGatewayDltSystem: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ recipientGatewayPubkey: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ recipientGatewayDltSystem: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ escrowType?: TransferInitializationV1RequestEscrowTypeEnum; /** * * @type {string} * @memberof TransferInitializationV1Request */ expiryTime?: string; /** * * @type {boolean} * @memberof TransferInitializationV1Request */ multipleClaimsAllowed?: boolean; /** * * @type {boolean} * @memberof TransferInitializationV1Request */ multipleCancelsAllowed?: boolean; /** * * @type {object} * @memberof TransferInitializationV1Request */ permissions?: object; /** * * @type {string} * @memberof TransferInitializationV1Request */ origin?: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ destination?: string; /** * * @type {object} * @memberof TransferInitializationV1Request */ subsequentCalls?: object; /** * * @type {Array<History>} * @memberof TransferInitializationV1Request */ histories?: Array<History>; /** * * @type {number} * @memberof TransferInitializationV1Request */ sequenceNumber: number; /** * * @type {string} * @memberof TransferInitializationV1Request */ sourceGatewayPath?: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ recipientBasePath: string; /** * * @type {number} * @memberof TransferInitializationV1Request */ maxRetries: number; /** * * @type {number} * @memberof TransferInitializationV1Request */ maxTimeout: number; /** * * @type {Array<string>} * @memberof TransferInitializationV1Request */ backupGatewaysAllowed: Array<string>; } /** * @export * @enum {string} */ export enum TransferInitializationV1RequestEscrowTypeEnum { Faucet = 'FAUCET', Timelock = 'TIMELOCK', Hashlock = 'HASHLOCK', Hashtimelock = 'HASHTIMELOCK', Multiclaimpc = 'MULTICLAIMPC', Destroy = 'DESTROY', Burn = 'BURN' } /** * * @export * @interface TransferInitializationV1Response */ export interface TransferInitializationV1Response { /** * * @type {string} * @memberof TransferInitializationV1Response */ messageType: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ sessionID: string; /** * * @type {number} * @memberof TransferInitializationV1Response */ sequenceNumber: number; /** * * @type {string} * @memberof TransferInitializationV1Response */ odapPhase?: TransferInitializationV1ResponseOdapPhaseEnum; /** * * @type {string} * @memberof TransferInitializationV1Response */ initialRequestMessageHash: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ destination?: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ timeStamp: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ processedTimeStamp: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ signature: string; /** * * @type {Array<string>} * @memberof TransferInitializationV1Response */ backupGatewaysAllowed: Array<string>; } /** * @export * @enum {string} */ export enum TransferInitializationV1ResponseOdapPhaseEnum { TransferInitialization = 'TransferInitialization', LockEvidenceVerification = 'LockEvidenceVerification', CommitmentEstablishment = 'CommitmentEstablishment' } /** * DefaultApi - axios parameter creator * @export */ export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * * @param {ClientV1Request} [clientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ clientRequestV1: async (clientV1Request?: ClientV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/clientrequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(clientV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase1TransferInitiationRequestV1: async (transferInitializationV1Request?: TransferInitializationV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase1/transferinitiationrequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferInitializationV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferInitializationV1Response} [transferInitializationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase1TransferInitiationResponseV1: async (transferInitializationV1Response?: TransferInitializationV1Response, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase1/transferinitiationresponse`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferInitializationV1Response, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2LockEvidenceRequestV1: async (lockEvidenceV1Request?: LockEvidenceV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase2/lockevidencerequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(lockEvidenceV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {LockEvidenceV1Response} [lockEvidenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2LockEvidenceResponseV1: async (lockEvidenceV1Response?: LockEvidenceV1Response, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase2/lockevidenceresponse`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(lockEvidenceV1Response, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2TransferCommenceRequestV1: async (transferCommenceV1Request?: TransferCommenceV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase2/transfercommencerequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferCommenceV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferCommenceV1Response} [transferCommenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2TransferCommenceResponseV1: async (transferCommenceV1Response?: TransferCommenceV1Response, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase2/transfercommenceresponse`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferCommenceV1Response, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitFinalRequestV1: async (commitFinalV1Request?: CommitFinalV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase3/commitfinalrequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(commitFinalV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {CommitFinalV1Response} [commitFinalV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitFinalResponseV1: async (commitFinalV1Response?: CommitFinalV1Response, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase3/commitfinalresponse`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(commitFinalV1Response, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitPreparationRequestV1: async (commitPreparationV1Request?: CommitPreparationV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase3/commitpreparationrequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(commitPreparationV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {CommitPreparationV1Response} [commitPreparationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitPreparationResponseV1: async (commitPreparationV1Response?: CommitPreparationV1Response, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase3/commitpreparationresponse`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(commitPreparationV1Response, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3TransferCompleteRequestV1: async (transferCompleteV1Request?: TransferCompleteV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/phase3/transfercompleterequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferCompleteV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {RecoverUpdateAckV1Message} [recoverUpdateAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverUpdateAckV1Message: async (recoverUpdateAckV1Message?: RecoverUpdateAckV1Message, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/recoverupdateackmessage`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(recoverUpdateAckV1Message, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {RecoverUpdateV1Message} [recoverUpdateV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverUpdateV1Message: async (recoverUpdateV1Message?: RecoverUpdateV1Message, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/recoverupdatemessage`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(recoverUpdateV1Message, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {RecoverV1Message} [recoverV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverV1Message: async (recoverV1Message?: RecoverV1Message, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/recovermessage`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(recoverV1Message, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {RecoverSuccessV1Message} [recoverSuccessV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverV1Success: async (recoverSuccessV1Message?: RecoverSuccessV1Message, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/recoversuccessmessage`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(recoverSuccessV1Message, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {RollbackAckV1Message} [rollbackAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ rollbackAckV1Message: async (rollbackAckV1Message?: RollbackAckV1Message, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/rollbackackmessage`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(rollbackAckV1Message, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {RollbackV1Message} [rollbackV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ rollbackV1Message: async (rollbackV1Message?: RollbackV1Message, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hermes/rollbackmessage`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(rollbackV1Message, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * DefaultApi - functional programming interface * @export */ export const DefaultApiFp = function(configuration?: Configuration) { const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration) return { /** * * @param {ClientV1Request} [clientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async clientRequestV1(clientV1Request?: ClientV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> { const localVarAxiosArgs = await localVarAxiosParamCreator.clientRequestV1(clientV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase1TransferInitiationRequestV1(transferInitializationV1Request?: TransferInitializationV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase1TransferInitiationRequestV1(transferInitializationV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferInitializationV1Response} [transferInitializationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase1TransferInitiationResponseV1(transferInitializationV1Response?: TransferInitializationV1Response, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase1TransferInitiationResponseV1(transferInitializationV1Response, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase2LockEvidenceRequestV1(lockEvidenceV1Request?: LockEvidenceV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase2LockEvidenceRequestV1(lockEvidenceV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {LockEvidenceV1Response} [lockEvidenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase2LockEvidenceResponseV1(lockEvidenceV1Response?: LockEvidenceV1Response, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase2LockEvidenceResponseV1(lockEvidenceV1Response, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase2TransferCommenceRequestV1(transferCommenceV1Request?: TransferCommenceV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase2TransferCommenceRequestV1(transferCommenceV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferCommenceV1Response} [transferCommenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase2TransferCommenceResponseV1(transferCommenceV1Response?: TransferCommenceV1Response, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase2TransferCommenceResponseV1(transferCommenceV1Response, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3CommitFinalRequestV1(commitFinalV1Request?: CommitFinalV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3CommitFinalRequestV1(commitFinalV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {CommitFinalV1Response} [commitFinalV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3CommitFinalResponseV1(commitFinalV1Response?: CommitFinalV1Response, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3CommitFinalResponseV1(commitFinalV1Response, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3CommitPreparationRequestV1(commitPreparationV1Request?: CommitPreparationV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3CommitPreparationRequestV1(commitPreparationV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {CommitPreparationV1Response} [commitPreparationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3CommitPreparationResponseV1(commitPreparationV1Response?: CommitPreparationV1Response, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3CommitPreparationResponseV1(commitPreparationV1Response, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3TransferCompleteRequestV1(transferCompleteV1Request?: TransferCompleteV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3TransferCompleteRequestV1(transferCompleteV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {RecoverUpdateAckV1Message} [recoverUpdateAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async recoverUpdateAckV1Message(recoverUpdateAckV1Message?: RecoverUpdateAckV1Message, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.recoverUpdateAckV1Message(recoverUpdateAckV1Message, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {RecoverUpdateV1Message} [recoverUpdateV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async recoverUpdateV1Message(recoverUpdateV1Message?: RecoverUpdateV1Message, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.recoverUpdateV1Message(recoverUpdateV1Message, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {RecoverV1Message} [recoverV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async recoverV1Message(recoverV1Message?: RecoverV1Message, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.recoverV1Message(recoverV1Message, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {RecoverSuccessV1Message} [recoverSuccessV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async recoverV1Success(recoverSuccessV1Message?: RecoverSuccessV1Message, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.recoverV1Success(recoverSuccessV1Message, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {RollbackAckV1Message} [rollbackAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async rollbackAckV1Message(rollbackAckV1Message?: RollbackAckV1Message, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.rollbackAckV1Message(rollbackAckV1Message, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {RollbackV1Message} [rollbackV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async rollbackV1Message(rollbackV1Message?: RollbackV1Message, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.rollbackV1Message(rollbackV1Message, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, } }; /** * DefaultApi - factory interface * @export */ export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { const localVarFp = DefaultApiFp(configuration) return { /** * * @param {ClientV1Request} [clientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ clientRequestV1(clientV1Request?: ClientV1Request, options?: any): AxiosPromise<any> { return localVarFp.clientRequestV1(clientV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase1TransferInitiationRequestV1(transferInitializationV1Request?: TransferInitializationV1Request, options?: any): AxiosPromise<void> { return localVarFp.phase1TransferInitiationRequestV1(transferInitializationV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferInitializationV1Response} [transferInitializationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase1TransferInitiationResponseV1(transferInitializationV1Response?: TransferInitializationV1Response, options?: any): AxiosPromise<void> { return localVarFp.phase1TransferInitiationResponseV1(transferInitializationV1Response, options).then((request) => request(axios, basePath)); }, /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2LockEvidenceRequestV1(lockEvidenceV1Request?: LockEvidenceV1Request, options?: any): AxiosPromise<void> { return localVarFp.phase2LockEvidenceRequestV1(lockEvidenceV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {LockEvidenceV1Response} [lockEvidenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2LockEvidenceResponseV1(lockEvidenceV1Response?: LockEvidenceV1Response, options?: any): AxiosPromise<void> { return localVarFp.phase2LockEvidenceResponseV1(lockEvidenceV1Response, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2TransferCommenceRequestV1(transferCommenceV1Request?: TransferCommenceV1Request, options?: any): AxiosPromise<void> { return localVarFp.phase2TransferCommenceRequestV1(transferCommenceV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferCommenceV1Response} [transferCommenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2TransferCommenceResponseV1(transferCommenceV1Response?: TransferCommenceV1Response, options?: any): AxiosPromise<void> { return localVarFp.phase2TransferCommenceResponseV1(transferCommenceV1Response, options).then((request) => request(axios, basePath)); }, /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitFinalRequestV1(commitFinalV1Request?: CommitFinalV1Request, options?: any): AxiosPromise<void> { return localVarFp.phase3CommitFinalRequestV1(commitFinalV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {CommitFinalV1Response} [commitFinalV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitFinalResponseV1(commitFinalV1Response?: CommitFinalV1Response, options?: any): AxiosPromise<void> { return localVarFp.phase3CommitFinalResponseV1(commitFinalV1Response, options).then((request) => request(axios, basePath)); }, /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitPreparationRequestV1(commitPreparationV1Request?: CommitPreparationV1Request, options?: any): AxiosPromise<void> { return localVarFp.phase3CommitPreparationRequestV1(commitPreparationV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {CommitPreparationV1Response} [commitPreparationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitPreparationResponseV1(commitPreparationV1Response?: CommitPreparationV1Response, options?: any): AxiosPromise<void> { return localVarFp.phase3CommitPreparationResponseV1(commitPreparationV1Response, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3TransferCompleteRequestV1(transferCompleteV1Request?: TransferCompleteV1Request, options?: any): AxiosPromise<void> { return localVarFp.phase3TransferCompleteRequestV1(transferCompleteV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {RecoverUpdateAckV1Message} [recoverUpdateAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverUpdateAckV1Message(recoverUpdateAckV1Message?: RecoverUpdateAckV1Message, options?: any): AxiosPromise<void> { return localVarFp.recoverUpdateAckV1Message(recoverUpdateAckV1Message, options).then((request) => request(axios, basePath)); }, /** * * @param {RecoverUpdateV1Message} [recoverUpdateV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverUpdateV1Message(recoverUpdateV1Message?: RecoverUpdateV1Message, options?: any): AxiosPromise<void> { return localVarFp.recoverUpdateV1Message(recoverUpdateV1Message, options).then((request) => request(axios, basePath)); }, /** * * @param {RecoverV1Message} [recoverV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverV1Message(recoverV1Message?: RecoverV1Message, options?: any): AxiosPromise<void> { return localVarFp.recoverV1Message(recoverV1Message, options).then((request) => request(axios, basePath)); }, /** * * @param {RecoverSuccessV1Message} [recoverSuccessV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ recoverV1Success(recoverSuccessV1Message?: RecoverSuccessV1Message, options?: any): AxiosPromise<void> { return localVarFp.recoverV1Success(recoverSuccessV1Message, options).then((request) => request(axios, basePath)); }, /** * * @param {RollbackAckV1Message} [rollbackAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ rollbackAckV1Message(rollbackAckV1Message?: RollbackAckV1Message, options?: any): AxiosPromise<void> { return localVarFp.rollbackAckV1Message(rollbackAckV1Message, options).then((request) => request(axios, basePath)); }, /** * * @param {RollbackV1Message} [rollbackV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} */ rollbackV1Message(rollbackV1Message?: RollbackV1Message, options?: any): AxiosPromise<void> { return localVarFp.rollbackV1Message(rollbackV1Message, options).then((request) => request(axios, basePath)); }, }; }; /** * DefaultApi - object-oriented interface * @export * @class DefaultApi * @extends {BaseAPI} */ export class DefaultApi extends BaseAPI { /** * * @param {ClientV1Request} [clientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public clientRequestV1(clientV1Request?: ClientV1Request, options?: any) { return DefaultApiFp(this.configuration).clientRequestV1(clientV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase1TransferInitiationRequestV1(transferInitializationV1Request?: TransferInitializationV1Request, options?: any) { return DefaultApiFp(this.configuration).phase1TransferInitiationRequestV1(transferInitializationV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferInitializationV1Response} [transferInitializationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase1TransferInitiationResponseV1(transferInitializationV1Response?: TransferInitializationV1Response, options?: any) { return DefaultApiFp(this.configuration).phase1TransferInitiationResponseV1(transferInitializationV1Response, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase2LockEvidenceRequestV1(lockEvidenceV1Request?: LockEvidenceV1Request, options?: any) { return DefaultApiFp(this.configuration).phase2LockEvidenceRequestV1(lockEvidenceV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {LockEvidenceV1Response} [lockEvidenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase2LockEvidenceResponseV1(lockEvidenceV1Response?: LockEvidenceV1Response, options?: any) { return DefaultApiFp(this.configuration).phase2LockEvidenceResponseV1(lockEvidenceV1Response, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase2TransferCommenceRequestV1(transferCommenceV1Request?: TransferCommenceV1Request, options?: any) { return DefaultApiFp(this.configuration).phase2TransferCommenceRequestV1(transferCommenceV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferCommenceV1Response} [transferCommenceV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase2TransferCommenceResponseV1(transferCommenceV1Response?: TransferCommenceV1Response, options?: any) { return DefaultApiFp(this.configuration).phase2TransferCommenceResponseV1(transferCommenceV1Response, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3CommitFinalRequestV1(commitFinalV1Request?: CommitFinalV1Request, options?: any) { return DefaultApiFp(this.configuration).phase3CommitFinalRequestV1(commitFinalV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {CommitFinalV1Response} [commitFinalV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3CommitFinalResponseV1(commitFinalV1Response?: CommitFinalV1Response, options?: any) { return DefaultApiFp(this.configuration).phase3CommitFinalResponseV1(commitFinalV1Response, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3CommitPreparationRequestV1(commitPreparationV1Request?: CommitPreparationV1Request, options?: any) { return DefaultApiFp(this.configuration).phase3CommitPreparationRequestV1(commitPreparationV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {CommitPreparationV1Response} [commitPreparationV1Response] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3CommitPreparationResponseV1(commitPreparationV1Response?: CommitPreparationV1Response, options?: any) { return DefaultApiFp(this.configuration).phase3CommitPreparationResponseV1(commitPreparationV1Response, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3TransferCompleteRequestV1(transferCompleteV1Request?: TransferCompleteV1Request, options?: any) { return DefaultApiFp(this.configuration).phase3TransferCompleteRequestV1(transferCompleteV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {RecoverUpdateAckV1Message} [recoverUpdateAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public recoverUpdateAckV1Message(recoverUpdateAckV1Message?: RecoverUpdateAckV1Message, options?: any) { return DefaultApiFp(this.configuration).recoverUpdateAckV1Message(recoverUpdateAckV1Message, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {RecoverUpdateV1Message} [recoverUpdateV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public recoverUpdateV1Message(recoverUpdateV1Message?: RecoverUpdateV1Message, options?: any) { return DefaultApiFp(this.configuration).recoverUpdateV1Message(recoverUpdateV1Message, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {RecoverV1Message} [recoverV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public recoverV1Message(recoverV1Message?: RecoverV1Message, options?: any) { return DefaultApiFp(this.configuration).recoverV1Message(recoverV1Message, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {RecoverSuccessV1Message} [recoverSuccessV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public recoverV1Success(recoverSuccessV1Message?: RecoverSuccessV1Message, options?: any) { return DefaultApiFp(this.configuration).recoverV1Success(recoverSuccessV1Message, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {RollbackAckV1Message} [rollbackAckV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public rollbackAckV1Message(rollbackAckV1Message?: RollbackAckV1Message, options?: any) { return DefaultApiFp(this.configuration).rollbackAckV1Message(rollbackAckV1Message, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {RollbackV1Message} [rollbackV1Message] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public rollbackV1Message(rollbackV1Message?: RollbackV1Message, options?: any) { return DefaultApiFp(this.configuration).rollbackV1Message(rollbackV1Message, options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import { JSONSchema4 } from 'json-schema'; const upperFirst = (x: string) => x.slice(0, 1).toUpperCase() + x.slice(1); const makeEvent = (name: string, description: string, params: JSONSchema4) => ({ [`${upperFirst(name)}Event`]: { allOf: [ { $ref: '#/definitions/Event' }, { type: 'object', description, properties: { event: { type: 'string', enum: [name], }, body: { type: 'object', ...params, }, }, required: ['event', 'body'], }, ], }, }); const makeRequest = ( name: string, description: string, args: JSONSchema4 = {}, response?: JSONSchema4, ) => ({ [`${upperFirst(name)}Request`]: { allOf: [ { $ref: '#/definitions/Request' }, { type: 'object', description, properties: { command: { type: 'string', enum: [name], }, arguments: { $ref: `#/definitions/${upperFirst(name)}Arguments`, }, }, required: ['command', 'arguments'], }, ], }, [`${upperFirst(name)}Arguments`]: { type: 'object', description: `Arguments for '${name}' request.`, ...args, }, [`${upperFirst(name)}Response`]: { allOf: [ { $ref: '#/definitions/Response' }, { type: 'object', description: `Response to '${name}' request.`, ...(response && { properties: { body: { type: 'object', ...response, }, }, required: ['body'], }), }, ], }, }); const dapCustom: JSONSchema4 = { definitions: { ...makeRequest('enableCustomBreakpoints', 'Enable custom breakpoints.', { properties: { ids: { type: 'array', items: { type: 'string', }, description: 'Id of breakpoints to enable.', }, }, required: ['ids'], }), ...makeRequest('disableCustomBreakpoints', 'Disable custom breakpoints.', { properties: { ids: { type: 'array', items: { type: 'string', }, description: 'Id of breakpoints to enable.', }, }, required: ['ids'], }), ...makeRequest( 'canPrettyPrintSource', 'Returns whether particular source can be pretty-printed.', { properties: { source: { $ref: '#/definitions/Source', description: 'Source to be pretty printed.', }, }, required: ['source'], }, { required: ['canPrettyPrint'], properties: { canPrettyPrint: { type: 'boolean', description: 'Whether source can be pretty printed.', }, }, }, ), ...makeRequest('prettyPrintSource', 'Pretty prints source for debugging.', { properties: { source: { $ref: '#/definitions/Source', description: 'Source to be pretty printed.', }, line: { type: 'integer', description: 'Line number of currently selected location to reveal after pretty printing. If not present, nothing is revealed.', }, column: { type: 'integer', description: 'Column number of currently selected location to reveal after pretty printing.', }, }, required: ['source'], }), ...makeRequest('toggleSkipFileStatus', 'Toggle skip status of file.', { properties: { resource: { type: 'string', description: 'Url of file to be skipped.', }, sourceReference: { type: 'number', description: 'Source reference number of file.', }, }, }), ...makeEvent('revealLocationRequested', 'A request to reveal a certain location in the UI.', { properties: { source: { $ref: '#/definitions/Source', description: 'The source to reveal.', }, line: { type: 'integer', description: 'The line number to reveal.', }, column: { type: 'integer', description: 'The column number to reveal.', }, }, required: ['source'], }), ...makeEvent('copyRequested', 'A request to copy a certain string to clipboard.', { properties: { text: { type: 'string', description: 'Text to copy.', }, }, required: ['text'], }), ...makeEvent( 'longPrediction', 'An event sent when breakpoint prediction takes a significant amount of time.', {}, ), ...makeEvent( 'launchBrowserInCompanion', 'Request to launch a browser in the companion extension within the UI.', { required: ['type', 'params', 'serverPort', 'launchId'], properties: { type: { type: 'string', enum: ['chrome', 'edge'], description: 'Type of browser to launch', }, launchId: { type: 'number', description: 'Incrementing ID to refer to this browser launch request', }, serverPort: { type: 'number', description: 'Local port the debug server is listening on', }, browserArgs: { type: 'array', items: { type: 'string', }, }, attach: { type: 'object', required: ['host', 'port'], properties: { host: { type: 'string' }, port: { type: 'number' }, }, }, params: { type: 'object', description: 'Original launch parameters for the debug session', }, }, }, ), ...makeEvent('killCompanionBrowser', 'Kills a launched browser companion.', { required: ['launchId'], properties: { launchId: { type: 'number', description: 'Incrementing ID to refer to this browser launch request', }, }, }), ...makeRequest('startProfile', 'Starts taking a profile of the target.', { properties: { stopAtBreakpoint: { type: 'array', items: { type: 'number', }, description: 'Breakpoints where we should stop once hit.', }, type: { type: 'string', description: 'Type of profile that should be taken', }, params: { type: 'object', description: 'Additional arguments for the type of profiler', }, }, required: ['file', 'type'], }), ...makeRequest('stopProfile', 'Stops a running profile.'), ...makeEvent('profileStarted', 'Fired when a profiling state changes.', { required: ['type', 'file'], properties: { type: { type: 'string', description: 'Type of running profile', }, file: { type: 'string', description: 'Location where the profile is saved.', }, }, }), ...makeEvent('profilerStateUpdate', 'Fired when a profiling state changes.', { required: ['label', 'running'], properties: { label: { type: 'string', description: 'Description of the current state', }, running: { type: 'boolean', description: 'Set to false if the profile has now ended', }, }, }), ...makeRequest( 'launchVSCode', 'Launches a VS Code extension host in debug mode.', { required: ['args', 'env'], properties: { args: { type: 'array', items: { $ref: '#/definitions/LaunchVSCodeArgument', }, }, env: { type: 'object', }, debugRenderer: { type: 'boolean', }, }, }, { properties: { rendererDebugPort: { type: 'number', }, }, }, ), LaunchVSCodeArgument: { type: 'object', description: 'This interface represents a single command line argument split into a "prefix" and a "path" half. The optional "prefix" contains arbitrary text and the optional "path" contains a file system path. Concatenating both results in the original command line argument.', properties: { path: { type: 'string', }, prefix: { type: 'string', }, }, }, ...makeRequest('launchUnelevated', 'Launches a VS Code extension host in debug mode.', { properties: { process: { type: 'string', }, args: { type: 'array', items: { type: 'string', }, }, }, }), ...makeRequest( 'remoteFileExists', 'Check if file exists on remote file system, used in VS.', { properties: { localFilePath: { type: 'string', }, }, }, { required: ['doesExists'], properties: { doesExists: { type: 'boolean', description: 'Does the file exist on the remote file system.', }, }, }, ), ...makeRequest( 'remoteFileExists', 'Check if file exists on remote file system, used in VS.', { properties: { localFilePath: { type: 'string', }, }, }, { required: ['doesExists'], properties: { doesExists: { type: 'boolean', description: 'Does the file exist on the remote file system.', }, }, }, ), ...makeRequest('revealPage', 'Focuses the browser page or tab associated with the session.'), ...makeRequest('startSelfProfile', 'Starts profiling the extension itself. Used by VS.', { required: ['file'], properties: { file: { description: 'File where the profile should be saved', type: 'string', }, }, }), ...makeRequest('stopSelfProfile', 'Stops profiling the extension itself. Used by VS.'), ...makeRequest( 'getPerformance', 'Requests that we get performance information from the runtime.', {}, { properties: { metrics: { type: 'object', description: "Response to 'GetPerformance' request. A key-value list of runtime-dependent details.", }, error: { description: 'Optional error from the adapter', type: 'string', }, }, }, ), ...makeEvent( 'suggestDisableSourcemap', 'Fired when requesting a missing source from a sourcemap. UI will offer to disable the sourcemap.', { properties: { source: { $ref: '#/definitions/Source', description: 'Source to be pretty printed.', }, }, required: ['source'], }, ), ...makeRequest( 'disableSourcemap', 'Disables the sourcemapped source and refreshes the stacktrace if paused.', { properties: { source: { $ref: '#/definitions/Source', description: 'Source to be pretty printed.', }, }, required: ['source'], }, ), ...makeRequest( 'createDiagnostics', 'Generates diagnostic information for the debug session.', { properties: { fromSuggestion: { type: 'boolean', description: 'Whether the tool is opening from a prompt', }, }, }, { properties: { file: { type: 'string', description: 'Location of the generated report on disk', }, }, required: ['file'], }, ), ...makeEvent( 'suggestDiagnosticTool', "Shows a prompt to the user suggesting they use the diagnostic tool if breakpoints don't bind.", {}, ), ...makeEvent('openDiagnosticTool', "Opens the diagnostic tool if breakpoints don't bind.", { properties: { file: { type: 'string', description: 'Location of the generated report on disk', }, }, required: ['file'], }), ...makeRequest( 'requestCDPProxy', 'Request WebSocket connection information on a proxy for this debug sessions CDP connection.', undefined, { required: ['host', 'port', 'path'], properties: { host: { type: 'string', description: 'Name of the host, on which the CDP proxy is available through a WebSocket.', }, port: { type: 'number', description: 'Port on the host, under which the CDP proxy is available through a WebSocket.', }, path: { type: 'string', description: 'Websocket path to connect to.', }, }, }, ), }, }; export default dapCustom;
the_stack
import { assert } from 'chai' import bigInt from 'big-integer' import { FakeIlpNetworkClientResponses } from './fakes/fake-ilp-network-client' import { PaymentRequest } from '../../src/ILP/model/payment-request' import IlpError from '../../src/ILP/ilp-error' import FakeDefaultIlpClient from './fakes/fake-default-ilp-client' // Fake accountId const accountId = 'test.foo.bar' // Fake PaymentRequest const fakePaymentRequest = new PaymentRequest({ amount: bigInt(100), destinationPaymentPointer: '$money/baz', senderAccountId: accountId, }) describe('Default ILP Client', function (): void { it('Get balance - success', async function (): Promise<void> { // GIVEN a DefaultIlpClient const client = FakeDefaultIlpClient.fakeSuceedingNetworkClient() // WHEN the balance for an account is requested const amount = await client.getBalance(accountId) // THEN the balance is returned const successfulGetBalanceResponse = FakeIlpNetworkClientResponses.defaultGetBalanceResponse() assert.equal(amount.accountId, successfulGetBalanceResponse.getAccountId()) assert.equal(amount.assetCode, successfulGetBalanceResponse.getAssetCode()) assert.equal( amount.assetScale, successfulGetBalanceResponse.getAssetScale(), ) assert.equal( Number(amount.clearingBalance), successfulGetBalanceResponse.getClearingBalance(), ) assert.equal( Number(amount.prepaidAmount), successfulGetBalanceResponse.getPrepaidAmount(), ) assert.equal( Number(amount.netBalance), successfulGetBalanceResponse.getNetBalance(), ) }) it('Get balance - default error', function (done): void { // GIVEN a DefaultIlpClient const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.defaultError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN an error is thrown assert.typeOf(error, 'Error') assert.equal( error.message, FakeIlpNetworkClientResponses.defaultError.message, ) done() }) }) it('Get balance - Not Found Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.NOT_FOUND const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.notFoundError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.accountNotFound) done() }) }) it('Get balance - Invalid Argument Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.INVALID_ARGUMENT const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.invalidArgumentError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.invalidArgument) done() }) }) it('Get balance - Unauthenticated Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.UNAUTHENTICATED const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.unauthenticatedError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.unauthenticated) done() }) }) it('Get balance - Internal Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.INTERNAL const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.internalError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.internal) done() }) }) it('Get balance - Unknown Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.INTERNAL const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.unknownError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.unknown) done() }) }) it('Get balance - Invalid Access Token', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a IlpError.invalidAccessToken error const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.invalidAccessTokenError, ) // WHEN the balance for an account is requested client.getBalance(accountId).catch((error) => { // THEN the error is simply rethrown assert.equal(error as IlpError, IlpError.invalidAccessToken) done() }) }) it('Send - success', async function (): Promise<void> { // GIVEN a DefaultIlpClient const client = FakeDefaultIlpClient.fakeSuceedingNetworkClient() // WHEN a payment request is sent const paymentResponse = await client.sendPayment(fakePaymentRequest) const successfulPaymentResponse = FakeIlpNetworkClientResponses.defaultSendResponse() // THEN the original amount is equal to mocked original amount assert.equal( Number(paymentResponse.originalAmount), successfulPaymentResponse.getOriginalAmount(), ) // AND the delivered amount is equal to the mocked delivered amount assert.equal( Number(paymentResponse.amountDelivered), successfulPaymentResponse.getAmountDelivered(), ) // AND the amount sent is equal to the mocked amount sent assert.equal( Number(paymentResponse.amountSent), successfulPaymentResponse.getAmountSent(), ) // AND the payment success is equal to the payment success of the mocked response assert.equal( paymentResponse.successfulPayment, successfulPaymentResponse.getSuccessfulPayment(), ) }) it('Send - error', function (done): void { // GIVEN a DefaultIlpClient const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.defaultError, ) // WHEN a payment is requested client.sendPayment(fakePaymentRequest).catch((error) => { // THEN an error is thrown assert.typeOf(error, 'Error') assert.equal( error.message, FakeIlpNetworkClientResponses.defaultError.message, ) done() }) }) it('Send Payment - Not Found Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.NOT_FOUND const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.notFoundError, ) // WHEN a payment is sent client.sendPayment(fakePaymentRequest).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.accountNotFound) done() }) }) it('Send Payment - Invalid Argument Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.INVALID_ARGUMENT const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.invalidArgumentError, ) // WHEN a payment is sent client.sendPayment(fakePaymentRequest).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.invalidArgument) done() }) }) it('Send Payment - Unauthenticated Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.UNAUTHENTICATED const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.unauthenticatedError, ) // WHEN a payment is sent client.sendPayment(fakePaymentRequest).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.unauthenticated) done() }) }) it('Send Payment - Internal Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.INTERNAL const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.internalError, ) // WHEN a payment is sent client.sendPayment(fakePaymentRequest).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.internal) done() }) }) it('Send Payment - Unknown Error', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a grpc.ServiceError // with code = grpcStatusCode.INTERNAL const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.unknownError, ) // WHEN a payment is sent client.sendPayment(fakePaymentRequest).catch((error) => { // THEN the error is translated to a IlpError assert.equal(error as IlpError, IlpError.unknown) done() }) }) it('Send Payment - Invalid Access Token', function (done): void { // GIVEN a DefaultIlpClient with a network client which always throws a IlpError.invalidAccessToken error const client = FakeDefaultIlpClient.withErrors( FakeIlpNetworkClientResponses.invalidAccessTokenError, ) // WHEN a payment is sent client.sendPayment(fakePaymentRequest).catch((error) => { // THEN the error is simply rethrown assert.equal(error as IlpError, IlpError.invalidAccessToken) done() }) }) })
the_stack
'use strict'; import * as server from "./server" import { DocumentFormattingParams, TextEdit, Files, TextDocument, Range, Position } from 'vscode-languageserver' import * as stream from 'stream' let skProtocolProcess = null let skeHandler = null export function initializeSourcekite() { if (skProtocolProcess == null) { initializeSKProtocolProcess() } } function createSkProtocolProcess() { if (server.skProtocolProcessAsShellCmd) { return server.spawn(server.getShellExecPath(), ["-c", `docker run --rm -v ${server.workspaceRoot}:${server.workspaceRoot} -i jinmingjian/docker-sourcekite`]) } else { return server.spawn(server.skProtocolPath) } } function initializeSKProtocolProcess() { debugLog(`***sourcekite initializing with skProtocolProcess at [${server.skProtocolPath}]`) const pathSourcekite = server.sdeSettings.path.sourcekite skProtocolProcess = createSkProtocolProcess() skProtocolProcess.stderr.on('data', (data) => { if (server.isTracingOn) { debugLog('***stderr***' + data) } }) skProtocolProcess.on('exit', function (code, signal) { debugLog('***sourcekite exited***' + `code: ${code}, signal: ${signal}`) debugLog('***sourcekite exited***' + 'to spawn a new sourcekite process') //NOTE this is not guaranteed to reboot, but we just want it 'not guaranteed' skProtocolProcess = createSkProtocolProcess() }) skProtocolProcess.on('error', function (err) { debugLog('***sourcekitd_repl error***' + (<Error>err).message) if ((<Error>err).message.indexOf("ENOENT") > 0) { const msg = "The '" + pathSourcekite + "' command is not available." + " Please check your swift executable user setting and ensure it is installed."; debugLog('***sourcekitd_repl not found***' + msg) } throw err }) skeHandler = new SourcekiteResponseHandler() } enum ParsingState { endResponse, startResponseContent } //assumption:single-thread class SourcekiteResponseHandler { private static nResponsesSlot = 64 //FIXME config options? // private static responseTimeoutMills = 15 * 1000 //FIXME private rids = new Array<number>(SourcekiteResponseHandler.nResponsesSlot)//for checking private responses = new Array<any>(SourcekiteResponseHandler.nResponsesSlot) private responsesProcessed = Array.from(new Array<boolean>(SourcekiteResponseHandler.nResponsesSlot)).map((_, i) => true) private responseResolves = new Array<Function>(SourcekiteResponseHandler.nResponsesSlot) private responseRejects = new Array<Function>(SourcekiteResponseHandler.nResponsesSlot) constructor() { skProtocolProcess.stdout.on('data', this.handleResponse.bind(this)) debugLog("-->SourcekiteResponseHandler constructor done") } // private hasError = false private output = "" // private rid = -1 private handleResponse(data): void { this.output += data if (server.isTracingOn) { server.trace('', '' + data) } if (this.output.endsWith("}\n\n")) { const idx = this.output.indexOf("\n") const ridstr = this.output.substring(0, idx) const rid = parseInt(ridstr) if (isNaN(rid)) { throw new Error("wrong format for reqid") } const res = this.output.substring(idx + 1) const slot = this.getSlot(rid) const resolve = this.responseResolves[slot] const reject = this.responseRejects[slot] this.output = "" this.responsesProcessed[slot] = true try { resolve(res) } catch (e) { debugLog(`---error: ${e}`) reject(e) } } } public getResponse(rid: number): Promise<string> { // const start = new Date().getTime() //FIXME enable timeout? return new Promise((resolve, reject) => { const slot = this.getSlot(rid) //FIXME enable timeout?reject only when covered by next replacer if (!this.responsesProcessed[slot]) { const rjt = this.responseRejects[slot] rjt(`fail to process the request[reqid=${this.rids[slot]}]`) } this.rids[slot] = rid this.responseResolves[slot] = resolve this.responseRejects[slot] = reject this.responsesProcessed[slot] = false }) } private getSlot(rid: number): number { return rid % SourcekiteResponseHandler.nResponsesSlot } } let reqCount = 0 //FIXME type RequestType = "codecomplete" | "cursorinfo" | "demangle" | "editor.open" | "editor.formattext" //FIXME generic for future function typedResponse(request: string, requestType: RequestType, extraState: any = null): Promise<{}> { server.trace('to write request: ', request) const rid = reqCount++ skProtocolProcess.stdin.write(rid + "\n") skProtocolProcess.stdin.write(request) return skeHandler.getResponse(rid) .then(resp => { switch (requestType) { case "codecomplete": case "demangle": const res = JSON.parse(jsonify(resp)) return res["key.results"] case "editor.formattext": const keyLine = extraState.keyLine const lineRange = extraState.lineRange let offSetEnd = resp.lastIndexOf("\""); let offSetStart = resp.indexOf("\"", resp.lastIndexOf("key.sourcetext:")) + 1 let lineText = resp.substring(offSetStart, offSetEnd) // server.trace(`---responseEditorFormatText lineText(${keyLine}): `, lineText) return { line: keyLine, textEdit: { range: lineRange, newText: JSON.parse(`"${lineText}"`) //NOTE convert back, silly... } } default: return JSON.parse(jsonify(resp)) } }).catch(e => { debugLog("***typedResponse error: " + e) }) } function request( requestType: RequestType, srcText: string, srcPath: string, offset: number): Promise<any> { const sourcePaths = server.getAllSourcePaths(srcPath) const compilerargs = JSON.stringify((sourcePaths ? sourcePaths : [srcPath]) .concat(server.loadArgsImportPaths()) ) srcText = JSON.stringify(srcText) let request = `{ key.request: source.request.${requestType}, key.sourcefile: "${srcPath}", key.offset: ${offset}, key.compilerargs: ${compilerargs}, key.sourcetext: ${srcText} } ` return typedResponse(request, requestType) }; //== codeComplete export function codeComplete(srcText: string, srcPath: string, offset: number): Promise<any> { return request("codecomplete", srcText, srcPath, offset); } //== cursorInfo export function cursorInfo(srcText: string, srcPath: string, offset: number): Promise<any> { return request("cursorinfo", srcText, srcPath, offset); } //== demangle export function demangle(...demangledNames: string[]): Promise<any> { const names = JSON.stringify(demangledNames.join(",")); let request = `{ key.request: source.request.demangle, key.names: [${names}] } ` return typedResponse(request, "demangle") } //== editorFormatText export function editorFormatText( document: TextDocument, srcText: string, srcPath: string, lineStart: number, lineEnd: number): Promise<TextEdit[]> { return new Promise<TextEdit[]>((resolve, reject) => { let tes: TextEdit[] = [] editorOpen(srcPath, srcText, false, false, true) .then((v) => { // discard v let p = requestEditorFormatText(srcPath, lineStart, 1, document) //TODO async-await function nextp(fts: FormatTextState) { tes.push(fts.textEdit) if (fts.line != lineEnd) { let sPos: Position = { line: fts.line, character: 0 } let ePos: Position = document.positionAt( document.offsetAt({ line: fts.line + 1, character: 0 }) - 1) requestEditorFormatText(srcPath, fts.line + 1, 1, document) .then(nextp) .catch((err) => { reject(err) }) } else { resolve(tes) } } p.then(nextp).catch((err) => { reject(err) }) }).catch((err) => { reject(err) }) }); } //== editorOpen function editorOpen( keyName: string, keySourcetext: string, keyEnableSyntaxMap: boolean, keyEnableSubStructure: boolean, keySyntacticOnly: boolean): Promise<string> { keySourcetext = JSON.stringify(keySourcetext); let request = `{ key.request: source.request.editor.open, key.name: "${keyName}", key.enablesyntaxmap: ${booleanToInt(keyEnableSyntaxMap)}, key.enablesubstructure: ${booleanToInt(keyEnableSubStructure)}, key.syntactic_only: ${booleanToInt(keySyntacticOnly)}, key.sourcetext: ${keySourcetext}, key.sourcetext: ${keySourcetext} } ` return typedResponse(request, "editor.open") } interface FormatTextState { line: number, textEdit: TextEdit } function requestEditorFormatText( keyName: string, keyLine: number, keyLength: number,//FIXME unuseful now document: TextDocument ): Promise<FormatTextState> { let request = `{ key.request: source.request.editor.formattext, key.name: "${keyName}", key.line: ${keyLine}, key.length: ${keyLength}, } `; let firstStartPos: Position = { line: keyLine - 1, character: 0 } let firstEndPos: Position = keyLine != document.lineCount ? document.positionAt( document.offsetAt({ line: keyLine, character: 0 }) - 1) : document.positionAt( document.offsetAt({ line: document.lineCount, character: 0 })) return typedResponse(request, "editor.formattext", { keyLine: keyLine, lineRange: { start: firstStartPos, end: firstEndPos }//NOTE format req is 1-based } ) } function debugLog(msg: string) { server.trace(msg) } function booleanToInt(v: boolean): Number { return v ? 1 : 0 } const cutOffPrefix = "key.results:"; function cutOffResponse(s: string): string { s = s.substring(s.indexOf(cutOffPrefix) + cutOffPrefix.length, s.length) s = s.substring(0, s.lastIndexOf("key.kind:")) s = s.substring(0, s.lastIndexOf(",")) + "]" return jsonify(s); } function jsonify(s: string): string { return s .replace(/(key.[a-z_.]+):/g, '"$1":') .replace(/(source.[a-z_.]+),/g, '"$1",') }
the_stack
// aliases for shorter compressed code (most minifers don't do this) const ab = ArrayBuffer, u8 = Uint8Array, u16 = Uint16Array, i16 = Int16Array, u32 = Uint32Array, i32 = Int32Array; // Huffman decoding table interface HDT { // initial bits b: number; // symbols s: Uint8Array; // num bits n: Uint8Array; } // FSE decoding table interface FSEDT extends HDT { // next state t: Uint16Array; } // decompress Zstandard state interface DZstdState { // byte b: number; // out byte y: number; // dictionary ID d: number; // window w: Uint8Array; // max block size m: number; // uncompressed size u: number; // has checksum c: number; // offsets o: Int32Array; // window head e: number; // last huffman decoding table h?: HDT; // last FSE decoding tables t?: [FSEDT, FSEDT, FSEDT]; // last block l: number; } const slc = (v: Uint8Array, s: number, e?: number) => { if (u8.prototype.slice) return u8.prototype.slice.call(v, s, e); if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; const n = new u8(e - s); n.set(v.subarray(s, e)); return n; } const fill = (v: Uint8Array, n: number, s?: number, e?: number) => { if (u8.prototype.fill) return u8.prototype.fill.call(v, n, s, e); if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; for (; s < e; ++s) v[s] = n; return v; } const cpw = (v: Uint8Array, t: number, s?: number, e?: number) => { if (u8.prototype.copyWithin) return u8.prototype.copyWithin.call(v, t, s, e); if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; while (s < e) { v[t++] = v[s++]; } } /** * Codes for errors generated within this library */ export const ZstdErrorCode = { InvalidData: 0, WindowSizeTooLarge: 1, InvalidBlockType: 2, FSEAccuracyTooHigh: 3, DistanceTooFarBack: 4, UnexpectedEOF: 5 } as const; type ZEC = (typeof ZstdErrorCode)[keyof typeof ZstdErrorCode]; // error codes const ec: Record<ZEC, string | undefined> = [ 'invalid zstd data', 'window size too large (>2046MB)', 'invalid block type', 'FSE accuracy too high', 'match distance too far back', 'unexpected EOF' ]; /** * An error generated within this library */ export interface ZstdError extends Error { /** * The code associated with this error */ code: ZEC; }; const err = (ind: ZEC, msg?: string | 0, nt?: 1) => { const e: Partial<ZstdError> = new Error(msg || ec[ind]); e.code = ind; if (Error.captureStackTrace) Error.captureStackTrace(e, err); if (!nt) throw e; return e as ZstdError; } const rb = (d: Uint8Array, b: number, n: number) => { let i = 0, o = 0; for (; i < n; ++i) o |= d[b++] << (i << 3); return o; } const b4 = (d: Uint8Array, b: number) => (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; // read Zstandard frame header const rzfh = (dat: Uint8Array, w?: Uint8Array | 1): number | DZstdState => { const n3 = dat[0] | (dat[1] << 8) | (dat[2] << 16); if (n3 == 0x2FB528 && dat[3] == 253) { // Zstandard const flg = dat[4]; // single segment checksum dict flag frame content flag const ss = (flg >> 5) & 1, cc = (flg >> 2) & 1, df = flg & 3, fcf = flg >> 6; if (flg & 8) err(0); // byte let bt = 6 - ss; // dict bytes const db = df == 3 ? 4 : df; // dictionary id const di = rb(dat, bt, db); bt += db; // frame size bytes const fsb = fcf ? (1 << fcf) : ss; // frame source size const fss = rb(dat, bt, fsb) + ((fcf == 1) && 256); // window size let ws = fss; if (!ss) { // window descriptor const wb = 1 << (10 + (dat[5] >> 3)); ws = wb + (wb >> 3) * (dat[5] & 7); } if (ws > 2145386496) err(1); const buf = new u8((w == 1 ? (fss || ws) : w ? 0 : ws) + 12); buf[0] = 1, buf[4] = 4, buf[8] = 8; return { b: bt + fsb, y: 0, l: 0, d: di, w: (w && w != 1) ? w : buf.subarray(12), e: ws, o: new i32(buf.buffer, 0, 3), u: fss, c: cc, m: Math.min(131072, ws) }; } else if (((n3 >> 4) | (dat[3] << 20)) == 0x184D2A5) { // skippable return b4(dat, 4) + 8; } err(0); } // most significant bit for nonzero const msb = (val: number) => { let bits = 0; for (; (1 << bits) <= val; ++bits); return bits - 1; } // read finite state entropy const rfse = (dat: Uint8Array, bt: number, mal: number): [number, FSEDT] => { // table pos let tpos = (bt << 3) + 4; // accuracy log const al = (dat[bt] & 15) + 5; if (al > mal) err(3); // size const sz = 1 << al; // probabilities symbols repeat index high threshold let probs = sz, sym = -1, re = -1, i = -1, ht = sz; // optimization: single allocation is much faster const buf = new ab(512 + (sz << 2)); const freq = new i16(buf, 0, 256); // same view as freq const dstate = new u16(buf, 0, 256); const nstate = new u16(buf, 512, sz); const bb1 = 512 + (sz << 1); const syms = new u8(buf, bb1, sz); const nbits = new u8(buf, bb1 + sz); while (sym < 255 && probs > 0) { const bits = msb(probs + 1); const cbt = tpos >> 3; // mask const msk = (1 << (bits + 1)) - 1; let val = ((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (tpos & 7)) & msk; // mask (1 fewer bit) const msk1fb = (1 << bits) - 1; // max small value const msv = msk - probs - 1; // small value const sval = val & msk1fb; if (sval < msv) tpos += bits, val = sval; else { tpos += bits + 1; if (val > msk1fb) val -= msv; } freq[++sym] = --val; if (val == -1) { probs += val; syms[--ht] = sym; } else probs -= val; if (!val) { do { // repeat byte const rbt = tpos >> 3; re = ((dat[rbt] | (dat[rbt + 1] << 8)) >> (tpos & 7)) & 3; tpos += 2; sym += re; } while (re == 3); } } if (sym > 255 || probs) err(0); let sympos = 0; // sym step (coprime with sz - formula from zstd source) const sstep = (sz >> 1) + (sz >> 3) + 3; // sym mask const smask = sz - 1; for (let s = 0; s <= sym; ++s) { const sf = freq[s]; if (sf < 1) { dstate[s] = -sf; continue; } // This is split into two loops in zstd to avoid branching, but as JS is higher-level that is unnecessary for (i = 0; i < sf; ++i) { syms[sympos] = s; do { sympos = (sympos + sstep) & smask; } while (sympos >= ht); } } // After spreading symbols, should be zero again if (sympos) err(0); for (i = 0; i < sz; ++i) { // next state const ns = dstate[syms[i]]++; // num bits const nb = nbits[i] = al - msb(ns); nstate[i] = (ns << nb) - sz; } return [(tpos + 7) >> 3, { b: al, s: syms, n: nbits, t: nstate }]; } // read huffman const rhu = (dat: Uint8Array, bt: number): [number, HDT] => { // index weight count let i = 0, wc = -1; // buffer header byte const buf = new u8(292), hb = dat[bt]; // huffman weights const hw = buf.subarray(0, 256); // rank count const rc = buf.subarray(256, 268); // rank index const ri = new u16(buf.buffer, 268); // NOTE: at this point bt is 1 less than expected if (hb < 128) { // end byte, fse decode table const [ebt, fdt] = rfse(dat, bt + 1, 6); bt += hb; const epos = ebt << 3; // last byte const lb = dat[bt]; if (!lb) err(0); // state1 state2 state1 bits state2 bits let st1 = 0, st2 = 0, btr1 = fdt.b, btr2 = btr1 // fse pos // pre-increment to account for original deficit of 1 let fpos = (++bt << 3) - 8 + msb(lb); for (;;) { fpos -= btr1; if (fpos < epos) break; let cbt = fpos >> 3; st1 += ((dat[cbt] | (dat[cbt + 1] << 8)) >> (fpos & 7)) & ((1 << btr1) - 1); hw[++wc] = fdt.s[st1]; fpos -= btr2; if (fpos < epos) break; cbt = fpos >> 3; st2 += ((dat[cbt] | (dat[cbt + 1] << 8)) >> (fpos & 7)) & ((1 << btr2) - 1); hw[++wc] = fdt.s[st2]; btr1 = fdt.n[st1]; st1 = fdt.t[st1]; btr2 = fdt.n[st2]; st2 = fdt.t[st2]; } if (++wc > 255) err(0); } else { wc = hb - 127; for (; i < wc; i += 2) { const byte = dat[++bt]; hw[i] = byte >> 4; hw[i + 1] = byte & 15; } ++bt; } // weight exponential sum let wes = 0; for (i = 0; i < wc; ++i) { const wt = hw[i]; // bits must be at most 11, same as weight if (wt > 11) err(0); wes += wt && (1 << (wt - 1)); } // max bits const mb = msb(wes) + 1; // table size const ts = 1 << mb; // remaining sum const rem = ts - wes; // must be power of 2 if (rem & (rem - 1)) err(0); hw[wc++] = msb(rem) + 1; for (i = 0; i < wc; ++i) { const wt = hw[i]; ++rc[hw[i] = wt && (mb + 1 - wt)]; } // huf buf const hbuf = new u8(ts << 1); // symbols num bits const syms = hbuf.subarray(0, ts), nb = hbuf.subarray(ts); ri[mb] = 0; for (i = mb; i > 0; --i) { const pv = ri[i]; fill(nb, i, pv, ri[i - 1] = pv + rc[i] * (1 << (mb - i))); } if (ri[0] != ts) err(0); for (i = 0; i < wc; ++i) { const bits = hw[i]; if (bits) { const code = ri[bits]; fill(syms, i, code, ri[bits] = code + (1 << (mb - bits))); } } return [bt, { n: nb, b: mb, s: syms }]; } // Tables generated using this: // https://gist.github.com/101arrowz/a979452d4355992cbf8f257cbffc9edd // default literal length table const dllt = /*#__PURE__*/ rfse(/*#__PURE__*/ new u8([ 81, 16, 99, 140, 49, 198, 24, 99, 12, 33, 196, 24, 99, 102, 102, 134, 70, 146, 4 ]), 0, 6)[1]; // default match length table const dmlt = /*#__PURE__*/ rfse(/*#__PURE__*/ new u8([ 33, 20, 196, 24, 99, 140, 33, 132, 16, 66, 8, 33, 132, 16, 66, 8, 33, 68, 68, 68, 68, 68, 68, 68, 68, 36, 9 ]), 0, 6)[1]; // default offset code table const doct = /*#__PURE__ */ rfse(/*#__PURE__*/ new u8([ 32, 132, 16, 66, 102, 70, 68, 68, 68, 68, 36, 73, 2 ]), 0, 5)[1]; // bits to baseline const b2bl = (b: Uint8Array, s: number) => { const len = b.length, bl = new i32(len); for (let i = 0; i < len; ++i) { bl[i] = s; s += 1 << b[i]; } return bl; } // literal length bits const llb = /*#__PURE__ */ new u8((/*#__PURE__ */ new i32([ 0, 0, 0, 0, 16843009, 50528770, 134678020, 202050057, 269422093 ])).buffer, 0, 36); // literal length baseline const llbl = /*#__PURE__ */ b2bl(llb, 0); // match length bits const mlb = /*#__PURE__ */ new u8((/*#__PURE__ */ new i32([ 0, 0, 0, 0, 0, 0, 0, 0, 16843009, 50528770, 117769220, 185207048, 252579084, 16 ])).buffer, 0, 53); // match length baseline const mlbl = /*#__PURE__ */ b2bl(mlb, 3); // decode huffman stream const dhu = (dat: Uint8Array, out: Uint8Array, hu: HDT) => { const len = dat.length, ss = out.length, lb = dat[len - 1], msk = (1 << hu.b) - 1, eb = -hu.b; if (!lb) err(0); let st = 0, btr = hu.b, pos = (len << 3) - 8 + msb(lb) - btr, i = -1; for (; pos > eb && i < ss;) { const cbt = pos >> 3; const val = (dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (pos & 7); st = ((st << btr) | val) & msk; out[++i] = hu.s[st]; pos -= (btr = hu.n[st]); } if (pos != eb || i + 1 != ss) err(0); } // decode huffman stream 4x // TODO: use workers to parallelize const dhu4 = (dat: Uint8Array, out: Uint8Array, hu: HDT) => { let bt = 6; const ss = out.length, sz1 = (ss + 3) >> 2, sz2 = sz1 << 1, sz3 = sz1 + sz2; dhu(dat.subarray(bt, bt += dat[0] | (dat[1] << 8)), out.subarray(0, sz1), hu); dhu(dat.subarray(bt, bt += dat[2] | (dat[3] << 8)), out.subarray(sz1, sz2), hu); dhu(dat.subarray(bt, bt += dat[4] | (dat[5] << 8)), out.subarray(sz2, sz3), hu); dhu(dat.subarray(bt), out.subarray(sz3), hu); } // read Zstandard block const rzb = (dat: Uint8Array, st: DZstdState, out?: Uint8Array) => { let bt = st.b; // byte 0 block type const b0 = dat[bt], btype = (b0 >> 1) & 3; st.l = b0 & 1; const sz = (b0 >> 3) | (dat[bt + 1] << 5) | (dat[bt + 2] << 13); // end byte for block const ebt = (bt += 3) + sz; if (btype == 1) { if (bt >= dat.length) return; st.b = bt + 1; if (out) { fill(out, dat[bt], st.y, st.y += sz); return out; } return fill(new u8(sz), dat[bt]); } if (ebt > dat.length) return; if (btype == 0) { st.b = ebt; if (out) { out.set(dat.subarray(bt, ebt), st.y); st.y += sz; return out; } return slc(dat, bt, ebt); } if (btype == 2) { // byte 3 lit btype size format const b3 = dat[bt], lbt = b3 & 3, sf = (b3 >> 2) & 3; // lit src size lit cmp sz 4 streams let lss = b3 >> 4, lcs = 0, s4 = 0; if (lbt < 2) { if (sf & 1) lss |= (dat[++bt] << 4) | ((sf & 2) && (dat[++bt] << 12)); else lss = b3 >> 3; } else { s4 = sf; if (sf < 2) lss |= ((dat[++bt] & 63) << 4), lcs = (dat[bt] >> 6) | (dat[++bt] << 2); else if (sf == 2) lss |= (dat[++bt] << 4) | ((dat[++bt] & 3) << 12), lcs = (dat[bt] >> 2) | (dat[++bt] << 6); else lss |= (dat[++bt] << 4) | ((dat[++bt] & 63) << 12), lcs = (dat[bt] >> 6) | (dat[++bt] << 2) | (dat[++bt] << 10); } ++bt; // add literals to end - can never overlap with backreferences because unused literals always appended let buf = out ? out.subarray(st.y, st.y + st.m) : new u8(st.m); // starting point for literals let spl = buf.length - lss; if (lbt == 0) buf.set(dat.subarray(bt, bt += lss), spl); else if (lbt == 1) fill(buf, dat[bt++], spl); else { // huffman table let hu = st.h; if (lbt == 2) { const hud = rhu(dat, bt); // subtract description length lcs += bt - (bt = hud[0]); st.h = hu = hud[1]; } else if (!hu) err(0); (s4 ? dhu4 : dhu)(dat.subarray(bt, bt += lcs), buf.subarray(spl), hu); } // num sequences let ns = dat[bt++]; if (ns) { if (ns == 255) ns = (dat[bt++] | (dat[bt++] << 8)) + 0x7F00; else if (ns > 127) ns = ((ns - 128) << 8) | dat[bt++]; // symbol compression modes const scm = dat[bt++]; if (scm & 3) err(0); let dts: [FSEDT, FSEDT, FSEDT] = [dmlt, doct, dllt]; for (let i = 2; i > -1; --i) { const md = (scm >> ((i << 1) + 2)) & 3; if (md == 1) { // rle buf const rbuf = new u8([0, 0, dat[bt++]]); dts[i] = { s: rbuf.subarray(2, 3), n: rbuf.subarray(0, 1), t: new u16(rbuf.buffer, 0, 1), b: 0 }; } else if (md == 2) { // accuracy log 8 for offsets, 9 for others [bt, dts[i]] = rfse(dat, bt, 9 - (i & 1)); } else if (md == 3) { if (!st.t) err(0); dts[i] = st.t[i]; } } const [mlt, oct, llt] = st.t = dts; const lb = dat[ebt - 1]; if (!lb) err(0); let spos = (ebt << 3) - 8 + msb(lb) - llt.b, cbt = spos >> 3, oubt = 0; let lst = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << llt.b) - 1); cbt = (spos -= oct.b) >> 3; let ost = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << oct.b) - 1); cbt = (spos -= mlt.b) >> 3; let mst = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << mlt.b) - 1); for (++ns; --ns;) { const llc = llt.s[lst]; const lbtr = llt.n[lst]; const mlc = mlt.s[mst]; const mbtr = mlt.n[mst]; const ofc = oct.s[ost]; const obtr = oct.n[ost]; cbt = (spos -= ofc) >> 3; const ofp = 1 << ofc; let off = ofp + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16) | (dat[cbt + 3] << 24)) >>> (spos & 7)) & (ofp - 1)); cbt = (spos -= mlb[mlc]) >> 3; let ml = mlbl[mlc] + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (spos & 7)) & ((1 << mlb[mlc]) - 1)); cbt = (spos -= llb[llc]) >> 3; const ll = llbl[llc] + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (spos & 7)) & ((1 << llb[llc]) - 1)); cbt = (spos -= lbtr) >> 3; lst = llt.t[lst] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << lbtr) - 1)); cbt = (spos -= mbtr) >> 3; mst = mlt.t[mst] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << mbtr) - 1)); cbt = (spos -= obtr) >> 3; ost = oct.t[ost] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << obtr) - 1)); if (off > 3) { st.o[2] = st.o[1]; st.o[1] = st.o[0]; st.o[0] = off -= 3; } else { const idx = off - ((ll != 0) as unknown as number); if (idx) { off = idx == 3 ? st.o[0] - 1 : st.o[idx] if (idx > 1) st.o[2] = st.o[1]; st.o[1] = st.o[0] st.o[0] = off; } else off = st.o[0]; } for (let i = 0; i < ll; ++i) { buf[oubt + i] = buf[spl + i]; } oubt += ll, spl += ll; let stin = oubt - off; if (stin < 0) { let len = -stin; const bs = st.e + stin; if (len > ml) len = ml; for (let i = 0; i < len; ++i) { buf[oubt + i] = st.w[bs + i]; } oubt += len, ml -= len, stin = 0; } for (let i = 0; i < ml; ++i) { buf[oubt + i] = buf[stin + i]; } oubt += ml } if (oubt != spl) { while (spl < buf.length) { buf[oubt++] = buf[spl++]; } } else oubt = buf.length; if (out) st.y += oubt; else buf = slc(buf, 0, oubt); } else { if (out) { st.y += lss; if (spl) { for (let i = 0; i < lss; ++i) { buf[i] = buf[spl + i]; } } } else if (spl) buf = slc(buf, spl); } st.b = ebt; return buf; } err(2); } // concat const cct = (bufs: Uint8Array[], ol: number) => { if (bufs.length == 1) return bufs[0]; const buf = new u8(ol); for (let i = 0, b = 0; i < bufs.length; ++i) { const chk = bufs[i]; buf.set(chk, b); b += chk.length; } return buf; } /** * Decompresses Zstandard data * @param dat The input data * @param buf The output buffer. If unspecified, the function will allocate * exactly enough memory to fit the decompressed data. If your * data has multiple frames and you know the output size, specifying * it will yield better performance. * @returns The decompressed data */ export function decompress(dat: Uint8Array, buf?: Uint8Array) { let bt = 0, bufs: Uint8Array[] = [], nb = +!buf as 0 | 1, ol = 0; for (; dat.length;) { let st = rzfh(dat, nb || buf); if (typeof st == 'object') { if (nb) { buf = null; if (st.w.length == st.u) { bufs.push(buf = st.w); ol += st.u; } } else { bufs.push(buf); st.e = 0; } for (; !st.l;) { const blk = rzb(dat, st, buf); if (!blk) err(5); if (buf) st.e = st.y; else { bufs.push(blk); ol += blk.length; cpw(st.w, 0, blk.length); st.w.set(blk, st.w.length - blk.length); } } bt = st.b + (st.c * 4); } else bt = st; dat = dat.subarray(bt); } return cct(bufs, ol); } /** * Callback to handle data in Zstandard streams * @param data The data that was (de)compressed * @param final Whether this is the last chunk in the stream */ export type ZstdStreamHandler = (data: Uint8Array, final?: boolean) => unknown; /** * Decompressor for Zstandard streamed data */ export class Decompress { private s: DZstdState | number; private c: Uint8Array[]; private l: number; private z: number; /** * Creates a Zstandard decompressor * @param ondata The handler for stream data */ constructor(ondata?: ZstdStreamHandler) { this.ondata = ondata; this.c = []; this.l = 0; this.z = 0; } /** * Pushes data to be decompressed * @param chunk The chunk of data to push * @param final Whether or not this is the last chunk in the stream */ push(chunk: Uint8Array, final?: boolean) { if (typeof this.s == 'number') { const sub = Math.min(chunk.length, this.s as number); chunk = chunk.subarray(sub); (this.s as number) -= sub; } const sl = chunk.length; const ncs = sl + this.l; if (!this.s) { if (final) { if (!ncs) return; // min for frame + one block if (ncs < 5) err(5); } else if (ncs < 18) { this.c.push(chunk); this.l = ncs; return; } if (this.l) { this.c.push(chunk); chunk = cct(this.c, ncs); this.c = []; this.l = 0; } if (typeof (this.s = rzfh(chunk)) == 'number') return this.push(chunk, final); } if (typeof this.s != 'number') { if (ncs < (this.z || 4)) { if (final) err(5); this.c.push(chunk); this.l = ncs; return; } if (this.l) { this.c.push(chunk); chunk = cct(this.c, ncs); this.c = []; this.l = 0; } if (!this.z && ncs < (this.z = (chunk[(this.s as DZstdState).b] & 2) ? 5 : 4 + ((chunk[(this.s as DZstdState).b] >> 3) | (chunk[(this.s as DZstdState).b + 1] << 5) | (chunk[(this.s as DZstdState).b + 2] << 13)))) { if (final) err(5); this.c.push(chunk); this.l = ncs; return; } else this.z = 0; for (;;) { const blk = rzb(chunk, this.s as DZstdState); if (!blk) { if (final) err(5); const adc = chunk.subarray((this.s as DZstdState).b); (this.s as DZstdState).b = 0; this.c.push(adc), this.l += adc.length; return; } else { this.ondata(blk, false); cpw((this.s as DZstdState).w, 0, blk.length); (this.s as DZstdState).w.set(blk, (this.s as DZstdState).w.length - blk.length); } if ((this.s as DZstdState).l) { const rest = chunk.subarray((this.s as DZstdState).b); this.s = (this.s as DZstdState).c * 4; this.push(rest, final); return; } } } } /** * Handler called whenever data is decompressed */ ondata: ZstdStreamHandler; }
the_stack
import * as parseXml from '../parser/types'; import { PropertyResolver } from './property-resolver'; import { PropertyHandlerProvider, WidgetResolveResult } from '../providers/property-handler-provider'; import { RootWidgetModel, ImportModel, WidgetModel, PropertyModel, ParamModel, VariableModel } from '../models/models'; import { Config } from '../models/config'; import { removeDuplicatedBuilders } from './util'; export class WidgetResolver { constructor(private readonly config: Config, private readonly propertyHandlerProvider: PropertyHandlerProvider, private readonly propertyResolver: PropertyResolver) { } resolve(xmlDoc: parseXml.Document): RootWidgetModel { const rootElement = xmlDoc.children[0] as parseXml.Element; const rootElementAttrs = JSON.parse(JSON.stringify(rootElement.attributes)); const rootChild = this.getChildWidget(rootElement); let rootChildWidget = this.resolveWidget(rootChild, null); // check for top-level properties, specially for <if> if (rootChildWidget.isPropertyElement) { const propertyHandler = this.propertyHandlerProvider.get(rootChildWidget.propertyElement); if (propertyHandler && propertyHandler.canResolvePropertyElement()) { const childrenElements = rootElement.children.filter(a => a.type === 'element').map(a => a as parseXml.Element); const child = childrenElements.filter(a => a.name === rootChildWidget.propertyElement)[0]; const widget = this.resolvePropertyElement(rootChildWidget, rootElement, childrenElements, child); if (widget) { rootChildWidget = { widget: widget, isPropertyElement: false, propertyElement: null, propertyElementProperties: [] }; } } // no need for now // else { // // this child is a property element <title>...</title> // this.addElementAsAttribute(rootElement, rootChildWidget); // } } removeDuplicatedBuilders(rootChildWidget.widget, null, 'wrappedWidgets', { }); this.callOnResolved(rootChildWidget.widget); const mixins = this.resolveMixins(rootElement); const params = this.resolveParams(rootElement); const providers = this.resolveProviders(rootElement); const vars = this.resolveVars(rootElement); const imports = this.resolveImports(rootElementAttrs); const routeAware = 'routeAware' in rootElementAttrs; if (routeAware) { const hasRouteAware = mixins.filter(a => a === 'RouteAware').length > 0; if (!hasRouteAware) { mixins.push('RouteAware'); } } const rootWidget: RootWidgetModel = { type: rootElement.name, stateful: 'stateful' in rootElementAttrs, controller: rootElementAttrs.controller, // controllerName: rootElementAttrs.controller, controllerPath: rootElementAttrs.controllerPath, rootChild: rootChildWidget.widget, params: params, mixins: mixins, providers: providers, vars: vars, imports: imports, routeAware: routeAware }; return rootWidget; } private callOnResolved(widget: WidgetModel) { if (!widget) { return; } if (widget.onResolved) { widget.onResolved.forEach(a => a && a(widget)); widget.onResolved = null as any; } if (widget.wrappedWidgets) { widget.wrappedWidgets.forEach(w => { this.callOnResolved(w); }); } widget.properties.forEach(p => { let property = p; if (p.dataType === 'propertyElement') { // unwrap the contained property property = p.value as any; } if (property.dataType === 'widget') { this.callOnResolved(property.value as any); } else if (property.dataType === 'widgetList') { (property.value as WidgetModel[]).forEach(w => { this.callOnResolved(w); }); } }); } private getChildWidget(rootElement: parseXml.Element) { return rootElement.children .filter(a => a.type === 'element' && ['var', 'param', 'provider', 'with'].indexOf((a as parseXml.Element).name) === -1)[0] as parseXml.Element; } private resolveMixins(rootElement: parseXml.Element): string[] { const nodes = rootElement.children.filter(a => a.type === 'element' && (a as parseXml.Element).name === 'with') as parseXml.Element[]; const params: string[] = nodes .map(n => { return n.attributes['mixin']; }) .filter(a => !!a); return params; } private resolveImports(attrs: any): ImportModel[] { const imports: ImportModel[] = []; Object.keys(attrs).filter(k => k.startsWith('xmlns')).forEach(k => { const name = k.replace('xmlns:', '').replace('xmlns', ''); const path = attrs[k]; imports.push({ // name: name, path: path }); }); return imports; } private resolveParams(rootElement: parseXml.Element): ParamModel[] { const nodes = rootElement.children.filter(a => a.type === 'element' && (a as parseXml.Element).name === 'param') as parseXml.Element[]; const params: ParamModel[] = nodes.map(n => { return { type: n.attributes['type'] || 'dynamic', name: n.attributes['name'], value: n.attributes['value'], superParamName: n.attributes['superParamName'], required: 'required' in n.attributes }; }).filter(a => !!a.name || !!a.superParamName); return params; } private resolveProviders(rootElement: parseXml.Element): VariableModel[] { const nodes = rootElement.children.filter(a => a.type === 'element' && (a as parseXml.Element).name === 'provider') as parseXml.Element[]; const params: VariableModel[] = nodes.map(n => { return { type: n.attributes['type'], name: n.attributes['name'] }; }).filter(a => !!a.name); return params; } private resolveVars(rootElement: parseXml.Element): VariableModel[] { const nodes = rootElement.children.filter(a => a.type === 'element' && (a as parseXml.Element).name === 'var') as parseXml.Element[]; const params: VariableModel[] = nodes.map(n => { const value = n.attributes['value']; const type = n.attributes['type']; const name = n.attributes['name']; return { type: type ? type : ((value || '').split('(')[0]), name: n.attributes['name'], value: value }; }).filter(a => !!a.name && !!a.type && !!a.value); return params; } private resolveWidget(element: parseXml.Element, parent: parseXml.Element | null): WidgetResolveResult { let widget: WidgetModel = { type: element.name, controllers: [], vars: [], formControls: [], properties: [], wrappedWidgets: [], onResolved: [] }; // propertyElement const propertyElementResult = this.checkIfPropertyElement(element); widget.isPropertyElement = propertyElementResult.isPropertyElement; const propertyElementProperties: any[] = []; // *bug: XmlParser doesn't parse comments widget.comments = element.children.filter(a => a.type === 'comment').map(a => a as parseXml.Comment).map(a => a.content.trim()).filter(a => !!a); // children this.resolveChildren(element, widget, parent); // content child this.resolveContentChildData(element, widget); // properties const wrapperWidget = this.propertyResolver.resolveProperties(element, widget); // controllers widget.controllers = [...(widget.controllers || []), ...this.resolveControllers(widget.properties)]; // // property element e.g.: <AppBar.title></AppBar.title> or just <title></title> // if (propertyElementResult.isPropertyElement) { // unwrap widget propertyElementProperties.push(...widget.properties.filter(a => a.dataType !== 'widgetList' && a.dataType !== 'widget')); const widgetProp = widget.properties.filter(a => a.dataType === 'widgetList' || a.dataType === 'widget')[0]; const contentWidget = (widgetProp ? widgetProp.value as WidgetModel : null) as any; widget = contentWidget; } // replace widget with the wrap one if there is a wrapper if (wrapperWidget) { widget = wrapperWidget; } const result = { widget: widget, isPropertyElement: propertyElementResult.isPropertyElement, propertyElement: propertyElementResult.name, propertyElementProperties: propertyElementProperties }; return result; } private resolveChildren(element: parseXml.Element, widget: WidgetModel, parent: parseXml.Element | null) { const childrenWidgets: WidgetModel[] = []; const childrenElements = element.children.filter(a => a.type === 'element').map(a => a as parseXml.Element); for (const child of childrenElements) { const childResult = this.resolveWidget(child, element); if (!childResult) { continue; } if (childResult.isPropertyElement) { const widget = this.resolvePropertyElement(childResult, element, childrenElements, child); if (widget) { childrenWidgets.push(widget); } } else { // append element to children childrenWidgets.push(childResult.widget); } } const hasArrayAttribute = 'array' in element.attributes; // children & child properties if (childrenWidgets.length > 1 || hasArrayAttribute || this.hasChildrenProperty(element.name, parent ? parent.name : '')) { widget.properties.push({ dataType: 'widgetList', name: 'children', value: childrenWidgets }); } else if (childrenWidgets.length === 1) { widget.properties.push({ dataType: 'widget', name: 'child', value: childrenWidgets[0] }); } } private resolvePropertyElement(resolvedWidget: WidgetResolveResult, parentElement: parseXml.Element, parentChildrenElements: parseXml.Element[], childElement: parseXml.Element): WidgetModel | null { // check if we want to treat it as a custom element and not a property <if>...</if> const propertyHandler = this.propertyHandlerProvider.get(resolvedWidget.propertyElement); if (propertyHandler && propertyHandler.canResolvePropertyElement()) { const propertyElementWidget: WidgetModel | null = propertyHandler.resolvePropertyElement( childElement, resolvedWidget, parentElement, parentChildrenElements, (el, parent) => this.resolveWidget(el, parent)); if (propertyElementWidget) { resolvedWidget.isPropertyElement = false; return propertyElementWidget; } } else { // this child is a property element <title>...</title> this.addElementAsAttribute(parentElement, resolvedWidget); } return null; } private resolveContentChildData(element: parseXml.Element, widget: WidgetModel) { //e.g. <Text>content goes here</Text> const contentChild = element.children .filter(a => a.type === 'text' && (a as parseXml.Text).text.trimLeft().trimRight()) .map(a => a as parseXml.Text)[0]; // todo take all node and join them as one. if (contentChild) { const value = contentChild.text ? contentChild.text.trimLeft().trimRight() : ''; if (value && value !== '') { const result = this.propertyResolver.resolveProperty(element, '', value, widget, widget); widget.properties.push(result.property); } } } private addElementAsAttribute(element: parseXml.Element, childResult: { widget: WidgetModel, propertyElementProperties: any[], propertyElement: string }) { const attrValue = { dataType: childResult.widget instanceof Array ? 'widgetList' : 'widget', // name: childResult.propertyElement, value: childResult.widget, extraData: { properties: childResult.propertyElementProperties } }; if (element.attributes[childResult.propertyElement]) { // if the previous value is not an array, then make it an array. if (!(element.attributes[childResult.propertyElement] as any instanceof Array)) { element.attributes[childResult.propertyElement] = [element.attributes[childResult.propertyElement]] as any; } // append the new value to the array. (element.attributes[childResult.propertyElement] as any).push(attrValue); } else { element.attributes[childResult.propertyElement] = attrValue as any; } } private hasChildrenProperty(name: string, parentName: string): boolean { const elementsHaveChildren = [ 'Column', 'Row', 'ListView', 'GridView', 'Stack', 'Wrap', ...this.getWidgetsWithChildrenProperty() ]; let result = !!elementsHaveChildren.find(a => a === name); if (!result) { const arrayProperties: any = { 'DropdownButton': ['items'], 'CustomScrollView': ['slivers'] }; result = arrayProperties[parentName] && arrayProperties[parentName].filter((a: any) => a === name).length === 1 || !!this.config.arrayProperties && this.config.arrayProperties[parentName] && this.config.arrayProperties[parentName].filter(a => a === name).length === 1; } return result; } private getWidgetsWithChildrenProperty(): string[] { const items = this.config.arrayProperties || {}; return Object .keys(items) .filter(k => { return items[k].filter(a => a === 'children').length > 0; }); } private resolveControllers(properties: PropertyModel[]): VariableModel[] { const controllers = properties .filter(a => !!a.controller) .map(a => a.controller as any); return controllers; } private checkIfPropertyElement(element: parseXml.Element): { name: string, isPropertyElement: boolean } { const dotIndex = element.name.indexOf('.'); let childPropName = ''; let isPropertyElement = false; if (dotIndex > -1) { // example: <AppBar.body> childPropName = element.name.substring(dotIndex + 1); isPropertyElement = true; } else if (/[a-z]/.test(element.name[0])) { // example: <body> childPropName = element.name; isPropertyElement = true; } return { name: childPropName, isPropertyElement }; } }
the_stack
import { _backburner, run } from '@ember/runloop'; import { set, setProperties, get, getProperties } from '@ember/object'; import type Resolver from '@ember/application/resolver'; import { setOwner } from '@ember/application'; import buildOwner, { Owner } from './build-owner'; import { _setupAJAXHooks, _teardownAJAXHooks } from './settled'; import { _prepareOnerror } from './setup-onerror'; import Ember from 'ember'; import { assert, registerDeprecationHandler, registerWarnHandler, } from '@ember/debug'; import global from './global'; import { getResolver } from './resolver'; import { getApplication } from './application'; import { Promise } from './-utils'; import getTestMetadata, { ITestMetadata } from './test-metadata'; import { registerDestructor, associateDestroyableChild, } from '@ember/destroyable'; import { getDeprecationsForContext, getDeprecationsDuringCallbackForContext, DeprecationFailure, } from './-internal/deprecations'; import { getWarningsForContext, getWarningsDuringCallbackForContext, Warning, } from './-internal/warnings'; // This handler exists to provide the underlying data to enable the following methods: // * getDeprecations() // * getDeprecationsDuringCallback() // * getDeprecationsDuringCallbackForContext() registerDeprecationHandler((message, options, next) => { const context = getContext(); if (context === undefined) { return; } getDeprecationsForContext(context).push({ message, options }); next.apply(null, [message, options]); }); // This handler exists to provide the underlying data to enable the following methods: // * getWarnings() // * getWarningsDuringCallback() // * getWarningsDuringCallbackForContext() registerWarnHandler((message, options, next) => { const context = getContext(); if (context === undefined) { return; } getWarningsForContext(context).push({ message, options }); next.apply(null, [message, options]); }); export interface BaseContext { [key: string]: any; } export interface TestContext extends BaseContext { owner: Owner; set(key: string, value: any): any; setProperties(hash: { [key: string]: any }): { [key: string]: any }; get(key: string): any; getProperties(...args: string[]): Pick<BaseContext, string>; pauseTest(): Promise<void>; resumeTest(): Promise<void>; } // eslint-disable-next-line require-jsdoc export function isTestContext(context: BaseContext): context is TestContext { return ( typeof context.pauseTest === 'function' && typeof context.resumeTest === 'function' ); } let __test_context__: BaseContext | undefined; /** Stores the provided context as the "global testing context". Generally setup automatically by `setupContext`. @public @param {Object} context the context to use */ export function setContext(context: BaseContext): void { __test_context__ = context; } /** Retrive the "global testing context" as stored by `setContext`. @public @returns {Object} the previously stored testing context */ export function getContext(): BaseContext | undefined { return __test_context__; } /** Clear the "global testing context". Generally invoked from `teardownContext`. @public */ export function unsetContext(): void { __test_context__ = undefined; } /** * Returns a promise to be used to pauses the current test (due to being * returned from the test itself). This is useful for debugging while testing * or for test-driving. It allows you to inspect the state of your application * at any point. * * The test framework wrapper (e.g. `ember-qunit` or `ember-mocha`) should * ensure that when `pauseTest()` is used, any framework specific test timeouts * are disabled. * * @public * @returns {Promise<void>} resolves _only_ when `resumeTest()` is invoked * @example <caption>Usage via ember-qunit</caption> * * import { setupRenderingTest } from 'ember-qunit'; * import { render, click, pauseTest } from '@ember/test-helpers'; * * * module('awesome-sauce', function(hooks) { * setupRenderingTest(hooks); * * test('does something awesome', async function(assert) { * await render(hbs`{{awesome-sauce}}`); * * // added here to visualize / interact with the DOM prior * // to the interaction below * await pauseTest(); * * click('.some-selector'); * * assert.equal(this.element.textContent, 'this sauce is awesome!'); * }); * }); */ export function pauseTest(): Promise<void> { let context = getContext(); if (!context || !isTestContext(context)) { throw new Error( 'Cannot call `pauseTest` without having first called `setupTest` or `setupRenderingTest`.' ); } return context.pauseTest(); } /** Resumes a test previously paused by `await pauseTest()`. @public */ export function resumeTest(): void { let context = getContext(); if (!context || !isTestContext(context)) { throw new Error( 'Cannot call `resumeTest` without having first called `setupTest` or `setupRenderingTest`.' ); } context.resumeTest(); } /** @private @param {Object} context the test context being cleaned up */ function cleanup(context: BaseContext) { _teardownAJAXHooks(); (Ember as any).testing = false; unsetContext(); // this should not be required, but until https://github.com/emberjs/ember.js/pull/19106 // lands in a 3.20 patch release context.owner.destroy(); } /** * Returns deprecations which have occured so far for a the current test context * * @public * @returns {Array<DeprecationFailure>} An array of deprecation messages * @example <caption>Usage via ember-qunit</caption> * * import { getDeprecations } from '@ember/test-helpers'; * * module('awesome-sauce', function(hooks) { * setupRenderingTest(hooks); * * test('does something awesome', function(assert) { const deprecations = getDeprecations() // => returns deprecations which have occured so far in this test * }); * }); */ export function getDeprecations(): Array<DeprecationFailure> { const context = getContext(); if (!context) { throw new Error( '[@ember/test-helpers] could not get deprecations if no test context is currently active' ); } return getDeprecationsForContext(context); } /** * Returns deprecations which have occured so far for a the current test context * * @public * @param {CallableFunction} [callback] The callback that when executed will have its DeprecationFailure recorded * @returns {Array<DeprecationFailure> | Promise<Array<DeprecationFailure>>} An array of deprecation messages * @example <caption>Usage via ember-qunit</caption> * * import { getDeprecationsDuringCallback } from '@ember/test-helpers'; * * module('awesome-sauce', function(hooks) { * setupRenderingTest(hooks); * * test('does something awesome', function(assert) { * const deprecations = getDeprecationsDuringCallback(() => { * // code that might emit some deprecations * * }); // => returns deprecations which occured while the callback was invoked * }); * * * test('does something awesome', async function(assert) { * const deprecations = await getDeprecationsDuringCallback(async () => { * // awaited code that might emit some deprecations * }); // => returns deprecations which occured while the callback was invoked * }); * }); */ export function getDeprecationsDuringCallback( callback: CallableFunction ): Array<DeprecationFailure> | Promise<Array<DeprecationFailure>> { const context = getContext(); if (!context) { throw new Error( '[@ember/test-helpers] could not get deprecations if no test context is currently active' ); } return getDeprecationsDuringCallbackForContext(context, callback); } /** * Returns warnings which have occured so far for a the current test context * * @public * @returns {Array<Warning>} An array of warnings * @example <caption>Usage via ember-qunit</caption> * * import { getWarnings } from '@ember/test-helpers'; * * module('awesome-sauce', function(hooks) { * setupRenderingTest(hooks); * * test('does something awesome', function(assert) { const warnings = getWarnings() // => returns warnings which have occured so far in this test * }); * }); */ export function getWarnings(): Array<Warning> { const context = getContext(); if (!context) { throw new Error( '[@ember/test-helpers] could not get warnings if no test context is currently active' ); } return getWarningsForContext(context); } /** * Returns warnings which have occured so far for a the current test context * * @public * @param {CallableFunction} [callback] The callback that when executed will have its warnings recorded * @returns {Array<Warning> | Promise<Array<Warning>>} An array of warnings information * @example <caption>Usage via ember-qunit</caption> * * import { getWarningsDuringCallback } from '@ember/test-helpers'; * import { warn } from '@ember/debug'; * * module('awesome-sauce', function(hooks) { * setupRenderingTest(hooks); * * test('does something awesome', function(assert) { * const warnings = getWarningsDuringCallback(() => { * warn('some warning'); * * }); // => returns warnings which occured while the callback was invoked * }); * * test('does something awesome', async function(assert) { * warn('some warning'); * * const warnings = await getWarningsDuringCallback(async () => { * warn('some other warning'); * }); // => returns warnings which occured while the callback was invoked * }); * }); */ export function getWarningsDuringCallback( callback: CallableFunction ): Array<Warning> | Promise<Array<Warning>> { const context = getContext(); if (!context) { throw new Error( '[@ember/test-helpers] could not get warnings if no test context is currently active' ); } return getWarningsDuringCallbackForContext(context, callback); } /** Used by test framework addons to setup the provided context for testing. Responsible for: - sets the "global testing context" to the provided context (`setContext`) - create an owner object and set it on the provided context (e.g. `this.owner`) - setup `this.set`, `this.setProperties`, `this.get`, and `this.getProperties` to the provided context - setting up AJAX listeners - setting up `pauseTest` (also available as `this.pauseTest()`) and `resumeTest` helpers @public @param {Object} context the context to setup @param {Object} [options] options used to override defaults @param {Resolver} [options.resolver] a resolver to use for customizing normal resolution @returns {Promise<Object>} resolves with the context that was setup */ export default function setupContext( context: BaseContext, options: { resolver?: Resolver } = {} ): Promise<TestContext> { (Ember as any).testing = true; setContext(context); let testMetadata: ITestMetadata = getTestMetadata(context); testMetadata.setupTypes.push('setupContext'); _backburner.DEBUG = true; registerDestructor(context, cleanup); _prepareOnerror(context); return Promise.resolve() .then(() => { let application = getApplication(); if (application) { return application.boot().then(() => {}); } return; }) .then(() => { let { resolver } = options; // This handles precendence, specifying a specific option of // resolver always trumps whatever is auto-detected, then we fallback to // the suite-wide registrations // // At some later time this can be extended to support specifying a custom // engine or application... if (resolver) { return buildOwner(null, resolver); } return buildOwner(getApplication(), getResolver()); }) .then((owner) => { associateDestroyableChild(context, owner); Object.defineProperty(context, 'owner', { configurable: true, enumerable: true, value: owner, writable: false, }); setOwner(context, owner); Object.defineProperty(context, 'set', { configurable: true, enumerable: true, value(key: string, value: any): any { let ret = run(function () { return set(context, key, value); }); return ret; }, writable: false, }); Object.defineProperty(context, 'setProperties', { configurable: true, enumerable: true, value(hash: { [key: string]: any }): { [key: string]: any } { let ret = run(function () { return setProperties(context, hash); }); return ret; }, writable: false, }); Object.defineProperty(context, 'get', { configurable: true, enumerable: true, value(key: string): any { return get(context, key); }, writable: false, }); Object.defineProperty(context, 'getProperties', { configurable: true, enumerable: true, value(...args: string[]): Pick<BaseContext, string> { return getProperties(context, args); }, writable: false, }); let resume: Function | undefined; context.resumeTest = function resumeTest() { assert( 'Testing has not been paused. There is nothing to resume.', Boolean(resume) ); (resume as Function)(); global.resumeTest = resume = undefined; }; context.pauseTest = function pauseTest() { console.info('Testing paused. Use `resumeTest()` to continue.'); // eslint-disable-line no-console return new Promise((resolve) => { resume = resolve; global.resumeTest = resumeTest; }); }; _setupAJAXHooks(); return context as TestContext; }); }
the_stack
import type { FullResourceLocation, ProcessorContext } from '@spyglassmc/core' import { Arrayable } from '@spyglassmc/core' import { localeQuote, localize } from '@spyglassmc/locales' import type { EnumKind } from '../node/index.js' export interface Attribute { name: string, value: AttributeValue, } export type AttributeValue = McdocType | AttributeTree export type AttributeTree = { [key: string | number]: AttributeValue } export type NumericRange = [number | undefined, number | undefined] export const StaticIndexKeywords = Object.freeze(['fallback', 'none', 'unknown'] as const) export type StaticIndexKeyword = typeof StaticIndexKeywords[number] export interface StaticIndex { kind: 'static', value: string, } export interface DynamicIndex { kind: 'dynamic', accessor: (string | { keyword: 'key' | 'parent' })[] } export type Index = StaticIndex | DynamicIndex /** * Corresponds to the IndexBodyNode */ export type ParallelIndices = Index[] export interface DispatcherData { registry: FullResourceLocation, index: ParallelIndices, } export interface TypeBase { kind: string, attributes?: Attribute[], indices?: ParallelIndices[], } export interface DispatcherType extends TypeBase, DispatcherData { kind: 'dispatcher', } export interface StructType extends TypeBase { kind: 'struct', fields: StructTypeField[] } export type StructTypeField = StructTypePairField | StructTypeSpreadField export interface StructTypePairField { kind: 'pair', key: string | McdocType, type: McdocType, } export interface StructTypeSpreadField { kind: 'spread', attributes?: Attribute[], type: McdocType, } export interface EnumType extends TypeBase { kind: 'enum', enumKind?: EnumKind, values: EnumTypeField[], } export interface EnumTypeField { attributes?: Attribute[], identifier: string, value: string | number | bigint, } export interface ReferenceType extends TypeBase { kind: 'reference', path?: string, typeParameters?: McdocType[], } export interface UnionType<T extends McdocType = McdocType> extends TypeBase { kind: 'union', members: T[], } export const EmptyUnion: UnionType<never> & NoIndices = Object.freeze({ kind: 'union', members: [] }) export function createEmptyUnion(attributes?: Attribute[]): UnionType<never> & NoIndices { return { ...EmptyUnion, attributes, } } export interface KeywordType extends TypeBase { kind: 'any' | 'boolean', } export interface StringType extends TypeBase { kind: 'string', lengthRange?: NumericRange, } export type LiteralValue = { kind: 'boolean', value: boolean, } | { kind: 'string', value: string, } | { kind: 'number', value: number, suffix: 'b' | 's' | 'l' | 'f' | 'd' | undefined, } export interface LiteralType extends TypeBase { kind: 'literal', value: LiteralValue, } export const LiteralNumberSuffixes = Object.freeze(['b', 's', 'l', 'f', 'd'] as const) export type LiteralNumberSuffix = typeof LiteralNumberSuffixes[number] export const LiteralNumberCaseInsensitiveSuffixes = Object.freeze([...LiteralNumberSuffixes, 'B', 'S', 'L', 'F', 'D'] as const) export type LiteralNumberCaseInsensitiveSuffix = typeof LiteralNumberCaseInsensitiveSuffixes[number] export interface NumericType extends TypeBase { kind: NumericTypeKind, valueRange?: NumericRange, } export const NumericTypeIntKinds = Object.freeze(['byte', 'short', 'int', 'long'] as const) export type NumericTypeIntKind = typeof NumericTypeIntKinds[number] export const NumericTypeFloatKinds = Object.freeze(['float', 'double'] as const) export type NumericTypeFloatKind = typeof NumericTypeFloatKinds[number] export const NumericTypeKinds = Object.freeze([...NumericTypeIntKinds, ...NumericTypeFloatKinds] as const) export type NumericTypeKind = typeof NumericTypeKinds[number] export interface PrimitiveArrayType extends TypeBase { kind: 'byte_array' | 'int_array' | 'long_array', valueRange?: NumericRange, lengthRange?: NumericRange, } export const PrimitiveArrayValueKinds = Object.freeze(['byte', 'int', 'long'] as const) export type PrimitiveArrayValueKind = typeof PrimitiveArrayValueKinds[number] export const PrimitiveArrayKinds = Object.freeze(PrimitiveArrayValueKinds.map(kind => `${kind}_array` as const)) export type PrimitiveArrayKind = typeof PrimitiveArrayKinds[number] export interface ListType extends TypeBase { kind: 'list', item: McdocType, lengthRange?: NumericRange, } export interface TupleType extends TypeBase { kind: 'tuple', items: McdocType[], } export type McdocType = | DispatcherType | EnumType | KeywordType | ListType | LiteralType | NumericType | PrimitiveArrayType | ReferenceType | StringType | StructType | TupleType | UnionType export namespace McdocType { export function toString(type: McdocType | undefined): string { const rangeToString = (range: NumericRange | undefined): string => { if (!range) { return '' } const [min, max] = range return min === max ? ` @ ${min}` : ` @ ${min ?? ''}..${max ?? ''}` } const indicesToString = (indices: Arrayable<Index | undefined>): string => { const strings: string[] = [] for (const index of Arrayable.toArray(indices)) { if (index === undefined) { strings.push('()') } else { strings.push(index.kind === 'static' ? `[${index.value}]` : `[[${index.accessor.map(v => typeof v === 'string' ? v : v.keyword).join('.')}]]` ) } } return `[${strings.join(', ')}]` } if (type === undefined) { return '<unknown>' } switch (type.kind) { case 'any': case 'boolean': return type.kind case 'byte': return `byte${rangeToString(type.valueRange)}` case 'byte_array': return `byte${rangeToString(type.valueRange)}[]${rangeToString(type.lengthRange)}` case 'dispatcher': return `${type.registry ?? 'spyglass:unknown'}[${indicesToString(type.index)}]` case 'double': return `double${rangeToString(type.valueRange)}` case 'enum': return '<anonymous_enum>' case 'float': return `float${rangeToString(type.valueRange)}` case 'int': return `int${rangeToString(type.valueRange)}` case 'int_array': return `int${rangeToString(type.valueRange)}[]${rangeToString(type.lengthRange)}` case 'list': return `[${toString(type.item)}]${rangeToString(type.lengthRange)}` case 'literal': return `${type.value}` case 'long': return `long${rangeToString(type.valueRange)}` case 'long_array': return `long${rangeToString(type.valueRange)}[]${rangeToString(type.lengthRange)}` case 'reference': return type.path ?? '<unknown_reference>' case 'short': return `short${rangeToString(type.valueRange)}` case 'string': return `string${rangeToString(type.lengthRange)}` case 'struct': return '<anonymous_compound>' case 'tuple': return `[${type.items.map(v => toString(v)).join(',')}${type.items.length === 1 ? ',' : ''}]` case 'union': return `(${type.members.map(toString).join(' | ')})` } } } /** * A type that doesn't include a dispatcher type. */ export type DispatchedType = Exclude<McdocType, DispatcherType | UnionType> | UnionType<DispatchedType> /** * A type that doesn't include a reference type. */ export type DereferencedType = Exclude<McdocType, ReferenceType | UnionType> | UnionType<DereferencedType> /** * A type that doesn't include a dispatcher type or a reference type. */ export type TangibleType = Exclude<McdocType, DispatcherType | ReferenceType | UnionType> | UnionType<TangibleType> /** * A type that is {@link TangibleType} and doesn't have any indices. */ export type ResolvedType = (Exclude<McdocType, DispatcherType | ReferenceType | UnionType> | UnionType<ResolvedType>) & NoIndices type NoIndices = { indices?: undefined } export interface FlatStructType extends TypeBase { kind: 'flat_struct', fields: Record<string, McdocType>, } enum CheckResult { Nah = 0b00, Assignable = 0b01, StrictlyAssignable = 0b11, } const areRangesMatch = (s: NumericRange | undefined, t: NumericRange | undefined): boolean => { if (!t) { return true } if (!s) { return false } const [sMin, sMax] = s const [tMin, tMax] = t return (tMin === undefined || (sMin !== undefined && sMin >= tMin)) && (tMax === undefined || (sMax !== undefined && sMax <= tMax)) } export const flattenUnionType = (union: UnionType): UnionType => { const set = new Set<McdocType>() const add = (data: McdocType): void => { for (const existingMember of set) { if ((check(data, existingMember) & CheckResult.StrictlyAssignable) === CheckResult.StrictlyAssignable) { return } if ((check(existingMember, data) & CheckResult.StrictlyAssignable) === CheckResult.StrictlyAssignable) { set.delete(existingMember) } } set.add(data) } for (const member of union.members) { if (member.kind === 'union') { flattenUnionType(member).members.forEach(add) } else { add(member) } } return { kind: 'union', members: [...set], } } export const unionTypes = (a: McdocType, b: McdocType): McdocType => { if ((check(a, b) & CheckResult.StrictlyAssignable) === CheckResult.StrictlyAssignable) { return b } if ((check(b, a) & CheckResult.StrictlyAssignable) === CheckResult.StrictlyAssignable) { return a } const ans: UnionType = { kind: 'union', members: [ ...a.kind === 'union' ? a.members : [a], ...b.kind === 'union' ? b.members : [b], ], } return ans } export const simplifyUnionType = (union: UnionType): McdocType => { union = flattenUnionType(union) if (union.members.length === 1) { return union.members[0] } return union } export const simplifyListType = (list: ListType): ListType => ({ kind: 'list', item: simplifyType(list.item), ...list.lengthRange ? { lengthRange: [...list.lengthRange] } : {}, }) export const simplifyType = (data: McdocType): McdocType => { if (data.kind === 'union') { data = simplifyUnionType(data) } else if (data.kind === 'list') { data = simplifyListType(data) } return data } const check = (s: McdocType, t: McdocType, errors: string[] = []): CheckResult => { const strictlyAssignableIfTrue = (value: boolean): CheckResult => value ? CheckResult.StrictlyAssignable : CheckResult.Nah const assignableIfTrue = (value: boolean): CheckResult => value ? CheckResult.Assignable : CheckResult.Nah let ans: CheckResult s = simplifyType(s) t = simplifyType(t) if (s.kind === 'any' || s.kind === 'reference' || t.kind === 'reference') { // Reference types are treated as any for now. ans = CheckResult.Assignable } else if (t.kind === 'any') { ans = CheckResult.StrictlyAssignable } else if (s.kind === 'union') { ans = assignableIfTrue(s.members.every(v => check(v, t, errors))) } else if (t.kind === 'union') { ans = assignableIfTrue(t.members.some(v => check(s, v))) } else if (s.kind === 'boolean') { ans = strictlyAssignableIfTrue(t.kind === 'boolean' || t.kind === 'byte') } else if (s.kind === 'byte') { if (t.kind === 'boolean') { ans = check(s, { kind: 'byte', valueRange: [0, 1] }, errors) } else if (t.kind === 'byte') { ans = strictlyAssignableIfTrue(areRangesMatch(s.valueRange, t.valueRange)) } else if (t.kind === 'enum') { ans = assignableIfTrue(!t.enumKind || t.enumKind === 'byte') } else { ans = CheckResult.Nah } } else if (s.kind === 'byte_array' || s.kind === 'int_array' || s.kind === 'long_array') { ans = strictlyAssignableIfTrue(t.kind === s.kind && areRangesMatch(s.lengthRange, t.lengthRange) && areRangesMatch(s.valueRange, t.valueRange)) } else if (s.kind === 'struct' || s.kind === 'dispatcher') { ans = assignableIfTrue(t.kind === 'struct' || t.kind === 'dispatcher') } else if (s.kind === 'enum') { ans = assignableIfTrue((t.kind === 'byte' || t.kind === 'float' || t.kind === 'double' || t.kind === 'int' || t.kind === 'long' || t.kind === 'short' || t.kind === 'string') && (!s.enumKind || s.enumKind === t.kind)) } else if (s.kind === 'float' || s.kind === 'double' || s.kind === 'int' || s.kind === 'long' || s.kind === 'short') { if (t.kind === s.kind) { ans = strictlyAssignableIfTrue(areRangesMatch(s.valueRange, t.valueRange)) } else if (t.kind === 'enum') { ans = assignableIfTrue(!t.enumKind || t.enumKind === s.kind) } else { ans = CheckResult.Nah } } else if (s.kind === 'list') { if (t.kind === 'list' && areRangesMatch(s.lengthRange, t.lengthRange)) { ans = check(s.item, t.item, errors) } else { ans = CheckResult.Nah } } else if (s.kind === 'string') { if (t.kind === 'string') { ans = CheckResult.StrictlyAssignable } else { ans = assignableIfTrue(t.kind === 'enum' && (!t.enumKind || t.enumKind === 'string')) } } else { ans = CheckResult.Nah } if (!ans) { errors.push(localize('mcdoc.checker.type-not-assignable', localeQuote(McdocType.toString(s)), localeQuote(McdocType.toString(t)) )) } return ans } export const checkAssignability = ({ source, target }: { source: McdocType | undefined, target: McdocType | undefined }): { isAssignable: boolean, errorMessage?: string, } => { if (source === undefined || target === undefined) { return { isAssignable: true } } const errors: string[] = [] check(source, target, errors) return { isAssignable: errors.length === 0, ...errors.length ? { errorMessage: errors.reverse().map((m, i) => `${' '.repeat(i)}${m}`).join('\n') } : {}, } } /** * https://spyglassmc.com/user/mcdoc/#p-RuntimeValue */ export interface RuntimeValue { asString(): string | undefined getKeyOnParent(): RuntimeValue | undefined getParent(): RuntimeValue | undefined getValue(key: string): RuntimeValue | undefined } export function resolveType(inputType: McdocType, ctx: ProcessorContext, value: RuntimeValue | undefined): ResolvedType { const type = getTangibleType(inputType, ctx, value) let ans: ResolvedType = ((): ResolvedType => { if (type.kind === 'union') { return { kind: 'union', members: type.members.map(t => resolveType(t, ctx, value)), attributes: type.attributes, } } else { return { ...type, indices: undefined, } } })() for (const parallelIndices of type.indices ?? []) { ans = navigateParallelIndices(ans, parallelIndices, ctx, value) } return ans } function dispatchType(type: DispatcherType, ctx: ProcessorContext): DispatchedType { throw '// TODO' } function dereferenceType(type: ReferenceType, ctx: ProcessorContext): DereferencedType { throw '// TODO' } function getTangibleType(type: McdocType, ctx: ProcessorContext, value: RuntimeValue | undefined): TangibleType { let ans: TangibleType if (type.kind === 'dispatcher') { const dispatchedType = dispatchType(type, ctx) return getTangibleType(dispatchedType, ctx, value) } else if (type.kind === 'reference') { const dereferencedType = dereferenceType(type, ctx) return getTangibleType(dereferencedType, ctx, value) } else if (type.kind === 'union') { ans = mapUnion(type, t => getTangibleType(t, ctx, value)) } else { ans = type } return ans } function navigateParallelIndices(type: ResolvedType, indices: ParallelIndices, ctx: ProcessorContext, value: RuntimeValue | undefined): ResolvedType { if (indices.length === 1) { return navigateIndex(type, indices[0], ctx, value) } else { return { kind: 'union', members: indices.map(i => navigateIndex(type, i, ctx, value)), attributes: type.attributes, } } } function navigateIndex(type: ResolvedType, index: Index, ctx: ProcessorContext, value: RuntimeValue | undefined): ResolvedType { if (type.kind === 'struct') { const key = index.kind === 'static' ? typeof index.value === 'string' ? index.value : undefined // Special static indices have no meaning on structs. : resolveDynamicIndex(index, value) if (key === undefined) { return createEmptyUnion(type.attributes) } const flatStruct = flattenStruct(type, ctx, value) return resolveType(flatStruct.fields[key], ctx, value) } else if (type.kind === 'union') { return mapUnion(type, t => navigateIndex(t, index, ctx, value)) } else { return createEmptyUnion(type.attributes) } } function resolveDynamicIndex(index: DynamicIndex, value: RuntimeValue | undefined): string | undefined { for (const key of index.accessor) { if (value === undefined) { break } if (typeof key === 'string') { value = value.getValue(key) } else if (key.keyword === 'key') { value = value.getKeyOnParent() } else if (key.keyword === 'parent') { value = value.getParent() } } return value?.asString() } function mapUnion<T extends McdocType, U extends McdocType>(type: UnionType<T> & NoIndices, mapper: (this: void, t: T) => U): UnionType<U> & NoIndices function mapUnion<T extends McdocType, U extends McdocType>(type: UnionType<T>, mapper: (this: void, t: T) => U): UnionType<U> function mapUnion<T extends McdocType, U extends McdocType>(type: UnionType<T>, mapper: (this: void, t: T) => U): UnionType<U> { const ans: UnionType<U> = { kind: 'union', members: type.members.map(mapper), attributes: type.attributes, indices: type.indices, } return ans } function flattenStruct(type: StructType & NoIndices, ctx: ProcessorContext, value: RuntimeValue | undefined): FlatStructType & NoIndices function flattenStruct(type: StructType, ctx: ProcessorContext, value: RuntimeValue | undefined): FlatStructType function flattenStruct(type: StructType, ctx: ProcessorContext, value: RuntimeValue | undefined): FlatStructType { const ans: FlatStructType = { kind: 'flat_struct', fields: Object.create(null), attributes: type.attributes, indices: type.indices, } for (const field of type.fields) { if (field.kind === 'spread') { const target = resolveType(field.type, ctx, value) addAttributes(ans, ...target.attributes ?? []) if (target.kind === 'struct') { const flatTarget = flattenStruct(target, ctx, value) for (const [key, value] of Object.entries(flatTarget)) { ans.fields[key] = value } } } else { if (typeof field.key === 'string') { ans.fields[field.key] = field.type } else { // TODO: Handle map keys } } } return ans } function addAttributes(type: TypeBase, ...attributes: Attribute[]): void { for (const attr of attributes) { type.attributes ??= [] if (!type.attributes.some(a => a.name === attr.name)) { type.attributes.push(attr) } } }
the_stack
import { catchError, concat as observableConcat, EMPTY, ignoreElements, map, mapTo, merge as observableMerge, mergeMap, Observable, of as observableOf, ReplaySubject, startWith, switchMap, take, } from "rxjs"; import config from "../../../config"; import { formatError } from "../../../errors"; import log from "../../../log"; import Manifest, { Adaptation, Period, } from "../../../manifest"; import objectAssign from "../../../utils/object_assign"; import { getLeftSizeOfRange } from "../../../utils/ranges"; import { IReadOnlySharedReference } from "../../../utils/reference"; import WeakMapMemory from "../../../utils/weak_map_memory"; import ABRManager from "../../abr"; import { SegmentFetcherCreator } from "../../fetchers"; import SegmentBuffersStore, { IBufferType, ITextTrackSegmentBufferOptions, SegmentBuffer, } from "../../segment_buffers"; import AdaptationStream, { IAdaptationStreamOptions, } from "../adaptation"; import EVENTS from "../events_generators"; import reloadAfterSwitch from "../reload_after_switch"; import { IAdaptationStreamEvent, IPeriodStreamEvent, IStreamWarningEvent, } from "../types"; import createEmptyStream from "./create_empty_adaptation_stream"; import getAdaptationSwitchStrategy from "./get_adaptation_switch_strategy"; const { DELTA_POSITION_AFTER_RELOAD } = config; export interface IPeriodStreamClockTick { position : number; // the position we are in the video in s at the time of the tic getCurrentTime : () => number; // fetch the current time duration : number; // duration of the HTMLMediaElement isPaused: boolean; // If true, the player is on pause liveGap? : number; // gap between the current position and the edge of a // live content. Not set for non-live contents readyState : number; // readyState of the HTMLMediaElement speed : number; // playback rate at which the content plays wantedTimeOffset : number; // offset in s to add to the time to obtain the // position we actually want to download from } export interface IPeriodStreamArguments { abrManager : ABRManager; bufferType : IBufferType; clock$ : Observable<IPeriodStreamClockTick>; content : { manifest : Manifest; period : Period; }; garbageCollectors : WeakMapMemory<SegmentBuffer, Observable<never>>; segmentFetcherCreator : SegmentFetcherCreator; segmentBuffersStore : SegmentBuffersStore; options: IPeriodStreamOptions; wantedBufferAhead : IReadOnlySharedReference<number>; } /** Options tweaking the behavior of the PeriodStream. */ export type IPeriodStreamOptions = IAdaptationStreamOptions & { /** * Strategy to adopt when manually switching of audio adaptation. * Can be either: * - "seamless": transitions are smooth but could be not immediate. * - "direct": strategy will be "smart", if the mimetype and the codec, * change, we will perform a hard reload of the media source, however, if it * doesn't change, we will just perform a small flush by removing buffered range * and performing, a small seek on the media element. * Transitions are faster, but, we could see appear a reloading or seeking state. */ audioTrackSwitchingMode : "seamless" | "direct"; /** Behavior when a new video and/or audio codec is encountered. */ onCodecSwitch : "continue" | "reload"; /** Options specific to the text SegmentBuffer. */ textTrackOptions? : ITextTrackSegmentBufferOptions; }; /** * Create single PeriodStream Observable: * - Lazily create (or reuse) a SegmentBuffer for the given type. * - Create a Stream linked to an Adaptation each time it changes, to * download and append the corresponding segments to the SegmentBuffer. * - Announce when the Stream is full or is awaiting new Segments through * events * @param {Object} args * @returns {Observable} */ export default function PeriodStream({ abrManager, bufferType, clock$, content, garbageCollectors, segmentFetcherCreator, segmentBuffersStore, options, wantedBufferAhead, } : IPeriodStreamArguments) : Observable<IPeriodStreamEvent> { const { period } = content; // Emits the chosen Adaptation for the current type. // `null` when no Adaptation is chosen (e.g. no subtitles) const adaptation$ = new ReplaySubject<Adaptation|null>(1); return adaptation$.pipe( switchMap(( adaptation : Adaptation | null, switchNb : number ) : Observable<IPeriodStreamEvent> => { /** * If this is not the first Adaptation choice, we might want to apply a * delta to the current position so we can re-play back some media in the * new Adaptation to give some context back. * This value contains this relative position, in seconds. * @see reloadAfterSwitch */ const relativePosAfterSwitch = switchNb === 0 ? 0 : bufferType === "audio" ? DELTA_POSITION_AFTER_RELOAD.trackSwitch.audio : bufferType === "video" ? DELTA_POSITION_AFTER_RELOAD.trackSwitch.video : DELTA_POSITION_AFTER_RELOAD.trackSwitch.other; if (adaptation === null) { // Current type is disabled for that Period log.info(`Stream: Set no ${bufferType} Adaptation`, period); const segmentBufferStatus = segmentBuffersStore.getStatus(bufferType); let cleanBuffer$ : Observable<unknown>; if (segmentBufferStatus.type === "initialized") { log.info(`Stream: Clearing previous ${bufferType} SegmentBuffer`); if (SegmentBuffersStore.isNative(bufferType)) { return reloadAfterSwitch(period, bufferType, clock$, 0); } cleanBuffer$ = segmentBufferStatus.value .removeBuffer(period.start, period.end == null ? Infinity : period.end); } else { if (segmentBufferStatus.type === "uninitialized") { segmentBuffersStore.disableSegmentBuffer(bufferType); } cleanBuffer$ = observableOf(null); } return observableConcat( cleanBuffer$.pipe(mapTo(EVENTS.adaptationChange(bufferType, null, period))), createEmptyStream(clock$, wantedBufferAhead, bufferType, { period }) ); } if (SegmentBuffersStore.isNative(bufferType) && segmentBuffersStore.getStatus(bufferType).type === "disabled") { return reloadAfterSwitch(period, bufferType, clock$, relativePosAfterSwitch); } log.info(`Stream: Updating ${bufferType} adaptation`, adaptation, period); const newStream$ = clock$.pipe( take(1), mergeMap((tick) => { const segmentBuffer = createOrReuseSegmentBuffer(segmentBuffersStore, bufferType, adaptation, options); const playbackInfos = { currentTime: tick.getCurrentTime(), readyState: tick.readyState }; const strategy = getAdaptationSwitchStrategy(segmentBuffer, period, adaptation, playbackInfos, options); if (strategy.type === "needs-reload") { return reloadAfterSwitch(period, bufferType, clock$, relativePosAfterSwitch); } const needsBufferFlush$ = strategy.type === "flush-buffer" ? observableOf(EVENTS.needsBufferFlush()) : EMPTY; const cleanBuffer$ = strategy.type === "clean-buffer" || strategy.type === "flush-buffer" ? observableConcat(...strategy.value.map(({ start, end }) => segmentBuffer.removeBuffer(start, end)) ).pipe(ignoreElements()) : EMPTY; const bufferGarbageCollector$ = garbageCollectors.get(segmentBuffer); const adaptationStream$ = createAdaptationStream(adaptation, segmentBuffer); return segmentBuffersStore.waitForUsableBuffers().pipe(mergeMap(() => { return observableConcat(cleanBuffer$, needsBufferFlush$, observableMerge(adaptationStream$, bufferGarbageCollector$)); })); })); return observableConcat( observableOf(EVENTS.adaptationChange(bufferType, adaptation, period)), newStream$ ); }), startWith(EVENTS.periodStreamReady(bufferType, period, adaptation$)) ); /** * @param {Object} adaptation * @param {Object} segmentBuffer * @returns {Observable} */ function createAdaptationStream( adaptation : Adaptation, segmentBuffer : SegmentBuffer ) : Observable<IAdaptationStreamEvent|IStreamWarningEvent> { const { manifest } = content; const adaptationStreamClock$ = clock$.pipe(map(tick => { const buffered = segmentBuffer.getBufferedRanges(); return objectAssign({}, tick, { bufferGap: getLeftSizeOfRange(buffered, tick.position) }); })); return AdaptationStream({ abrManager, clock$: adaptationStreamClock$, content: { manifest, period, adaptation }, options, segmentBuffer, segmentFetcherCreator, wantedBufferAhead }).pipe( catchError((error : unknown) => { // Stream linked to a non-native media buffer should not impact the // stability of the player. ie: if a text buffer sends an error, we want // to continue playing without any subtitles if (!SegmentBuffersStore.isNative(bufferType)) { log.error(`Stream: ${bufferType} Stream crashed. Aborting it.`, error); segmentBuffersStore.disposeSegmentBuffer(bufferType); const formattedError = formatError(error, { defaultCode: "NONE", defaultReason: "Unknown `AdaptationStream` error", }); return observableConcat( observableOf(EVENTS.warning(formattedError)), createEmptyStream(clock$, wantedBufferAhead, bufferType, { period }) ); } log.error(`Stream: ${bufferType} Stream crashed. Stopping playback.`, error); throw error; })); } } /** * @param {string} bufferType * @param {Object} adaptation * @returns {Object} */ function createOrReuseSegmentBuffer( segmentBuffersStore : SegmentBuffersStore, bufferType : IBufferType, adaptation : Adaptation, options: { textTrackOptions? : ITextTrackSegmentBufferOptions } ) : SegmentBuffer { const segmentBufferStatus = segmentBuffersStore.getStatus(bufferType); if (segmentBufferStatus.type === "initialized") { log.info("Stream: Reusing a previous SegmentBuffer for the type", bufferType); // eslint-disable-next-line @typescript-eslint/no-unsafe-return return segmentBufferStatus.value; } const codec = getFirstDeclaredMimeType(adaptation); const sbOptions = bufferType === "text" ? options.textTrackOptions : undefined; // eslint-disable-next-line @typescript-eslint/no-unsafe-return return segmentBuffersStore.createSegmentBuffer(bufferType, codec, sbOptions); } /** * Get mime-type string of the first representation declared in the given * adaptation. * @param {Adaptation} adaptation * @returns {string} */ function getFirstDeclaredMimeType(adaptation : Adaptation) : string { const { representations } = adaptation; if (representations[0] == null) { return ""; } return representations[0].getMimeTypeString(); }
the_stack
import React, { ChangeEvent, MouseEvent, FocusEvent, ReactNode, ElementType } from 'react'; import shallowEqual from 'shallowequal'; import { debounce } from 'debounce'; import { nanoid } from 'nanoid'; import { CommonProps, DaDataSuggestion } from './types'; import { makeRequest } from './request'; export type BaseProps<SuggestionType> = CommonProps<SuggestionType>; export interface BaseState<SuggestionType> { /** * Текущая строка в поле ввода */ query: string; displaySuggestions: boolean; /** * Оригинальная строка в поле поиска, требуется для хранения значения в момент переключения подсказок стрелками */ inputQuery: string; /** * Находится ли сейчас фокус в поле ввода */ isFocused: boolean; /** * Массив с текущими подсказками */ suggestions: Array<DaDataSuggestion<SuggestionType>>; /** * Индекс текущей выбранной подсказки */ suggestionIndex: number; } export abstract class BaseSuggestions<SuggestionType, OwnProps> extends React.PureComponent< BaseProps<SuggestionType> & OwnProps, BaseState<SuggestionType> > { /** * URL для загрузки подсказок, переопределяется в конкретном компоненте */ protected loadSuggestionsUrl = ''; protected dontPerformBlurHandler = false; protected uid: string; /** * HTML-input */ private textInput?: HTMLInputElement; constructor(props: BaseProps<SuggestionType> & OwnProps) { super(props); this.uid = nanoid(); const { defaultQuery, value, delay } = this.props; const valueQuery = value ? value.value : undefined; this.setupDebounce(delay); this.state = { query: (defaultQuery as string | undefined) || valueQuery || '', inputQuery: (defaultQuery as string | undefined) || valueQuery || '', isFocused: false, displaySuggestions: true, suggestions: [], suggestionIndex: -1, }; } componentDidUpdate(prevProps: Readonly<BaseProps<SuggestionType> & OwnProps>): void { const { value, delay } = this.props; const { query, inputQuery } = this.state; if (!shallowEqual(prevProps.value, value)) { const newQuery = value ? value.value : ''; if (query !== newQuery || inputQuery !== newQuery) { this.setState({ query: newQuery, inputQuery: newQuery }); } } if (delay !== prevProps.delay) { this.setupDebounce(delay); } } protected getSuggestionsUrl = (): string => { const { url } = this.props; return url || this.loadSuggestionsUrl; }; protected setupDebounce = (delay: number | undefined): void => { if (typeof delay === 'number' && delay > 0) { this.fetchSuggestions = debounce(this.performFetchSuggestions, delay); } else { this.fetchSuggestions = this.performFetchSuggestions; } }; /** * Функция, которая вернет данные для отправки для получения подсказок */ protected abstract getLoadSuggestionsData(): unknown; protected fetchSuggestions = (): void => { // }; private handleInputFocus = (event: FocusEvent<HTMLInputElement>) => { this.setState({ isFocused: true }); const { suggestions } = this.state; if (suggestions.length === 0) { this.fetchSuggestions(); } const { inputProps } = this.props; if (inputProps && inputProps.onFocus) { inputProps.onFocus(event); } }; private handleInputBlur = (event: FocusEvent<HTMLInputElement>) => { const { suggestions, suggestionIndex } = this.state; const { selectOnBlur, inputProps } = this.props; this.setState({ isFocused: false }); if (suggestions.length === 0) { this.fetchSuggestions(); } if (selectOnBlur && !this.dontPerformBlurHandler) { if (suggestions.length > 0) { const suggestionIndexToSelect = suggestionIndex >= 0 && suggestionIndex < suggestions.length ? suggestionIndex : 0; this.selectSuggestion(suggestionIndexToSelect, true); } } this.dontPerformBlurHandler = false; if (inputProps && inputProps.onBlur) { inputProps.onBlur(event); } }; private handleInputChange = (event: ChangeEvent<HTMLInputElement>) => { const { value } = event.target; const { inputProps } = this.props; this.setState({ query: value, inputQuery: value, displaySuggestions: !!value }, () => { this.fetchSuggestions(); }); if (inputProps && inputProps.onChange) { inputProps.onChange(event); } }; private handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { this.handleKeyboard(event); const { inputProps } = this.props; if (inputProps && inputProps.onKeyDown) { inputProps.onKeyDown(event); } }; private handleInputKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => { this.handleKeyboard(event); const { inputProps } = this.props; if (inputProps && inputProps.onKeyPress) { inputProps.onKeyPress(event); } }; private handleKeyboard = (event: React.KeyboardEvent<HTMLInputElement>) => { const { suggestions, suggestionIndex, inputQuery } = this.state; if (event.which === 40) { // Arrow down event.preventDefault(); if (suggestionIndex < suggestions.length - 1) { const newSuggestionIndex = suggestionIndex + 1; const newInputQuery = suggestions[newSuggestionIndex].value; this.setState({ suggestionIndex: newSuggestionIndex, query: newInputQuery }); } } else if (event.which === 38) { // Arrow up event.preventDefault(); if (suggestionIndex >= 0) { const newSuggestionIndex = suggestionIndex - 1; const newInputQuery = newSuggestionIndex === -1 ? inputQuery : suggestions[newSuggestionIndex].value; this.setState({ suggestionIndex: newSuggestionIndex, query: newInputQuery }); } } else if (event.which === 13) { // Enter event.preventDefault(); if (suggestionIndex >= 0) { this.selectSuggestion(suggestionIndex); } } }; private performFetchSuggestions = () => { const { minChars, token } = this.props; const { query } = this.state; // Проверяем на минимальное количество символов для отправки if (typeof minChars === 'number' && minChars > 0 && query.length < minChars) { this.setState({ suggestions: [], suggestionIndex: -1 }); return; } makeRequest( 'POST', this.getSuggestionsUrl(), { headers: { Accept: 'application/json', Authorization: `Token ${token}`, 'Content-Type': 'application/json', }, json: this.getLoadSuggestionsData() || {}, }, (suggestions) => { this.setState({ suggestions, suggestionIndex: -1 }); }, ); }; private onSuggestionClick = (index: number, event: MouseEvent<HTMLButtonElement>) => { event.stopPropagation(); this.selectSuggestion(index); }; private selectSuggestion = (index: number, isSilent = false) => { const { suggestions } = this.state; const { selectOnBlur, onChange } = this.props; if (suggestions.length >= index - 1) { const suggestion = suggestions[index]; if (selectOnBlur) { this.dontPerformBlurHandler = true; } this.setState({ query: suggestion.value, inputQuery: suggestion.value, displaySuggestions: false }, () => { if (!isSilent) { this.fetchSuggestions(); setTimeout(() => this.setCursorToEnd(this.textInput)); } }); if (onChange) { onChange(suggestion); } } }; private setCursorToEnd = (element: HTMLInputElement | undefined) => { if (element) { const valueLength = element.value.length; if (element.selectionStart || element.selectionStart === 0) { // eslint-disable-next-line no-param-reassign element.selectionStart = valueLength; // eslint-disable-next-line no-param-reassign element.selectionEnd = valueLength; element.focus(); } } }; protected getHighlightWords = (): string[] => { const { inputQuery } = this.state; const wordsToPass = ['г', 'респ', 'ул', 'р-н', 'село', 'деревня', 'поселок', 'пр-д', 'пл', 'к', 'кв', 'обл', 'д']; let words = inputQuery.replace(',', '').split(' '); words = words.filter((word) => { return wordsToPass.indexOf(word) < 0; }); return words; }; /** * Функция, которая вернет уникальный key для списка React * @param suggestion */ protected getSuggestionKey = (suggestion: DaDataSuggestion<SuggestionType>): string => suggestion.value; public focus = (): void => { if (this.textInput) { this.textInput.focus(); } }; public setInputValue = (value?: string): void => { this.setState({ query: value || '', inputQuery: value || '' }); }; protected abstract renderOption(suggestion: DaDataSuggestion<SuggestionType>): ReactNode; public render(): ReactNode { const { inputProps, hintText, containerClassName, hintClassName, suggestionsClassName, suggestionClassName, currentSuggestionClassName, customInput, children, } = this.props; const { query, isFocused, suggestions, suggestionIndex, displaySuggestions } = this.state; const Component = typeof customInput !== 'undefined' ? (customInput as ElementType) : 'input'; const optionsExpanded = isFocused && suggestions && displaySuggestions && suggestions.length > 0; return ( <div role="combobox" aria-expanded={optionsExpanded ? 'true' : 'false'} aria-owns={this.uid} aria-controls={this.uid} aria-haspopup="listbox" className={containerClassName || 'react-dadata react-dadata__container'} > <div> <Component autoComplete="off" className="react-dadata__input" {...inputProps} value={query} ref={(input: HTMLInputElement) => { this.textInput = input; }} onChange={this.handleInputChange} onKeyPress={this.handleInputKeyPress} onKeyDown={this.handleInputKeyDown} onFocus={this.handleInputFocus} onBlur={this.handleInputBlur} /> </div> {optionsExpanded && ( <ul id={this.uid} aria-expanded role="listbox" className={suggestionsClassName || 'react-dadata__suggestions'} > {typeof hintText !== 'undefined' && ( <div className={hintClassName || 'react-dadata__suggestion-note'}>{hintText}</div> )} {suggestions.map((suggestion, index) => { let suggestionClass = suggestionClassName || 'react-dadata__suggestion'; if (index === suggestionIndex) { suggestionClass += ` ${currentSuggestionClassName || 'react-dadata__suggestion--current'}`; } return ( <button role="option" aria-selected={index === suggestionIndex ? 'true' : 'false'} key={this.getSuggestionKey(suggestion)} onMouseDown={this.onSuggestionClick.bind(this, index)} className={suggestionClass} > {this.renderOption(suggestion)} </button> ); })} </ul> )} {children} </div> ); } }
the_stack
import { DEBUG, EDITOR, TEST } from 'internal:constants'; import { IFeatureMap } from 'pal/system-info'; import { EventTarget } from '../../../cocos/core/event'; import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; class SystemInfo extends EventTarget { public readonly networkType: NetworkType; public readonly isNative: boolean; public readonly isBrowser: boolean; public readonly isMobile: boolean; public readonly isLittleEndian: boolean; public readonly platform: Platform; public readonly language: Language; public readonly nativeLanguage: string; public readonly os: OS; public readonly osVersion: string; public readonly osMainVersion: number; public readonly browserType: BrowserType; public readonly browserVersion: string; private _battery?: any; private _featureMap: IFeatureMap; constructor () { super(); const nav = window.navigator; const ua = nav.userAgent.toLowerCase(); // @ts-expect-error getBattery is not totally supported nav.getBattery?.().then((battery) => { this._battery = battery; }); this.networkType = NetworkType.LAN; // TODO this.isNative = false; this.isBrowser = true; // init isMobile and platform if (EDITOR) { this.isMobile = false; this.platform = Platform.EDITOR_PAGE; // TODO } else { this.isMobile = /mobile|android|iphone|ipad/.test(ua); this.platform = this.isMobile ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER; } // init isLittleEndian this.isLittleEndian = (() => { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true); // Int16Array uses the platform's endianness. return new Int16Array(buffer)[0] === 256; })(); // init languageCode and language let currLanguage = nav.language; this.nativeLanguage = currLanguage.toLowerCase(); currLanguage = currLanguage || (nav as any).browserLanguage; currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH; this.language = currLanguage as Language; // init os, osVersion and osMainVersion let isAndroid = false; let iOS = false; let osVersion = ''; let osMajorVersion = 0; let uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform); if (uaResult) { isAndroid = true; osVersion = uaResult[1] || ''; osMajorVersion = parseInt(osVersion) || 0; } uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua); if (uaResult) { iOS = true; osVersion = uaResult[2] || ''; osMajorVersion = parseInt(osVersion) || 0; // refer to https://github.com/cocos-creator/engine/pull/5542 , thanks for contribition from @krapnikkk // ipad OS 13 safari identifies itself as "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko)" // so use maxTouchPoints to check whether it's desktop safari or not. // reference: https://stackoverflow.com/questions/58019463/how-to-detect-device-name-in-safari-on-ios-13-while-it-doesnt-show-the-correct // FIXME: should remove it when touch-enabled mac are available // TODO: due to compatibility issues, it is still determined to be ios, and a new operating system type ipados may be added later? } else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || (nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1)) { iOS = true; osVersion = ''; osMajorVersion = 0; } let osName = OS.UNKNOWN; if (nav.appVersion.indexOf('Win') !== -1) { osName = OS.WINDOWS; } else if (iOS) { osName = OS.IOS; } else if (nav.appVersion.indexOf('Mac') !== -1) { osName = OS.OSX; } else if (nav.appVersion.indexOf('X11') !== -1 && nav.appVersion.indexOf('Linux') === -1) { osName = OS.LINUX; } else if (isAndroid) { osName = OS.ANDROID; } else if (nav.appVersion.indexOf('Linux') !== -1 || ua.indexOf('ubuntu') !== -1) { osName = OS.LINUX; } this.os = osName; this.osVersion = osVersion; this.osMainVersion = osMajorVersion; // TODO: use dack-type to determine the browserType // init browserType and browserVersion this.browserType = BrowserType.UNKNOWN; const typeReg0 = /wechat|weixin|micromessenger/i; const typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i; const typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge|HuaweiBrowser/i; const typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i; const browserTypes = typeReg0.exec(ua) || typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua); let browserType = browserTypes ? browserTypes[0].toLowerCase() : OS.UNKNOWN; if (browserType === 'safari' && isAndroid) { browserType = BrowserType.ANDROID; } else if (browserType === 'qq' && /android.*applewebkit/i.test(ua)) { browserType = BrowserType.ANDROID; } const typeMap = { micromessenger: BrowserType.WECHAT, wechat: BrowserType.WECHAT, weixin: BrowserType.WECHAT, trident: BrowserType.IE, edge: BrowserType.EDGE, '360 aphone': BrowserType.BROWSER_360, mxbrowser: BrowserType.MAXTHON, 'opr/': BrowserType.OPERA, ubrowser: BrowserType.UC, huaweibrowser: BrowserType.HUAWEI, }; this.browserType = typeMap[browserType] || browserType; // init browserVersion this.browserVersion = ''; const versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i; const versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i; let tmp = versionReg1.exec(ua); if (!tmp) { tmp = versionReg2.exec(ua); } this.browserVersion = tmp ? tmp[4] : ''; // init capability const _tmpCanvas1 = document.createElement('canvas'); const supportCanvas = TEST ? false : !!_tmpCanvas1.getContext('2d'); let supportWebGL = false; if (TEST) { supportWebGL = false; } else if (window.WebGLRenderingContext) { supportWebGL = true; } let supportWebp; try { supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp'); } catch (e) { supportWebp = false; } let supportImageBitmap = false; if (!TEST && typeof createImageBitmap !== 'undefined' && typeof Blob !== 'undefined') { _tmpCanvas1.width = _tmpCanvas1.height = 2; createImageBitmap(_tmpCanvas1, {}).then((imageBitmap) => { supportImageBitmap = true; imageBitmap?.close(); }).catch((err) => {}); } const supportTouch = (document.documentElement.ontouchstart !== undefined || document.ontouchstart !== undefined); const supportMouse = !EDITOR && document.documentElement.onmouseup !== undefined; this._featureMap = { [Feature.WEBP]: supportWebp, [Feature.IMAGE_BITMAP]: supportImageBitmap, [Feature.WEB_VIEW]: true, [Feature.VIDEO_PLAYER]: true, [Feature.SAFE_AREA]: false, [Feature.INPUT_TOUCH]: supportTouch, [Feature.EVENT_KEYBOARD]: document.documentElement.onkeyup !== undefined, [Feature.EVENT_MOUSE]: supportMouse, [Feature.EVENT_TOUCH]: supportTouch || supportMouse, [Feature.EVENT_ACCELEROMETER]: (window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined), }; this._registerEvent(); } private _registerEvent () { let hiddenPropName: string; if (typeof document.hidden !== 'undefined') { hiddenPropName = 'hidden'; } else if (typeof document.mozHidden !== 'undefined') { hiddenPropName = 'mozHidden'; } else if (typeof document.msHidden !== 'undefined') { hiddenPropName = 'msHidden'; } else if (typeof document.webkitHidden !== 'undefined') { hiddenPropName = 'webkitHidden'; } else { hiddenPropName = 'hidden'; } let hidden = false; const onHidden = () => { if (!hidden) { hidden = true; this.emit('hide'); } }; // In order to adapt the most of platforms the onshow API. const onShown = (arg0?, arg1?, arg2?, arg3?, arg4?) => { if (hidden) { hidden = false; this.emit('show', arg0, arg1, arg2, arg3, arg4); } }; if (hiddenPropName) { const changeList = [ 'visibilitychange', 'mozvisibilitychange', 'msvisibilitychange', 'webkitvisibilitychange', 'qbrowserVisibilityChange', ]; for (let i = 0; i < changeList.length; i++) { document.addEventListener(changeList[i], (event) => { let visible = document[hiddenPropName]; // @ts-expect-error QQ App need hidden property visible = visible || event.hidden; if (visible) { onHidden(); } else { onShown(); } }); } } else { window.addEventListener('blur', onHidden); window.addEventListener('focus', onShown); } if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) { window.onfocus = onShown; } if ('onpageshow' in window && 'onpagehide' in window) { window.addEventListener('pagehide', onHidden); window.addEventListener('pageshow', onShown); // Taobao UIWebKit document.addEventListener('pagehide', onHidden); document.addEventListener('pageshow', onShown); } } public hasFeature (feature: Feature): boolean { return this._featureMap[feature]; } public getBatteryLevel (): number { if (this._battery) { return this._battery.level as number; } else { if (DEBUG) { console.warn('getBatteryLevel is not supported'); } return 1; } } public triggerGC (): void { if (DEBUG) { console.warn('triggerGC is not supported.'); } } public openURL (url: string): void { window.open(url); } public now (): number { if (Date.now) { return Date.now(); } return +(new Date()); } public restartJSVM (): void { if (DEBUG) { console.warn('restartJSVM is not supported.'); } } public close () { this.emit('close'); window.close(); } } export const systemInfo = new SystemInfo();
the_stack
import { cloneDeepFast } from './cloneDeepFast' import { Merge, OneOrMore } from '../types' export interface TreeDataNode extends Record<any, any> {} export type TreeDataSingleRootData<TNode extends TreeDataNode> = TNode export type TreeDataMultipleRootData<TNode extends TreeDataNode> = TNode[] export type TreeDataStandardNode<TNode extends TreeDataNode> = Merge< TNode, { children: Array<TreeDataStandardNode<TNode>> } > export type TreeDataData<TNode extends TreeDataNode> = TNode[] export type TreeDataChildrenPropName<TNode extends TreeDataNode> = { [K in keyof TNode]: Exclude<TNode[K], undefined> extends TreeDataData<TNode> ? K : never }[keyof TNode] export type TreeDataSearchStrategy = 'DFS' | 'BFS' export interface TreeDataOptions<TNode extends TreeDataNode> { /** * 节点上子树数据所在的属性名。 * * @default 'children' */ childrenPropName?: TreeDataChildrenPropName<TNode> /** * 遍历时的搜索策略。 * * - `DFS`: 深度优先搜索 * - `BFS`: 广度优先搜索 * * @default 'DFS' */ searchStrategy?: TreeDataSearchStrategy /** * 克隆数据时忽略的值。 */ cloneIgnore?: (value: unknown) => boolean | undefined } export interface TreeDataTraverseFnPayload<TNode extends TreeDataNode> { /** * 当前节点。 */ node: TNode /** * 当前节点索引。 */ index: number /** * 当前深度。从 `0` 开始。 */ depth: number /** * 父节点。为 `undefined` 时表示当前节点是根节点。 */ parentNode: TNode | undefined /** * 到当前节点的路径节点列表。 */ path: TNode[] /** * 移除当前节点。 */ removeNode: () => void /** * 退出遍历。 */ exit: () => void /** * 跳过子树遍历。 */ skipChildrenTraverse: () => void } export type TreeDataTraverseFn<TNode extends TreeDataNode> = ( payload: TreeDataTraverseFnPayload<TNode>, ) => void /** * 树数据处理。支持单根节点、多根节点树数据。 */ export class TreeData<TNode extends TreeDataNode> { private data: TreeDataData<TNode> private childrenPropName: TreeDataChildrenPropName<TNode> = 'children' as any private searchStrategy: TreeDataSearchStrategy = 'DFS' private cloneIgnore: ((value: unknown) => boolean | undefined) | undefined = undefined /** * 构造函数。 * * @param data 整棵树的数据 * @param options 选项 */ constructor( data: TreeDataSingleRootData<TNode> | TreeDataMultipleRootData<TNode>, options: TreeDataOptions<TNode> = {}, ) { this.setOptions(options) this.data = this.cloneDeep(Array.isArray(data) ? data : [data]) } private cloneDeep<T>(value: T): T { return cloneDeepFast(value, this.cloneIgnore) } /** * 核心遍历函数。 */ private static traverse<TNode extends TreeDataNode>( data: TreeDataData<TNode>, childrenPropName: TreeDataChildrenPropName<TNode>, searchStrategy: TreeDataSearchStrategy, fn: TreeDataTraverseFn<TNode>, ) { const nodes: Array< [ node: TNode, index: number, parentNode: TNode | undefined, siblings: TNode[], depth: number, path: TNode[], ] > = [] for (let i = data.length - 1; i >= 0; i--) { nodes.push([data[i], i, undefined, data, 0, []]) } let currentNode: typeof nodes[0] | undefined const removeNodes: Array<[siblings: TNode[], indexes: number[]]> = [] let isRemove = false let isExit = false let isSkipChildrenTraverse = false const removeNode = () => (isRemove = true) const exit = () => (isExit = true) const skipChildrenTraverse = () => (isSkipChildrenTraverse = true) while ((currentNode = nodes.pop())) { const [node, index, parentNode, siblings, depth, path] = currentNode isRemove = false isExit = false isSkipChildrenTraverse = false fn({ node: node, index: index, parentNode: parentNode, depth: depth, path: path, removeNode: removeNode, exit: exit, skipChildrenTraverse: skipChildrenTraverse, }) if (isRemove) { if ( !removeNodes.length || removeNodes[removeNodes.length - 1][0] !== siblings ) { removeNodes.push([siblings, []]) } removeNodes[removeNodes.length - 1][1].push(index) } if (isExit) return if ( !isRemove && !isSkipChildrenTraverse && node[childrenPropName] && Array.isArray(node[childrenPropName]) ) { if (searchStrategy === 'DFS') { for (let i = node[childrenPropName].length - 1; i >= 0; i--) { nodes.push([ node[childrenPropName][i], i, node, node[childrenPropName], depth + 1, path.concat(node), ]) } } else { for (let i = 0; i < node[childrenPropName].length; i++) { nodes.unshift([ node[childrenPropName][i], i, node, node[childrenPropName], depth + 1, path.concat(node), ]) } } } } let _removeNode: typeof removeNodes[0] | undefined while ((_removeNode = removeNodes.pop())) { let removeNodeIndex: number | undefined while ((removeNodeIndex = _removeNode[1].pop()) != null) { _removeNode[0].splice(removeNodeIndex, 1) } } } /** * 设置选项。 * * @param options 选项 */ setOptions(options: TreeDataOptions<TNode>): this { this.cloneIgnore = options.cloneIgnore || this.cloneIgnore this.childrenPropName = options.childrenPropName || this.childrenPropName this.searchStrategy = options.searchStrategy || this.searchStrategy return this } /** * 遍历节点。 * * @param node 节点 * @param fn 遍历函数 * @param searchStrategy 遍历搜索方式,默认为选项中的遍历搜索方式 */ traverseNode( node: | OneOrMore<TNode> | ((payload: TreeDataTraverseFnPayload<TNode>) => boolean), fn: OneOrMore<TreeDataTraverseFn<TNode> | false>, searchStrategy: TreeDataSearchStrategy = this.searchStrategy, ) { const nodes: TNode[] = typeof node === 'function' ? this.findNodeAll(node as any) : Array.isArray(node) ? node : [node] let _node: TNode | undefined while ((_node = nodes.pop())) { if (Array.isArray(_node[this.childrenPropName])) { const fns: Array<TreeDataTraverseFn<TNode>> = ( Array.isArray(fn) ? fn : [fn] ).filter(fn => typeof fn === 'function') as any for (let i = 0; i < fns.length; i++) { TreeData.traverse<TNode>( _node[this.childrenPropName], this.childrenPropName, searchStrategy, fns[i], ) } } } return this } /** * 深度优先遍历节点。 * * @param fn 遍历函数 */ traverseNodeDFS( node: | OneOrMore<TNode> | ((payload: TreeDataTraverseFnPayload<TNode>) => boolean), fn: OneOrMore<TreeDataTraverseFn<TNode> | false>, ): this { return this.traverseNode(node, fn, 'DFS') } /** * 广度优先遍历节点。 * * @param fn 遍历函数 */ traverseNodeBFS( node: | OneOrMore<TNode> | ((payload: TreeDataTraverseFnPayload<TNode>) => boolean), fn: OneOrMore<TreeDataTraverseFn<TNode> | false>, ): this { return this.traverseNode(node, fn, 'BFS') } /** * 遍历。 * * @param fn 遍历函数 * @param searchStrategy 遍历搜索方式,默认为选项中的遍历搜索方式 */ traverse( fn: OneOrMore<TreeDataTraverseFn<TNode> | false>, searchStrategy: TreeDataSearchStrategy = this.searchStrategy, ): this { this.traverseNode( { [this.childrenPropName]: this.data, } as any, fn, searchStrategy, ) return this } /** * 深度优先遍历。 * * @param fn 遍历函数 */ traverseDFS(fn: OneOrMore<TreeDataTraverseFn<TNode> | false>): this { return this.traverse(fn, 'DFS') } /** * 广度优先遍历。 * * @param fn 遍历函数 */ traverseBFS(fn: OneOrMore<TreeDataTraverseFn<TNode> | false>): this { return this.traverse(fn, 'BFS') } /** * 设置数据深度。从 `0` 开始,将会移除超过指定深度的数据。 * * @param depth 深度 */ setDepth(depth: number): this { this.traverse(payload => { if (payload.depth === depth) { delete payload.node[this.childrenPropName] } }) return this } /** * 设置节点属性。 * * @param props 节点属性键值映射对象,值为函数,用其返回值作为新的属性值 */ setNodeProps< TProps extends { [K in keyof TNode]?: (payload: TreeDataTraverseFnPayload<TNode>) => any } & { [K: string]: (payload: TreeDataTraverseFnPayload<TNode>) => any }, >( props: TProps, ): TreeData< Merge< TNode, { [K in keyof TProps]: ReturnType<TProps[K]> } > > { this.traverse(payload => { for (const propName in props) { ;(payload.node as any)[propName] = props[propName](payload) } }) return this as any } /** * 移除节点上指定的属性。 * * @param propNames 属性名列表 */ omitNodeProps<TPropName extends keyof TNode>( propNames: TPropName[], ): TreeData<Omit<TNode, TPropName>> { this.traverse(payload => { for (const i in propNames) { delete payload.node[propNames[i]] } }) return this as any } /** * 选取节点上指定的属性。 * * @param propNames 属性名列表 */ pickNodeProps<TPropName extends keyof TNode>( propNames: TPropName[], ): TreeData<Pick<TNode, TPropName>> { this.traverse(payload => { for (const propName in payload.node) { if (propNames.indexOf(propName as any) === -1) { delete payload.node[propName] } } }) return this as any } /** * 筛选符合条件的节点。 * * @param predicate 条件 */ filter( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): this { this.traverse([ payload => { if (predicate(payload)) { ;(payload.node as any).__SKIP__ = true ;(payload.node as any).__PICK__ = true let node: TNode | undefined while ((node = payload.path.pop())) { ;(node as any).__PICK__ = true } payload.skipChildrenTraverse() } }, payload => { if (payload.node.__SKIP__ === true) { payload.skipChildrenTraverse() } if (payload.node.__PICK__ !== true) { payload.removeNode() } delete payload.node.__SKIP__ delete payload.node.__PICK__ }, ]) return this } /** * 查找符合条件的第一个节点。 * * @param predicate 条件 */ findNode( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): TNode | undefined { let node: TNode | undefined this.traverse(payload => { if (predicate(payload)) { node = payload.node payload.exit() } }) return node } /** * 查找符合条件的所有节点。 * * @param predicate 条件 */ findNodeAll( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): TNode[] { const nodes: TNode[] = [] this.traverse(payload => { if (predicate(payload)) { nodes.push(payload.node) } }) return nodes } /** * 查找符合条件的第一个节点的路径。 * * @param predicate 条件 */ findNodePath( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): TNode[] | undefined { let path: TNode[] | undefined this.traverse(payload => { if (predicate(payload)) { path = payload.path.concat(payload.node) payload.exit() } }) return path } /** * 查找符合条件的所有节点的路径。 * * @param predicate 条件 */ findNodePathAll( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): Array<TNode[]> { const paths: Array<TNode[]> = [] this.traverse(payload => { if (predicate(payload)) { paths.push(payload.path.concat(payload.node)) } }) return paths } /** * 移除符合条件的第一个节点。返回被移除的节点。 * * @param predicate 条件 */ removeNode( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): TNode | undefined { let node: TNode | undefined this.traverse(payload => { if (predicate(payload)) { payload.removeNode() node = payload.node payload.exit() } }) return node } /** * 移除符合条件的所有节点。返回被移除的节点组成的数组。 * * @param predicate 条件 */ removeNodeAll( predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): TNode[] { const nodes: TNode[] = [] this.traverse(payload => { if (predicate(payload)) { payload.removeNode() nodes.push(payload.node) } }) return nodes } /** * 计算符合条件的节点个数。不给出条件则计算所有节点的个数。 * * @param predicate 条件 */ count( predicate?: (payload: TreeDataTraverseFnPayload<TNode>) => boolean, ): number { let counter = 0 this.traverse(payload => { if (predicate ? predicate(payload) : true) { counter++ } }) return counter } /** * 克隆实例。 */ clone(): TreeData<TNode> { return new TreeData(this.export()) } /** * 导出数据。 */ export(): TreeDataData<TNode> { return this.cloneDeep(this.data) } /** * 导出一维列表数据。 */ exportList(): TNode[] { const list: TNode[] = [] this.traverse(payload => { list.push(payload.node) }) return this.cloneDeep(list) } /** * 从一维列表生成实例。 * * @param list 列表 * @param idKey ID 所在键 * @param parentIdKey 父 ID 所在键 */ static fromList<TItem extends Record<any, any>>( list: TItem[], idKey: keyof TItem, parentIdKey: keyof TItem, ): TreeData<TreeDataStandardNode<TItem>> { const itemMap: Record<any, TItem> = {} for (let i = 0; i < list.length; i++) { const item = list[i] as any item.children = [] itemMap[item[idKey]] = item } const tree: TItem[] = [] for (let i = 0; i < list.length; i++) { const item = list[i] as any if (itemMap[item[parentIdKey]] !== undefined) { itemMap[item[parentIdKey]].children.push(item) } else { tree.push(item) } } return new TreeData(tree as any) } }
the_stack
import { Constants } from '../commons/CommonConstants'; export default class StringUtils { /** * Splits text into several paragraphs, each containing header * string and body string array * * Example input: * ["objectives", * " talkToHartin" * " completeQuest"] * * Example output: * [ ["objectives"], ["talkToHartin", "completeQuest"] ] * * @param lines raw text strings * @returns {Array<[string, string[]]>} several parargraphs that have * been split into head and body */ public static splitToParagraph(lines: string[]) { const headerAndBodyLines: [string, string[]][] = []; lines.forEach((line: string) => { if (line.startsWith('\t') || line.startsWith(' ')) { const content = line.startsWith('\t') ? line.slice(1) : line.slice(4); if (headerAndBodyLines.length === 0) { console.error('Unexpected tabs'); return; } const bodyLines = headerAndBodyLines[headerAndBodyLines.length - 1][1]; bodyLines.push(content); return; } headerAndBodyLines.push([line.trim(), []]); }); return headerAndBodyLines; } /** * Given an array of lines, returns a Map where the keys are the headings * and the value are the lines below each heading. * * @param lines lines to be processed * @param isHeaderFunction predicate that determines the header syntax. This * will be ran against every line, so take into account if you want * to detect header in the middle of line/in between lines. * @returns {Map<string, string>} */ public static mapByHeader( lines: string[], isHeaderFunction: (line: string) => boolean ): Map<string, string[]> { const map = new Map<string, string[]>(); if (!isHeaderFunction(lines[0])) { map.set('0', lines); return map; } let currHeader = ''; lines.forEach(line => { if (isHeaderFunction(line)) { currHeader = line; map.set(line, []); return; } map.get(currHeader)!.push(line); }); return map; } /** * Split using separator, but limit number of separators to split with. * After splitting, trim each entry to get rid of whitespaces. * * Example input: splitByChar("whatHappened, What Happened, Scottie?\n", ",", 1) * Example output: ["whatHappened", "What Happened, Scottie?"] * Explanation: This splits the string only using the first 1 comma then trims whitespaces * * @param line line to be split * @param sep separator to be used * @param limit the number of separators to split the string, undefined if use all separators * @param {Array<string>} */ public static splitWithLimit(line: string, sep: string, limit: number): string[] { let lines = []; if (limit) { let currWord = ''; for (let i = 0; i < line.length; i++) { const letter = line[i]; if (letter === sep && lines.length < limit) { lines.push(currWord); currWord = ''; } else { currWord += letter; } } lines.push(currWord); } else { lines = line.split(sep); } return lines.map((phrase: string) => phrase.trim()); } /** * Split using separator. After splitting, trim each entry to get rid of whitespaces. * * @param line line to be split * @param sep separator to be used * @param {Array<string>} */ public static splitByChar(line: string, sep: string): string[] { return line.split(sep).map((phrase: string) => phrase.trim()); } /** * Splits text into string array and removes * lines with only newlines. * * @param text text to split * @returns {Array<string>} */ public static splitToLines(text: string): string[] { return text .split('\n') .map(line => line.trimRight()) .filter(line => line !== ''); } /** * Splits text into string array, removes lines * with only newlines and removes characters that * are commented out in single and multi line * comments * * @param text text to split * @returns {Array<string>} */ public static splitToLinesAndRemoveComments(text: string): string[] { return this.removeMultiLineComments(text.split('\n'), '/*', '*/') .map(line => this.removeSingleLineComment(line, '//')) .map(line => line.trimRight()) .filter(line => line !== ''); } /** * Removes characters from string before/after * specified comment characters * * Example input: * removeSingleLineComment('Hello # World','#',false) * * Example output: * 'Hello ' * * @param text text with single line comments * @param commentChars characters to denote comment region * @param removeAfter (optional) true - remove characters after commentChars, * false - remove characters before commentChars * @returns {string} */ public static removeSingleLineComment( text: string, commentChars: string, removeAfter: boolean = true ) { const commentIndex = text.indexOf(commentChars); return commentIndex === -1 ? text : removeAfter ? text.slice(0, commentIndex) : text.slice(commentIndex + commentChars.length); } /** * Given an array of lines with a * a subset of characters commented out * by specified open and close comment * characters, Returns an array of lines * with characters inside commented regions * removed * * Example input: * removeMultiLineComments( * ['objectives', * ' checkedScreen', * ' talkedToLokKim1', * '/! talkedToLokKim2', * ' talkedToLokKim3!/'], * '/!', '!/'); * * Example output: * ['objectives', * ' checkedScreen', * ' talkedToLokKim1'] * * @param lines lines to remove comments from * @param openCommentChars characters to denote open comment * @param closeCommentChars characters to denote close comment * @returns {Array<string>} */ public static removeMultiLineComments( lines: string[], openCommentChars: string, closeCommentChars: string ): string[] { const newLines = []; let commentOpen = false; for (let l = 0; l < lines.length; l++) { const line = lines[l]; const commentRegions: [number, number][] = []; const openIns = this.findAllInstances(line, openCommentChars); const closeIns = this.findAllInstances(line, closeCommentChars); let activeIndex = -1; // current valid comment index in line let openInd = 0; // open comment index in openIns let closeInd = 0; // close comment index in closeIns let region = commentOpen ? [0] : []; while (openInd < openIns.length || closeInd < closeIns.length) { const prevActive = activeIndex; activeIndex = commentOpen ? closeIns[closeInd++] + closeCommentChars.length : openIns[openInd++]; if (activeIndex <= prevActive) { console.error(`Comment mismatch: Line ${l + 1}, Pos ${activeIndex + 1}`); activeIndex = prevActive; } else { region.push(activeIndex); commentOpen = !commentOpen; } if (region.length === 2) { commentRegions.push([region[0], region[1]]); region = []; } } if (region.length === 1) { commentRegions.push([region[0], line.length]); } newLines.push(this.removeCommentRegions(line, commentRegions)); } return newLines; } /** * Return a string whose content within the regions is removed * for each region; regions contain two elements: the index of * the first character to ignore, and the index of the last character * to ignore + 1, in the text string * * Example input (comment characters: '/!' and '!/'): * removeCommentRegions('Sour/!ce Academ!/y', [[4,17]]) * * Example output: * 'Soury' * * @param text the text to be removed from * @param regions contains all the regions of comments * @returns {string} */ public static removeCommentRegions(text: string, regions: [number, number][]) { let newString = ''; let prevEnd = 0; regions.forEach(arr => { newString += text.slice(prevEnd, arr[0]); prevEnd = arr[1]; }); newString += text.slice(prevEnd, text.length); return newString; } /** * Return an array of the starting indices of the substring within the text string * * @param text * @param substring substring to search for * @returns {Array<number>} */ public static findAllInstances(text: string, substring: string): number[] { const indices = []; let index = text.indexOf(substring); while (index !== -1) { indices.push(index); index = text.indexOf(substring, index + 1); } return indices; } /** * Capitalise first letter. * * @param word text to be capitalized * @returns {string} */ public static capitalize(word: string) { return word.charAt(0).toUpperCase() + word.slice(1); } /** * Turns snake case to capitalized case. * Only accounts for letters, i.e. numbers and symbols will be discarded. * e.g. snake_case_to_capitalized -> Snake Case To Capitalized * * @param name text to be capitalized * @returns {string} */ public static toCapitalizedWords(name: string) { const words = name.match(/[A-Za-z][a-z]*/g) || []; return words.map(StringUtils.capitalize).join(' '); } /** * Converts the given number into string. The given number * is rounded down. * * @param num number to be converted */ public static toIntString(num: number) { return Math.floor(num).toString(); } /** * Check whether given string is empty string. * * @param str string to check */ public static isEmptyString(str: string) { return str === Constants.nullInteractionId; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A scheduled job that can publish a pubsub message or a http request * every X interval of time, using crontab format string. * * To use Cloud Scheduler your project must contain an App Engine app * that is located in one of the supported regions. If your project * does not have an App Engine app, you must create one. * * To get more information about Job, see: * * * [API documentation](https://cloud.google.com/scheduler/docs/reference/rest/) * * How-to Guides * * [Official Documentation](https://cloud.google.com/scheduler/) * * ## Example Usage * ### Scheduler Job App Engine * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const job = new gcp.cloudscheduler.Job("job", { * appEngineHttpTarget: { * appEngineRouting: { * instance: "my-instance-001", * service: "web", * version: "prod", * }, * httpMethod: "POST", * relativeUri: "/ping", * }, * attemptDeadline: "320s", * description: "test app engine job", * retryConfig: { * maxDoublings: 2, * maxRetryDuration: "10s", * minBackoffDuration: "1s", * retryCount: 3, * }, * schedule: "*&#47;4 * * * *", * timeZone: "Europe/London", * }); * ``` * ### Scheduler Job Oauth * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const default = gcp.compute.getDefaultServiceAccount({}); * const job = new gcp.cloudscheduler.Job("job", { * description: "test http job", * schedule: "*&#47;8 * * * *", * timeZone: "America/New_York", * attemptDeadline: "320s", * httpTarget: { * httpMethod: "GET", * uri: "https://cloudscheduler.googleapis.com/v1/projects/my-project-name/locations/us-west1/jobs", * oauthToken: { * serviceAccountEmail: _default.then(_default => _default.email), * }, * }, * }); * ``` * ### Scheduler Job Oidc * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const default = gcp.compute.getDefaultServiceAccount({}); * const job = new gcp.cloudscheduler.Job("job", { * description: "test http job", * schedule: "*&#47;8 * * * *", * timeZone: "America/New_York", * attemptDeadline: "320s", * httpTarget: { * httpMethod: "GET", * uri: "https://example.com/ping", * oidcToken: { * serviceAccountEmail: _default.then(_default => _default.email), * }, * }, * }); * ``` * * ## Import * * Job can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:cloudscheduler/job:Job default projects/{{project}}/locations/{{region}}/jobs/{{name}} * ``` * * ```sh * $ pulumi import gcp:cloudscheduler/job:Job default {{project}}/{{region}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:cloudscheduler/job:Job default {{region}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:cloudscheduler/job:Job default {{name}} * ``` */ export class Job extends pulumi.CustomResource { /** * Get an existing Job resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: JobState, opts?: pulumi.CustomResourceOptions): Job { return new Job(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:cloudscheduler/job:Job'; /** * Returns true if the given object is an instance of Job. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Job { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Job.__pulumiType; } /** * App Engine HTTP target. * If the job providers a App Engine HTTP target the cron will * send a request to the service instance * Structure is documented below. */ public readonly appEngineHttpTarget!: pulumi.Output<outputs.cloudscheduler.JobAppEngineHttpTarget | undefined>; /** * The deadline for job attempts. If the request handler does not respond by this deadline then the request is * cancelled and the attempt is marked as a DEADLINE_EXCEEDED failure. The failed attempt can be viewed in * execution logs. Cloud Scheduler will retry the job according to the RetryConfig. * The allowed duration for this deadline is: * * For HTTP targets, between 15 seconds and 30 minutes. * * For App Engine HTTP targets, between 15 seconds and 24 hours. * * **Note**: For PubSub targets, this field is ignored - setting it will introduce an unresolvable diff. * A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s" */ public readonly attemptDeadline!: pulumi.Output<string | undefined>; /** * A human-readable description for the job. * This string must not contain more than 500 characters. */ public readonly description!: pulumi.Output<string | undefined>; /** * HTTP target. * If the job providers a httpTarget the cron will * send a request to the targeted url * Structure is documented below. */ public readonly httpTarget!: pulumi.Output<outputs.cloudscheduler.JobHttpTarget | undefined>; /** * The name of the job. */ public readonly name!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * Pub/Sub target * If the job providers a Pub/Sub target the cron will publish * a message to the provided topic * Structure is documented below. */ public readonly pubsubTarget!: pulumi.Output<outputs.cloudscheduler.JobPubsubTarget | undefined>; /** * Region where the scheduler job resides. If it is not provided, this provider will use the provider default. */ public readonly region!: pulumi.Output<string>; /** * By default, if a job does not complete successfully, * meaning that an acknowledgement is not received from the handler, * then it will be retried with exponential backoff according to the settings * Structure is documented below. */ public readonly retryConfig!: pulumi.Output<outputs.cloudscheduler.JobRetryConfig | undefined>; /** * Describes the schedule on which the job will be executed. */ public readonly schedule!: pulumi.Output<string | undefined>; /** * Specifies the time zone to be used in interpreting schedule. * The value of this field must be a time zone name from the tz database. */ public readonly timeZone!: pulumi.Output<string | undefined>; /** * Create a Job resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args?: JobArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: JobArgs | JobState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as JobState | undefined; inputs["appEngineHttpTarget"] = state ? state.appEngineHttpTarget : undefined; inputs["attemptDeadline"] = state ? state.attemptDeadline : undefined; inputs["description"] = state ? state.description : undefined; inputs["httpTarget"] = state ? state.httpTarget : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["pubsubTarget"] = state ? state.pubsubTarget : undefined; inputs["region"] = state ? state.region : undefined; inputs["retryConfig"] = state ? state.retryConfig : undefined; inputs["schedule"] = state ? state.schedule : undefined; inputs["timeZone"] = state ? state.timeZone : undefined; } else { const args = argsOrState as JobArgs | undefined; inputs["appEngineHttpTarget"] = args ? args.appEngineHttpTarget : undefined; inputs["attemptDeadline"] = args ? args.attemptDeadline : undefined; inputs["description"] = args ? args.description : undefined; inputs["httpTarget"] = args ? args.httpTarget : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["pubsubTarget"] = args ? args.pubsubTarget : undefined; inputs["region"] = args ? args.region : undefined; inputs["retryConfig"] = args ? args.retryConfig : undefined; inputs["schedule"] = args ? args.schedule : undefined; inputs["timeZone"] = args ? args.timeZone : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Job.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Job resources. */ export interface JobState { /** * App Engine HTTP target. * If the job providers a App Engine HTTP target the cron will * send a request to the service instance * Structure is documented below. */ appEngineHttpTarget?: pulumi.Input<inputs.cloudscheduler.JobAppEngineHttpTarget>; /** * The deadline for job attempts. If the request handler does not respond by this deadline then the request is * cancelled and the attempt is marked as a DEADLINE_EXCEEDED failure. The failed attempt can be viewed in * execution logs. Cloud Scheduler will retry the job according to the RetryConfig. * The allowed duration for this deadline is: * * For HTTP targets, between 15 seconds and 30 minutes. * * For App Engine HTTP targets, between 15 seconds and 24 hours. * * **Note**: For PubSub targets, this field is ignored - setting it will introduce an unresolvable diff. * A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s" */ attemptDeadline?: pulumi.Input<string>; /** * A human-readable description for the job. * This string must not contain more than 500 characters. */ description?: pulumi.Input<string>; /** * HTTP target. * If the job providers a httpTarget the cron will * send a request to the targeted url * Structure is documented below. */ httpTarget?: pulumi.Input<inputs.cloudscheduler.JobHttpTarget>; /** * The name of the job. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Pub/Sub target * If the job providers a Pub/Sub target the cron will publish * a message to the provided topic * Structure is documented below. */ pubsubTarget?: pulumi.Input<inputs.cloudscheduler.JobPubsubTarget>; /** * Region where the scheduler job resides. If it is not provided, this provider will use the provider default. */ region?: pulumi.Input<string>; /** * By default, if a job does not complete successfully, * meaning that an acknowledgement is not received from the handler, * then it will be retried with exponential backoff according to the settings * Structure is documented below. */ retryConfig?: pulumi.Input<inputs.cloudscheduler.JobRetryConfig>; /** * Describes the schedule on which the job will be executed. */ schedule?: pulumi.Input<string>; /** * Specifies the time zone to be used in interpreting schedule. * The value of this field must be a time zone name from the tz database. */ timeZone?: pulumi.Input<string>; } /** * The set of arguments for constructing a Job resource. */ export interface JobArgs { /** * App Engine HTTP target. * If the job providers a App Engine HTTP target the cron will * send a request to the service instance * Structure is documented below. */ appEngineHttpTarget?: pulumi.Input<inputs.cloudscheduler.JobAppEngineHttpTarget>; /** * The deadline for job attempts. If the request handler does not respond by this deadline then the request is * cancelled and the attempt is marked as a DEADLINE_EXCEEDED failure. The failed attempt can be viewed in * execution logs. Cloud Scheduler will retry the job according to the RetryConfig. * The allowed duration for this deadline is: * * For HTTP targets, between 15 seconds and 30 minutes. * * For App Engine HTTP targets, between 15 seconds and 24 hours. * * **Note**: For PubSub targets, this field is ignored - setting it will introduce an unresolvable diff. * A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s" */ attemptDeadline?: pulumi.Input<string>; /** * A human-readable description for the job. * This string must not contain more than 500 characters. */ description?: pulumi.Input<string>; /** * HTTP target. * If the job providers a httpTarget the cron will * send a request to the targeted url * Structure is documented below. */ httpTarget?: pulumi.Input<inputs.cloudscheduler.JobHttpTarget>; /** * The name of the job. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Pub/Sub target * If the job providers a Pub/Sub target the cron will publish * a message to the provided topic * Structure is documented below. */ pubsubTarget?: pulumi.Input<inputs.cloudscheduler.JobPubsubTarget>; /** * Region where the scheduler job resides. If it is not provided, this provider will use the provider default. */ region?: pulumi.Input<string>; /** * By default, if a job does not complete successfully, * meaning that an acknowledgement is not received from the handler, * then it will be retried with exponential backoff according to the settings * Structure is documented below. */ retryConfig?: pulumi.Input<inputs.cloudscheduler.JobRetryConfig>; /** * Describes the schedule on which the job will be executed. */ schedule?: pulumi.Input<string>; /** * Specifies the time zone to be used in interpreting schedule. * The value of this field must be a time zone name from the tz database. */ timeZone?: pulumi.Input<string>; }
the_stack
import * as IORedis from 'ioredis'; import { Module, RedisModuleOptions } from './module.base'; import { RedisAI } from './redis-ai/redis-ai'; import { RedisAICommander } from './redis-ai/redis-ai.commander'; import { RedisBloom } from './bloom/redisbloom'; import { RedisBloomCMK } from './bloom-cmk/redisbloom-cmk'; import { RedisBloomCuckoo } from './bloom-cuckoo/redisbloom-cuckoo'; import { RedisBloomTDigest } from './bloom-tdigest/redisbloom-tdigest'; import { RedisBloomTopK } from './bloom-topk/redisbloom-topk'; import { Redisearch } from './redisearch/redisearch'; import { RedisGears } from './redisgears/redisgears'; import { RedisGraph } from './redisgraph/redisgraph'; import { ReJSON } from './rejson/rejson'; import { RedisIntervalSets } from './ris/ris'; import { RedisIntervalSetsCommander } from './ris/ris.commander'; import { RedisTimeSeries } from './rts/rts'; import { BloomTdigestCommander } from './bloom-tdigest/redisbloom-tdigest.commander'; import { BloomCommander } from './bloom/redisbloom.commander'; import { BloomCmkCommander } from './bloom-cmk/redisbloom-cmk.commander'; import { BloomCuckooCommander } from './bloom-cuckoo/redisbloom-cuckoo.commander'; import { BloomTopkCommander } from './bloom-topk/redisbloom-topk.commander'; import { SearchCommander } from './redisearch/redisearch.commander'; import { GearsCommander } from './redisgears/redisgears.commander'; import { GraphCommander } from './redisgraph/redisgraph.commander'; import { RejsonCommander } from './rejson/rejson.commander'; import { RedisTimeSeriesCommander } from './rts/rts.commander'; import { RedisearchHelpers } from './redisearch/redisearch.helpers'; import { RedisIntervalSetsHelpers } from './ris/ris.helpers'; export class RedisModules extends Module { public bloomCommander = new BloomCommander() public bloomCmkCommander = new BloomCmkCommander() public bloomCuckooCommander = new BloomCuckooCommander() public bloomTdigestCommander = new BloomTdigestCommander() public bloomTopkCommander = new BloomTopkCommander() public aiCommander = new RedisAICommander() public searchCommander = new SearchCommander() public gearsCommander = new GearsCommander() public graphCommander = new GraphCommander() public rejsonCommander = new RejsonCommander() public risCommander = new RedisIntervalSetsCommander() public rtsCommander = new RedisTimeSeriesCommander() public searchHelpers = new RedisearchHelpers(); public risHelpers = new RedisIntervalSetsHelpers(); /** * Initializing the module object * @param name The name of the module * @param clusterNodes The nodes of the cluster * @param moduleOptions The additional module options * @param moduleOptions.isHandleError If to throw error on error * @param moduleOptions.showDebugLogs If to print debug logs * @param clusterOptions The options of the clusters */ constructor(clusterNodes: IORedis.ClusterNode[], moduleOptions?: RedisModuleOptions, clusterOptions?: IORedis.ClusterOptions) /** * Initializing the module object * @param name The name of the module * @param redisOptions The options of the redis database * @param moduleOptions The additional module options * @param moduleOptions.isHandleError If to throw error on error * @param moduleOptions.showDebugLogs If to print debug logs */ constructor(redisOptions: IORedis.RedisOptions, moduleOptions?: RedisModuleOptions) constructor(options: IORedis.RedisOptions & IORedis.ClusterNode[], moduleOptions?: RedisModuleOptions, clusterOptions?: IORedis.ClusterOptions) { super(RedisModules.name, options, moduleOptions, clusterOptions); this.applyMixins(RedisModules, [ RedisAI, RedisIntervalSets, RedisBloom, RedisBloomCMK, RedisBloomCuckoo, RedisBloomTopK, RedisBloomTDigest, Redisearch, RedisGears, RedisGraph, ReJSON, RedisTimeSeries, RedisIntervalSets ]) } /** * Applying mixings of given objects into base object * @param baseObject The base objects * @param givenObjects An array of given objects * @param addPrefix If to add a prefix of Object name to the properties as ObjectName_FunctionName */ private applyMixins(baseObject: any, givenObjects: any[], addPrefix = true): void { givenObjects.forEach(givenObject => { Object.getOwnPropertyNames(givenObject.prototype).forEach((name: string) => { if(name !== 'constructor'){ const functionName = addPrefix ? `${modulePropNames[givenObject.name]}_${name}`: name; Object.defineProperty(baseObject.prototype, functionName, Object.getOwnPropertyDescriptor(givenObject.prototype, name)); } }); }); } } /** * The Redis 'All in One' RedisIntervalSet module functions */ export type RedisIntervalSetMixin = { ris_module_add: typeof RedisIntervalSets.prototype.add, ris_module_get: typeof RedisIntervalSets.prototype.get, ris_module_del: typeof RedisIntervalSets.prototype.del, ris_module_score: typeof RedisIntervalSets.prototype.score, ris_module_notScore: typeof RedisIntervalSets.prototype.notScore } /** * The Redis 'All in One' RedisAI module functions */ export type RedisAIMixin = { redisaiCommander: RedisAICommander, ai_module_tensorset: typeof RedisAI.prototype.tensorset, ai_module_tensorget: typeof RedisAI.prototype.tensorget, ai_module_modeldel: typeof RedisAI.prototype.modeldel, ai_module_modelstore: typeof RedisAI.prototype.modelstore, ai_module_modelget: typeof RedisAI.prototype.modelget, ai_module_modelexecute: typeof RedisAI.prototype.modelexecute, ai_module_modelscan: typeof RedisAI.prototype.modelscan, ai_module_scriptset: typeof RedisAI.prototype.scriptset, ai_module_scriptget: typeof RedisAI.prototype.scriptget, ai_module_scriptdel: typeof RedisAI.prototype.scriptdel, ai_module_scriptexecute: typeof RedisAI.prototype.scriptexecute, ai_module_scriptscan: typeof RedisAI.prototype.scriptscan, ai_module_dagexecute: typeof RedisAI.prototype.dagexecute, ai_module_dagexecuteRO: typeof RedisAI.prototype.dagexecuteRO, ai_module_info: typeof RedisAI.prototype.info, ai_module_config: typeof RedisAI.prototype.config } /** * The Redis 'All in One' RedisBloom module functions */ export type RedisBloomMixin = { bloom_module_reserve: typeof RedisBloom.prototype.reserve, bloom_module_add: typeof RedisBloom.prototype.add, bloom_module_madd: typeof RedisBloom.prototype.madd, bloom_module_insert: typeof RedisBloom.prototype.insert, bloom_module_exists: typeof RedisBloom.prototype.exists, bloom_module_mexists: typeof RedisBloom.prototype.mexists, bloom_module_scandump: typeof RedisBloom.prototype.scandump, bloom_module_loadchunk: typeof RedisBloom.prototype.loadchunk, bloom_module_info: typeof RedisBloom.prototype.info } /** * The Redis 'All in One' RedisBloomCMK module functions */ export type RedisBloomCMKMixin = { bloom_cmk_module_initbydim: typeof RedisBloomCMK.prototype.initbydim, bloom_cmk_module_initbyprob: typeof RedisBloomCMK.prototype.initbyprob, bloom_cmk_module_incrby: typeof RedisBloomCMK.prototype.incrby, bloom_cmk_module_query: typeof RedisBloomCMK.prototype.query, bloom_cmk_module_merge: typeof RedisBloomCMK.prototype.merge, bloom_cmk_module_info: typeof RedisBloomCMK.prototype.info } /** * The Redis 'All in One' RedisBloomCuckoo module functions */ export type RedisBloomCuckooMixin = { bloom_cuckoo_module_reserve: typeof RedisBloomCuckoo.prototype.reserve, bloom_cuckoo_module_add: typeof RedisBloomCuckoo.prototype.add, bloom_cuckoo_module_addnx: typeof RedisBloomCuckoo.prototype.addnx, bloom_cuckoo_module_insert: typeof RedisBloomCuckoo.prototype.insert, bloom_cuckoo_module_insertnx: typeof RedisBloomCuckoo.prototype.insertnx, bloom_cuckoo_module_exists: typeof RedisBloomCuckoo.prototype.exists, bloom_cuckoo_module_del: typeof RedisBloomCuckoo.prototype.del, bloom_cuckoo_module_count: typeof RedisBloomCuckoo.prototype.count, bloom_cuckoo_module_scandump: typeof RedisBloomCuckoo.prototype.scandump, bloom_cuckoo_module_loadchunk: typeof RedisBloomCuckoo.prototype.loadchunk, bloom_cuckoo_module_info: typeof RedisBloomCuckoo.prototype.info } /** * The Redis 'All in One' RedisBloomTopK module functions */ export type RedisBloomTopKMixin = { bloom_topk_module_reserve: typeof RedisBloomTopK.prototype.reserve, bloom_topk_module_add: typeof RedisBloomTopK.prototype.add, bloom_topk_module_incrby: typeof RedisBloomTopK.prototype.incrby, bloom_topk_module_query: typeof RedisBloomTopK.prototype.query, bloom_topk_module_count: typeof RedisBloomTopK.prototype.count, bloom_topk_module_list: typeof RedisBloomTopK.prototype.list, bloom_topk_module_info: typeof RedisBloomTopK.prototype.info } /** * The Redis 'All in One' RedisBloomTDigest module functions */ export type RedisBloomTDigestMixin = { bloom_tdigest_module_create: typeof RedisBloomTDigest.prototype.create, bloom_tdigest_module_reset: typeof RedisBloomTDigest.prototype.reset, bloom_tdigest_module_add: typeof RedisBloomTDigest.prototype.add, bloom_tdigest_module_merge: typeof RedisBloomTDigest.prototype.merge, bloom_tdigest_module_max: typeof RedisBloomTDigest.prototype.max, bloom_tdigest_module_min: typeof RedisBloomTDigest.prototype.min, bloom_tdigest_module_quantile: typeof RedisBloomTDigest.prototype.quantile bloom_tdigest_module_cdf: typeof RedisBloomTDigest.prototype.cdf bloom_tdigest_module_info: typeof RedisBloomTDigest.prototype.info } /** * The Redis 'All in One' Redisearch module functions */ export type RedisearchMixin = { search_module_create: typeof Redisearch.prototype.create, search_module_search: typeof Redisearch.prototype.search, search_module_aggregate: typeof Redisearch.prototype.aggregate, search_module_explain: typeof Redisearch.prototype.explain, search_module_explainCLI: typeof Redisearch.prototype.explainCLI, search_module_alter: typeof Redisearch.prototype.alter, search_module_dropindex: typeof Redisearch.prototype.dropindex, search_module_aliasadd: typeof Redisearch.prototype.aliasadd, search_module_aliasupdate: typeof Redisearch.prototype.aliasupdate, search_module_aliasdel: typeof Redisearch.prototype.aliasdel, search_module_tagvals: typeof Redisearch.prototype.tagvals, search_module_sugadd: typeof Redisearch.prototype.sugadd, search_module_sugget: typeof Redisearch.prototype.sugget, search_module_sugdel: typeof Redisearch.prototype.sugdel, search_module_suglen: typeof Redisearch.prototype.suglen, search_module_synupdate: typeof Redisearch.prototype.synupdate, search_module_syndump: typeof Redisearch.prototype.syndump, search_module_spellcheck: typeof Redisearch.prototype.spellcheck, search_module_dictadd: typeof Redisearch.prototype.dictadd, search_module_dictdel: typeof Redisearch.prototype.dictdel, search_module_dictdump: typeof Redisearch.prototype.dictdump, search_module_info: typeof Redisearch.prototype.info, search_module_config: typeof Redisearch.prototype.config } /** * The Redis 'All in One' RedisGears module functions */ export type RedisGearsMixin = { gears_module_abortExecution: typeof RedisGears.prototype.abortExecution, gears_module_configGet: typeof RedisGears.prototype.configGet, gears_module_configSet: typeof RedisGears.prototype.configSet, gears_module_dropExecution: typeof RedisGears.prototype.dropExecution, gears_module_dumpExecutions: typeof RedisGears.prototype.dumpExecutions, gears_module_dumpRegistrations: typeof RedisGears.prototype.dumpRegistrations, gears_module_getExecution: typeof RedisGears.prototype.getExecution, gears_module_getResults: typeof RedisGears.prototype.getResults, gears_module_getResultsBlocking: typeof RedisGears.prototype.getResultsBlocking, gears_module_infocluster: typeof RedisGears.prototype.infocluster, gears_module_pyexecute: typeof RedisGears.prototype.pyexecute, gears_module_pystats: typeof RedisGears.prototype.pystats, gears_module_pydumpreqs: typeof RedisGears.prototype.pydumpreqs, gears_module_refreshCluster: typeof RedisGears.prototype.refreshCluster, gears_module_trigger: typeof RedisGears.prototype.trigger, gears_module_unregister: typeof RedisGears.prototype.unregister } /** * The Redis 'All in One' RedisGraph module functions */ export type RedisGraphMixin = { graph_module_query: typeof RedisGraph.prototype.query, graph_module_readonlyQuery: typeof RedisGraph.prototype.readonlyQuery, graph_module_profile: typeof RedisGraph.prototype.profile, graph_module_delete: typeof RedisGraph.prototype.delete, graph_module_explain: typeof RedisGraph.prototype.explain, graph_module_slowlog: typeof RedisGraph.prototype.slowlog, graph_module_config: typeof RedisGraph.prototype.config, } /** * The Redis 'All in One' ReJSON module functions */ export type ReJSONMixin = { rejson_module_del: typeof ReJSON.prototype.del, rejson_module_set: typeof ReJSON.prototype.set, rejson_module_get: typeof ReJSON.prototype.get, rejson_module_mget: typeof ReJSON.prototype.mget, rejson_module_type: typeof ReJSON.prototype.type, rejson_module_numincrby: typeof ReJSON.prototype.numincrby, rejson_module_nummultby: typeof ReJSON.prototype.nummultby, rejson_module_strappend: typeof ReJSON.prototype.strappend, rejson_module_strlen: typeof ReJSON.prototype.strlen, rejson_module_arrappend: typeof ReJSON.prototype.arrappend, rejson_module_arrindex: typeof ReJSON.prototype.arrindex, rejson_module_arrinsert: typeof ReJSON.prototype.arrinsert, rejson_module_arrlen: typeof ReJSON.prototype.arrlen, rejson_module_arrpop: typeof ReJSON.prototype.arrpop, rejson_module_arrtrim: typeof ReJSON.prototype.arrtrim, rejson_module_objkeys: typeof ReJSON.prototype.objkeys, rejson_module_objlen: typeof ReJSON.prototype.objlen, rejson_module_debug: typeof ReJSON.prototype.debug, rejson_module_forget: typeof ReJSON.prototype.forget rejson_module_resp: typeof ReJSON.prototype.resp, rejson_module_clear: typeof ReJSON.prototype.clear, rejson_module_toggle: typeof ReJSON.prototype.toggle } /** * The Redis 'All in One' RedisTimeSeries module functions */ export type RedisTimeSeriesMixin = { rts_module_create: typeof RedisTimeSeries.prototype.create, rts_module_alter: typeof RedisTimeSeries.prototype.alter, rts_module_add: typeof RedisTimeSeries.prototype.add, rts_module_madd: typeof RedisTimeSeries.prototype.madd, rts_module_incrby: typeof RedisTimeSeries.prototype.incrby, rts_module_decrby: typeof RedisTimeSeries.prototype.decrby, rts_module_createrule: typeof RedisTimeSeries.prototype.createrule, rts_module_deleterule: typeof RedisTimeSeries.prototype.deleterule, rts_module_range: typeof RedisTimeSeries.prototype.range, rts_module_revrange: typeof RedisTimeSeries.prototype.revrange, rts_module_mrange: typeof RedisTimeSeries.prototype.mrange, rts_module_mrevrange: typeof RedisTimeSeries.prototype.mrevrange, rts_module_get: typeof RedisTimeSeries.prototype.get, rts_module_mget: typeof RedisTimeSeries.prototype.mget, rts_module_info: typeof RedisTimeSeries.prototype.info rts_module_queryindex: typeof RedisTimeSeries.prototype.queryindex, rts_module_del: typeof RedisTimeSeries.prototype.del } /** * A list of converted Redis 'All in One' sub function prefixes per module */ export const modulePropNames = { RedisAI: 'ai_module', RedisIntervalSets: 'ris_module', RedisBloom: 'bloom_module', RedisBloomCMK: 'bloom_cmk_module', RedisBloomCuckoo: 'bloom_cuckoo_module', RedisBloomTopK: 'bloom_topk_module', RedisBloomTDigest: 'bloom_tdigest_module', Redisearch: 'search_module', RedisGears: 'gears_module', RedisGraph: 'graph_module', ReJSON: 'rejson_module', RedisTimeSeries: 'rts_module', } /** * A definition of all the modules functions to be under the Redis 'All in One' */ export interface RedisModules extends RedisAIMixin, RedisBloomCMKMixin, RedisBloomCuckooMixin, RedisBloomTopKMixin, RedisBloomMixin, RedisBloomTDigestMixin, RedisearchMixin, RedisGearsMixin, RedisGraphMixin, ReJSONMixin, RedisIntervalSetMixin, RedisTimeSeriesMixin {}
the_stack
module es { /** * 表示右手3 * 3的浮点矩阵,可以存储平移、缩放和旋转信息。 */ export class Matrix2D implements IEquatable<Matrix2D> { public m11: number = 0; // x 缩放 public m12: number = 0; public m21: number = 0; public m22: number = 0; public m31: number = 0; public m32: number = 0; /** * 返回标识矩阵 */ public static get identity(): Matrix2D { return new Matrix2D().setIdentity(); } public setIdentity(): Matrix2D { return this.setValues(1, 0, 0, 1, 0, 0); } public setValues( m11: number, m12: number, m21: number, m22: number, m31: number, m32: number ): Matrix2D { this.m11 = m11; this.m12 = m12; this.m21 = m21; this.m22 = m22; this.m31 = m31; this.m32 = m32; return this; } /** * 储存在该矩阵中的位置 */ public get translation(): Vector2 { return new Vector2(this.m31, this.m32); } public set translation(value: Vector2) { this.m31 = value.x; this.m32 = value.y; } /** * 以弧度为单位的旋转,存储在这个矩阵中 */ public get rotation(): number { return Math.atan2(this.m21, this.m11); } public set rotation(value: number) { let val1 = Math.cos(value); let val2 = Math.sin(value); this.m11 = val1; this.m12 = val2; this.m21 = -val2; this.m22 = val1; } /** * 矩阵中存储的旋转度数 */ public get rotationDegrees() { return MathHelper.toDegrees(this.rotation); } public set rotationDegrees(value: number) { this.rotation = MathHelper.toRadians(value); } /** * 储存在这个矩阵中的缩放 */ public get scale(): Vector2 { return new Vector2(this.m11, this.m22); } public set scale(value: Vector2) { this.m11 = value.x; this.m22 = value.y; } /** * 创建一个新的围绕Z轴的旋转矩阵2D * @param radians */ public static createRotation(radians: number, result: Matrix2D) { result.setIdentity(); const val1 = Math.cos(radians); const val2 = Math.sin(radians); result.m11 = val1; result.m12 = val2; result.m21 = val2 * -1; result.m22 = val1; } public static createRotationOut(radians: number, result: Matrix2D) { let val1 = Math.cos(radians); let val2 = Math.sin(radians); result.m11 = val1; result.m12 = val2; result.m21 = -val2; result.m22 = val1; } /** * 创建一个新的缩放矩阵2D * @param xScale * @param yScale */ public static createScale(xScale: number, yScale: number, result: Matrix2D) { result.m11 = xScale; result.m12 = 0; result.m21 = 0; result.m22 = yScale; result.m31 = 0; result.m32 = 0; } public static createScaleOut(xScale: number, yScale: number, result: Matrix2D) { result.m11 = xScale; result.m12 = 0; result.m21 = 0; result.m22 = yScale; result.m31 = 0; result.m32 = 0; } /** * 创建一个新的平移矩阵2D * @param xPosition * @param yPosition */ public static createTranslation(xPosition: number, yPosition: number, result: Matrix2D) { result.m11 = 1; result.m12 = 0; result.m21 = 0; result.m22 = 1; result.m31 = xPosition; result.m32 = yPosition; return result; } public static createTranslationOut(position: Vector2, result: Matrix2D) { result.m11 = 1; result.m12 = 0; result.m21 = 0; result.m22 = 1; result.m31 = position.x; result.m32 = position.y; } public static invert(matrix: Matrix2D) { let det = 1 / matrix.determinant(); let result = this.identity; result.m11 = matrix.m22 * det; result.m12 = -matrix.m12 * det; result.m21 = -matrix.m21 * det; result.m22 = matrix.m11 * det; result.m31 = (matrix.m32 * matrix.m21 - matrix.m31 * matrix.m22) * det; result.m32 = -(matrix.m32 * matrix.m11 - matrix.m31 * matrix.m12) * det; return result; } /** * 创建一个新的matrix, 它包含两个矩阵的和。 * @param matrix */ public add(matrix: Matrix2D): Matrix2D { this.m11 += matrix.m11; this.m12 += matrix.m12; this.m21 += matrix.m21; this.m22 += matrix.m22; this.m31 += matrix.m31; this.m32 += matrix.m32; return this; } public substract(matrix: Matrix2D): Matrix2D { this.m11 -= matrix.m11; this.m12 -= matrix.m12; this.m21 -= matrix.m21; this.m22 -= matrix.m22; this.m31 -= matrix.m31; this.m32 -= matrix.m32; return this; } public divide(matrix: Matrix2D): Matrix2D { this.m11 /= matrix.m11; this.m12 /= matrix.m12; this.m21 /= matrix.m21; this.m22 /= matrix.m22; this.m31 /= matrix.m31; this.m32 /= matrix.m32; return this; } public multiply(matrix: Matrix2D): Matrix2D { let m11 = (this.m11 * matrix.m11) + (this.m12 * matrix.m21); let m12 = (this.m11 * matrix.m12) + (this.m12 * matrix.m22); let m21 = (this.m21 * matrix.m11) + (this.m22 * matrix.m21); let m22 = (this.m21 * matrix.m12) + (this.m22 * matrix.m22); let m31 = (this.m31 * matrix.m11) + (this.m32 * matrix.m21) + matrix.m31; let m32 = (this.m31 * matrix.m12) + (this.m32 * matrix.m22) + matrix.m32; this.m11 = m11; this.m12 = m12; this.m21 = m21; this.m22 = m22; this.m31 = m31; this.m32 = m32; return this; } public static multiply(matrix1: Matrix2D, matrix2: Matrix2D, result: Matrix2D) { const m11 = (matrix1.m11 * matrix2.m11) + (matrix1.m12 * matrix2.m21); const m12 = (matrix1.m11 * matrix2.m12) + (matrix1.m12 * matrix2.m22); const m21 = (matrix1.m21 * matrix2.m11) + (matrix1.m22 * matrix2.m21); const m22 = (matrix1.m21 * matrix2.m12) + (matrix1.m22 * matrix2.m22); const m31 = (matrix1.m31 * matrix2.m11) + (matrix1.m32 * matrix2.m21) + matrix2.m31; const m32 = (matrix1.m31 * matrix2.m12) + (matrix1.m32 * matrix2.m22) + matrix2.m32; result.m11 = m11; result.m12 = m12; result.m21 = m21; result.m22 = m22; result.m31 = m31; result.m32 = m32; } public determinant() { return this.m11 * this.m22 - this.m12 * this.m21; } /** * 创建一个新的Matrix2D,包含指定矩阵中的线性插值。 * @param matrix1 * @param matrix2 * @param amount */ public static lerp(matrix1: Matrix2D, matrix2: Matrix2D, amount: number) { matrix1.m11 = matrix1.m11 + ((matrix2.m11 - matrix1.m11) * amount); matrix1.m12 = matrix1.m12 + ((matrix2.m12 - matrix1.m12) * amount); matrix1.m21 = matrix1.m21 + ((matrix2.m21 - matrix1.m21) * amount); matrix1.m22 = matrix1.m22 + ((matrix2.m22 - matrix1.m22) * amount); matrix1.m31 = matrix1.m31 + ((matrix2.m31 - matrix1.m31) * amount); matrix1.m32 = matrix1.m32 + ((matrix2.m32 - matrix1.m32) * amount); return matrix1; } /** * 交换矩阵的行和列 * @param matrix */ public static transpose(matrix: Matrix2D) { let ret: Matrix2D = this.identity; ret.m11 = matrix.m11; ret.m12 = matrix.m21; ret.m21 = matrix.m12; ret.m22 = matrix.m22; ret.m31 = 0; ret.m32 = 0; return ret; } public mutiplyTranslation(x: number, y: number) { let trans = new Matrix2D(); Matrix2D.createTranslation(x, y, trans); return MatrixHelper.mutiply(this, trans); } /** * 比较当前实例是否等于指定的Matrix2D * @param other */ public equals(other: Matrix2D) { return this == other; } public static toMatrix(mat: Matrix2D) { let matrix = new Matrix(); matrix.m11 = mat.m11; matrix.m12 = mat.m12; matrix.m13 = 0; matrix.m14 = 0; matrix.m21 = mat.m21; matrix.m22 = mat.m22; matrix.m23 = 0; matrix.m24 = 0; matrix.m31 = 0; matrix.m32 = 0; matrix.m33 = 1; matrix.m34 = 0; matrix.m41 = mat.m31; matrix.m42 = mat.m32; matrix.m43 = 0; matrix.m44 = 1; return matrix; } public toString() { return `{m11:${this.m11} m12:${this.m12} m21:${this.m21} m22:${this.m22} m31:${this.m31} m32:${this.m32}}` } } }
the_stack
function test_init() { Kakao.init('JAVASCRIPT_KEY'); console.log(Kakao.isInitialized()); } /** * Example from https://developers.kakao.com/docs/latest/ko/kakaologin/js#login */ function test_loginAuthorize() { Kakao.Auth.authorize({ redirectUri: '{REDIRECT_URI}', }); } function test_loginSetAccessToken() { const ACCESS_TOKEN = ''; Kakao.Auth.setAccessToken(ACCESS_TOKEN); } function test_logout() { if (!Kakao.Auth.getAccessToken()) { console.log('Not logged in.'); return; } Kakao.Auth.logout(() => { console.log(Kakao.Auth.getAccessToken()); }); } function test_userUnlink() { Kakao.API.request({ url: '/v1/user/unlink', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_userMe1() { Kakao.API.request({ url: '/v2/user/me', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); Kakao.API.request({ url: '/v2/user/me', data: { property_keys: ['kakao_account.email', 'kakao_account.gender'], }, success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_userUpdateProfile() { Kakao.API.request({ url: '/v1/user/update_profile', data: { properties: { nickname: '홍길동', age: '22', }, }, success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_loginAdditionalAgreement() { Kakao.Auth.authorize({ redirectUri: '{REDIRECT_URI}', scope: 'account_email,gender', }); Kakao.Auth.login({ scope: 'account_email,gender', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_loginUserAgreement() { Kakao.API.request({ url: '/v2/user/scopes', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); Kakao.API.request({ url: '/v2/user/scopes', data: { scopes: ['account_email', 'gender'], }, success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_loginUserRevokeAgreement() { Kakao.API.request({ url: '/v2/user/revoke/scopes', data: { scopes: ['account_email', 'gender'], }, success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_loginPopup() { Kakao.Auth.login({ success(response) { console.log(response); }, fail(error) { console.log(error); }, }); Kakao.Auth.createLoginButton({ container: '#CONTAINER_ID', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } /** * Example from https://developers.kakao.com/docs/latest/ko/kakaotalk-social/js */ function test_getProfile() { Kakao.API.request({ url: '/v1/api/talk/profile', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } function test_getFriends() { Kakao.API.request({ url: '/v1/api/talk/friends', success(response) { console.log(response); }, fail(error) { console.log(error); }, }); } /** * Example from https://developers.kakao.com/docs/latest/ko/message/js-link */ function test_linkCreateDefaultButtonTypeFeed() { Kakao.Link.createDefaultButton({ container: '#CONTAINER_ID', objectType: 'feed', content: { title: '디저트 사진', description: '아메리카노, 빵, 케익', imageUrl: 'http://mud-kage.kakao.co.kr/dn/NTmhS/btqfEUdFAUf/FjKzkZsnoeE4o19klTOVI1/openlink_640x640s.jpg', link: { mobileWebUrl: 'https://developers.kakao.com', androidExecParams: 'test', }, }, social: { likeCount: 10, commentCount: 20, sharedCount: 30, }, buttons: [ { title: '웹으로 이동', link: { mobileWebUrl: 'https://developers.kakao.com', }, }, { title: '앱으로 이동', link: { mobileWebUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkCreateDefaultButtonTypeList() { Kakao.Link.createDefaultButton({ container: '#create-kakao-link-btn', objectType: 'list', headerTitle: 'WEEKLY MAGAZINE', headerLink: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, contents: [ { title: '취미의 특징, 탁구', description: '스포츠', imageUrl: 'http://k.kakaocdn.net/dn/bDPMIb/btqgeoTRQvd/49BuF1gNo6UXkdbKecx600/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '크림으로 이해하는 커피이야기', description: '음식', imageUrl: 'http://k.kakaocdn.net/dn/QPeNt/btqgeSfSsCR/0QJIRuWTtkg4cYc57n8H80/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '감성이 가득한 분위기', description: '사진', imageUrl: 'http://k.kakaocdn.net/dn/c7MBX4/btqgeRgWhBy/ZMLnndJFAqyUAnqu4sQHS0/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], buttons: [ { title: '웹으로 보기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '앱으로 보기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkCreateDefaultButtonTypeLocation() { Kakao.Link.createDefaultButton({ container: '#create-kakao-link-btn', objectType: 'location', address: '경기 성남시 분당구 판교역로 235 에이치스퀘어 N동 8층', addressTitle: '카카오 판교오피스 카페톡', content: { title: '신메뉴 출시♥︎ 체리블라썸라떼', description: '이번 주는 체리블라썸라떼 1+1', imageUrl: 'http://k.kakaocdn.net/dn/bSbH9w/btqgegaEDfW/vD9KKV0hEintg6bZT4v4WK/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, social: { likeCount: 286, commentCount: 45, sharedCount: 845, }, buttons: [ { title: '웹으로 보기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkCreateDefaultButtonTypeCommerce() { Kakao.Link.createDefaultButton({ container: '#create-kakao-link-btn', objectType: 'commerce', content: { title: '언제 어디든, 더 쉽고 편하게 당신의 일상을 더 즐겁게, 헤이 라이언의 이야기를 들려드릴게요.', imageUrl: 'http://k.kakaocdn.net/dn/dScJiJ/btqB3cwK1Hi/pv5qHVwetz5RZfPZR3C5K1/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, commerce: { productName: '카카오미니', regularPrice: 100000, discountRate: 10, discountPrice: 90000, }, buttons: [ { title: '구매하기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '공유하기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkCreateDefaultButtonTypeText() { Kakao.Link.createDefaultButton({ container: '#create-kakao-link-btn', objectType: 'text', text: '기본 템플릿으로 제공되는 텍스트 템플릿은 텍스트를 최대 200자까지 표시할 수 있습니다. 텍스트 템플릿은 텍스트 영역과 하나의 기본 버튼을 가집니다. 임의의 버튼을 설정할 수도 있습니다. 여러 장의 이미지, 프로필 정보 등 보다 확장된 형태의 카카오링크는 다른 템플릿을 이용해 보낼 수 있습니다.', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }); } function test_linkSendDefaultTypeFeed() { Kakao.Link.sendDefault({ objectType: 'feed', content: { title: '디저트 사진', description: '아메리카노, 빵, 케익', imageUrl: 'http://mud-kage.kakao.co.kr/dn/NTmhS/btqfEUdFAUf/FjKzkZsnoeE4o19klTOVI1/openlink_640x640s.jpg', link: { mobileWebUrl: 'https://developers.kakao.com', androidExecParams: 'test', }, }, social: { likeCount: 10, commentCount: 20, sharedCount: 30, }, buttons: [ { title: '웹으로 이동', link: { mobileWebUrl: 'https://developers.kakao.com', }, }, { title: '앱으로 이동', link: { mobileWebUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkSendDefaultTypeList() { Kakao.Link.sendDefault({ objectType: 'list', headerTitle: 'WEEKLY MAGAZINE', headerLink: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, contents: [ { title: '취미의 특징, 탁구', description: '스포츠', imageUrl: 'http://k.kakaocdn.net/dn/bDPMIb/btqgeoTRQvd/49BuF1gNo6UXkdbKecx600/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '크림으로 이해하는 커피이야기', description: '음식', imageUrl: 'http://k.kakaocdn.net/dn/QPeNt/btqgeSfSsCR/0QJIRuWTtkg4cYc57n8H80/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '감성이 가득한 분위기', description: '사진', imageUrl: 'http://k.kakaocdn.net/dn/c7MBX4/btqgeRgWhBy/ZMLnndJFAqyUAnqu4sQHS0/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], buttons: [ { title: '웹으로 보기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '앱으로 보기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkSendDefaultTypeLocation() { Kakao.Link.sendDefault({ objectType: 'location', address: '경기 성남시 분당구 판교역로 235 에이치스퀘어 N동 8층', addressTitle: '카카오 판교오피스 카페톡', content: { title: '신메뉴 출시♥︎ 체리블라썸라떼', description: '이번 주는 체리블라썸라떼 1+1', imageUrl: 'http://k.kakaocdn.net/dn/bSbH9w/btqgegaEDfW/vD9KKV0hEintg6bZT4v4WK/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, social: { likeCount: 286, commentCount: 45, sharedCount: 845, }, buttons: [ { title: '웹으로 보기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkSendDefaultTypeCommerce() { Kakao.Link.sendDefault({ objectType: 'commerce', content: { title: '언제 어디든, 더 쉽고 편하게 당신의 일상을 더 즐겁게, 헤이 라이언의 이야기를 들려드릴게요.', imageUrl: 'http://k.kakaocdn.net/dn/dScJiJ/btqB3cwK1Hi/pv5qHVwetz5RZfPZR3C5K1/kakaolink40_original.png', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, commerce: { productName: '카카오미니', regularPrice: 100000, discountRate: 10, discountPrice: 90000, }, buttons: [ { title: '구매하기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, { title: '공유하기', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }, ], }); } function test_linkSendDefaultTypeText() { Kakao.Link.sendDefault({ objectType: 'text', text: '기본 템플릿으로 제공되는 텍스트 템플릿은 텍스트를 최대 200자까지 표시할 수 있습니다. 텍스트 템플릿은 텍스트 영역과 하나의 기본 버튼을 가집니다. 임의의 버튼을 설정할 수도 있습니다. 여러 장의 이미지, 프로필 정보 등 보다 확장된 형태의 카카오링크는 다른 템플릿을 이용해 보낼 수 있습니다.', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, }); } const TEMPLATE_ID = 0; // templateId is kakao api integer key function test_linkCreateCustomButton() { Kakao.Link.createCustomButton({ container: '#kakao-link-btn', templateId: TEMPLATE_ID, templateArgs: { title: '제목 영역입니다.', description: '설명 영역입니다.', }, }); } function test_linkSendCustom() { Kakao.Link.sendCustom({ templateId: TEMPLATE_ID, templateArgs: { title: '제목 영역입니다.', description: '설명 영역입니다.', }, }); } function test_linkCreateScrapButtonDefault() { Kakao.Link.createScrapButton({ container: '#kakao-link-btn', requestUrl: 'https://developers.kakao.com', }); } function test_linkSendScrapDefault() { Kakao.Link.sendScrap({ requestUrl: 'https://developers.kakao.com', }); } function test_linkCreateScrapButtonCustom() { Kakao.Link.createScrapButton({ container: '#kakao-link-btn', requestUrl: 'https://developers.kakao.com', templateId: TEMPLATE_ID, }); } function test_linkCreateSendScrapCustom() { Kakao.Link.sendScrap({ requestUrl: 'https://developers.kakao.com', templateId: TEMPLATE_ID, }); } function test_linkSuccessCallback() { Kakao.Link.sendDefault({ objectType: 'text', text: '간단한 JavaScript SDK 샘플과 함께 카카오 플랫폼 서비스 개발을 시작해 보세요.', link: { mobileWebUrl: 'https://developers.kakao.com', webUrl: 'https://developers.kakao.com', }, serverCallbackArgs: { // 사용자 정의 파라미터 설정 key: 'value', }, }); } function test_linkImageUpload() { const files = new FileList(); Kakao.Link.uploadImage({ file: files, }).then(res => { console.log(res); }); } function test_linkImageScrap() { const url = ''; Kakao.Link.scrapImage({ imageUrl: url, }).then(res => { console.log(res); }); } function test_linkImageDelete() { const url = ''; Kakao.Link.deleteImage({ imageUrl: url, }); } /** * Example from https://developers.kakao.com/docs/latest/ko/kakaostory/js */ function test_storyCreateFollowButton() { Kakao.Story.createFollowButton({ container: '#kakaostory-follow-button', id: 'kakao', }); } function test_storyCreateShareButton() { Kakao.Story.createShareButton({ container: '#kakaostory-share-button', url: 'https://developers.kakao.com', text: '카카오 개발자 사이트로 놀러오세요! #개발자 #카카오 :)', }); } function test_storyOpen() { Kakao.Story.open({ url: 'http://blog.kakaocorp.co.kr/390', text: '카카오검색에서 카카오스토리를! #카카오스토리 #카카오검색 :)', }); } function test_storyShare() { Kakao.Story.share({ url: 'https://developers.kakao.com', text: '카카오 개발자 사이트로 놀러오세요! #개발자 #카카오 :)', }); } /** * Example from https://developers.kakao.com/docs/latest/ko/kakaonavi/js */ function test_naviStart() { Kakao.Navi.start({ name: '현대백화점 판교점', x: 127.11205203011632, y: 37.39279717586919, coordType: 'wgs84', }); } function test_naviShare() { Kakao.Navi.share({ name: '현대백화점 판교점', x: 127.11205203011632, y: 37.39279717586919, coordType: 'wgs84', }); }
the_stack
import * as iam from '@aws-cdk/aws-iam'; import { Duration, IResource, Resource } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { CloudFormationInit } from './cfn-init'; import { Connections, IConnectable } from './connections'; import { CfnInstance } from './ec2.generated'; import { InstanceType } from './instance-types'; import { IMachineImage, OperatingSystemType } from './machine-image'; import { ISecurityGroup } from './security-group'; import { UserData } from './user-data'; import { BlockDevice } from './volume'; import { IVpc, SubnetSelection } from './vpc'; /** * @stability stable */ export interface IInstance extends IResource, IConnectable, iam.IGrantable { /** * The instance's ID. * * @stability stable * @attribute true */ readonly instanceId: string; /** * The availability zone the instance was launched in. * * @stability stable * @attribute true */ readonly instanceAvailabilityZone: string; /** * Private DNS name for this instance. * * @stability stable * @attribute true */ readonly instancePrivateDnsName: string; /** * Private IP for this instance. * * @stability stable * @attribute true */ readonly instancePrivateIp: string; /** * Publicly-routable DNS name for this instance. * * (May be an empty string if the instance does not have a public name). * * @stability stable * @attribute true */ readonly instancePublicDnsName: string; /** * Publicly-routable IP address for this instance. * * (May be an empty string if the instance does not have a public IP). * * @stability stable * @attribute true */ readonly instancePublicIp: string; } /** * Properties of an EC2 Instance. * * @stability stable */ export interface InstanceProps { /** * Name of SSH keypair to grant access to instance. * * @default - No SSH access will be possible. * @stability stable */ readonly keyName?: string; /** * Where to place the instance within the VPC. * * @default - Private subnets. * @stability stable */ readonly vpcSubnets?: SubnetSelection; /** * In which AZ to place the instance within the VPC. * * @default - Random zone. * @stability stable */ readonly availabilityZone?: string; /** * Whether the instance could initiate connections to anywhere by default. * * This property is only used when you do not provide a security group. * * @default true * @stability stable */ readonly allowAllOutbound?: boolean; /** * The length of time to wait for the resourceSignalCount. * * The maximum value is 43200 (12 hours). * * @default Duration.minutes(5) * @stability stable */ readonly resourceSignalTimeout?: Duration; /** * VPC to launch the instance in. * * @stability stable */ readonly vpc: IVpc; /** * Security Group to assign to this instance. * * @default - create new security group * @stability stable */ readonly securityGroup?: ISecurityGroup; /** * Type of instance to launch. * * @stability stable */ readonly instanceType: InstanceType; /** * AMI to launch. * * @stability stable */ readonly machineImage: IMachineImage; /** * Specific UserData to use. * * The UserData may still be mutated after creation. * * @default - A UserData object appropriate for the MachineImage's * Operating System is created. * @stability stable */ readonly userData?: UserData; /** * Changes to the UserData force replacement. * * Depending the EC2 instance type, changing UserData either * restarts the instance or replaces the instance. * * - Instance store-backed instances are replaced. * - EBS-backed instances are restarted. * * By default, restarting does not execute the new UserData so you * will need a different mechanism to ensure the instance is restarted. * * Setting this to `true` will make the instance's Logical ID depend on the * UserData, which will cause CloudFormation to replace it if the UserData * changes. * * @default - true iff `initOptions` is specified, false otherwise. * @stability stable */ readonly userDataCausesReplacement?: boolean; /** * An IAM role to associate with the instance profile assigned to this Auto Scaling Group. * * The role must be assumable by the service principal `ec2.amazonaws.com`: * * @default - A role will automatically be created, it can be accessed via the `role` property * @stability stable * @example * * const role = new iam.Role(this, 'MyRole', { * assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com') * }); */ readonly role?: iam.IRole; /** * The name of the instance. * * @default - CDK generated name * @stability stable */ readonly instanceName?: string; /** * Specifies whether to enable an instance launched in a VPC to perform NAT. * * This controls whether source/destination checking is enabled on the instance. * A value of true means that checking is enabled, and false means that checking is disabled. * The value must be false for the instance to perform NAT. * * @default true * @stability stable */ readonly sourceDestCheck?: boolean; /** * Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes. * * Each instance that is launched has an associated root device volume, * either an Amazon EBS volume or an instance store volume. * You can use block device mappings to specify additional EBS volumes or * instance store volumes to attach to an instance when it is launched. * * @default - Uses the block device mapping of the AMI * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html * @stability stable */ readonly blockDevices?: BlockDevice[]; /** * Defines a private IP address to associate with an instance. * * Private IP should be available within the VPC that the instance is build within. * * @default - no association * @stability stable */ readonly privateIpAddress?: string; /** * Apply the given CloudFormation Init configuration to the instance at startup. * * @default - no CloudFormation init * @stability stable */ readonly init?: CloudFormationInit; /** * Use the given options for applying CloudFormation Init. * * Describes the configsets to use and the timeout to wait * * @default - default options * @stability stable */ readonly initOptions?: ApplyCloudFormationInitOptions; } /** * This represents a single EC2 instance. * * @stability stable */ export declare class Instance extends Resource implements IInstance { /** * The type of OS the instance is running. * * @stability stable */ readonly osType: OperatingSystemType; /** * Allows specify security group connections for the instance. * * @stability stable */ readonly connections: Connections; /** * The IAM role assumed by the instance. * * @stability stable */ readonly role: iam.IRole; /** * The principal to grant permissions to. * * @stability stable */ readonly grantPrincipal: iam.IPrincipal; /** * UserData for the instance. * * @stability stable */ readonly userData: UserData; /** * the underlying instance resource. * * @stability stable */ readonly instance: CfnInstance; /** * The instance's ID. * * @stability stable * @attribute true */ readonly instanceId: string; /** * The availability zone the instance was launched in. * * @stability stable * @attribute true */ readonly instanceAvailabilityZone: string; /** * Private DNS name for this instance. * * @stability stable * @attribute true */ readonly instancePrivateDnsName: string; /** * Private IP for this instance. * * @stability stable * @attribute true */ readonly instancePrivateIp: string; /** * Publicly-routable DNS name for this instance. * * (May be an empty string if the instance does not have a public name). * * @stability stable * @attribute true */ readonly instancePublicDnsName: string; /** * Publicly-routable IP address for this instance. * * (May be an empty string if the instance does not have a public IP). * * @stability stable * @attribute true */ readonly instancePublicIp: string; private readonly securityGroup; private readonly securityGroups; /** * @stability stable */ constructor(scope: Construct, id: string, props: InstanceProps); /** * Add the security group to the instance. * * @param securityGroup : The security group to add. * @stability stable */ addSecurityGroup(securityGroup: ISecurityGroup): void; /** * Add command to the startup script of the instance. * * The command must be in the scripting language supported by the instance's OS (i.e. Linux/Windows). * * @stability stable */ addUserData(...commands: string[]): void; /** * Adds a statement to the IAM role assumed by the instance. * * @stability stable */ addToRolePolicy(statement: iam.PolicyStatement): void; /** * Use a CloudFormation Init configuration at instance startup * * This does the following: * * - Attaches the CloudFormation Init metadata to the Instance resource. * - Add commands to the instance UserData to run `cfn-init` and `cfn-signal`. * - Update the instance's CreationPolicy to wait for the `cfn-signal` commands. */ private applyCloudFormationInit; /** * Wait for a single additional resource signal * * Add 1 to the current ResourceSignal Count and add the given timeout to the current timeout. * * Use this to pause the CloudFormation deployment to wait for the instances * in the AutoScalingGroup to report successful startup during * creation and updates. The UserData script needs to invoke `cfn-signal` * with a success or failure code after it is done setting up the instance. */ private waitForResourceSignal; /** * Apply CloudFormation update policies for the instance */ private applyUpdatePolicies; } /** * Options for applying CloudFormation init to an instance or instance group. * * @stability stable */ export interface ApplyCloudFormationInitOptions { /** * ConfigSet to activate. * * @default ['default'] * @stability stable */ readonly configSets?: string[]; /** * Timeout waiting for the configuration to be applied. * * @default Duration.minutes(5) * @stability stable */ readonly timeout?: Duration; /** * Force instance replacement by embedding a config fingerprint. * * If `true` (the default), a hash of the config will be embedded into the * UserData, so that if the config changes, the UserData changes. * * - If the EC2 instance is instance-store backed or * `userDataCausesReplacement` is set, this will cause the instance to be * replaced and the new configuration to be applied. * - If the instance is EBS-backed and `userDataCausesReplacement` is not * set, the change of UserData will make the instance restart but not be * replaced, and the configuration will not be applied automatically. * * If `false`, no hash will be embedded, and if the CloudFormation Init * config changes nothing will happen to the running instance. If a * config update introduces errors, you will not notice until after the * CloudFormation deployment successfully finishes and the next instance * fails to launch. * * @default true * @stability stable */ readonly embedFingerprint?: boolean; /** * Print the results of running cfn-init to the Instance System Log. * * By default, the output of running cfn-init is written to a log file * on the instance. Set this to `true` to print it to the System Log * (visible from the EC2 Console), `false` to not print it. * * (Be aware that the system log is refreshed at certain points in * time of the instance life cycle, and successful execution may * not always show up). * * @default true * @stability stable */ readonly printLog?: boolean; /** * Don't fail the instance creation when cfn-init fails. * * You can use this to prevent CloudFormation from rolling back when * instances fail to start up, to help in debugging. * * @default false * @stability stable */ readonly ignoreFailures?: boolean; }
the_stack
import { App, Fragment, cloneVNode } from 'vue' import { $g } from './config' import { $cookie } from './cookie' const availablePrefixs = ['moz', 'ms', 'webkit'] class MiTools { /** * Set title. * @param title */ setTitle(title?: string): void { const powered = $g.powered ?? 'Powered by makeit.vip' title = $g.title ?? '中后台管理系统' if (title !== $g.title) $g.title = title document.title = `${title} - ${powered}` } /** * Set keywords. * @param keywords * @param overwritten */ setKeywords(keywords?: string | string[], overwritten?: boolean): void { overwritten = overwritten !== undefined ? overwritten : false const k = $g.keywords const key = keywords ? (Array.isArray(keywords) ? keywords.join(', ') : keywords) : null keywords = key ? (overwritten ? key : `${k} ${key}`) : k const element = document.querySelector(`meta[name="keywords"]`) if (element) element.setAttribute('content', keywords as string) else this.createMeta('keywords', keywords) } /** * Set description. * @param desc */ setDescription(desc?: string, overwritten?: boolean): void { const d = $g.description desc = desc ? (overwritten ? desc : `${desc} ${d}`) : d const description = document.querySelector(`meta[name="description"]`) if (description) description.setAttribute('content', desc as string) else this.createMeta('description', desc) } /** * Create meta element. * @param name * @param content */ createMeta(name: string, content: string): void { const head = document.getElementsByTagName('head'), meta = document.createElement('meta') meta.name = name.trim() meta.content = content.trim() if (head) head[0].appendChild(meta) } random(): string { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) } /** * Generate a random number within the specified range. * @param start * @param end * @returns {number} */ randomNumberInRange(start: number, end: number): number { return Math.round(Math.random() * (end - start) + start) } /** * Generate unique string. * @param upper * @returns {string} */ uid(upper = false, prefix?: string): string { let str = ( this.random() + this.random() + this.random() + this.random() + this.random() + this.random() + this.random() + this.random() ).toLocaleUpperCase() if (prefix) str = prefix + str return upper ? str.toUpperCase() : str.toLowerCase() } /** * Whether it is a mobile phone. * @returns {boolean} */ isMobile(): boolean { const agent = navigator.userAgent, agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'] let mobile = false for (let i = 0, len = agents.length; i < len; i++) { if (agent.indexOf(agents[i]) > 0) { mobile = true break } } return mobile } /** * Whether it is a number. * @param number */ isNumber(number: any): boolean { return typeof number === 'number' && isFinite(number) } /** * Check the validity of the email. * @param email * @returns {boolean} */ checkEmail(email: string): boolean { const regExp = $g.regExp return regExp.email.test(email) } /** * Check Password by rules. * @param password */ checkPassword(password: string): boolean { const regExp = $g.regExp return regExp.password.test(password) } /** * Get the password strength. * return a number level ( 1 - 4 ). * @param password */ getPasswordStrength(password: string): number { const reg = { lower: /[a-z]/, upper: /[A-Z]/, number: /[\d]/, character: /[~!@#$%^&*()_+=\-.,]/ } let strength = 0 if (reg.lower.test(password)) strength++ if (reg.upper.test(password)) strength++ if (reg.number.test(password)) strength++ if (reg.character.test(password)) strength++ return strength } /** * Whether the `element / params` is valid. * @param value */ isValid(value: any): boolean { return value !== undefined && value !== null && value !== '' } /** * The prefix of the default class name. * @param suffixCls * @param customizePrefixCls */ getPrefixCls(suffixCls: string, customizePrefixCls?: string) { if (customizePrefixCls) return customizePrefixCls return `mi-${suffixCls}` } /** * Trim string spaces. * @param str */ trim(str: string): string { return (str || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '') } /** * Whether the element has a specified class name. * @param el * @param cls */ hasClass(el: HTMLElement, cls: string): boolean { if (!el || !cls) return false if (cls.indexOf(' ') !== -1) throw new Error('class name should not contain space.') if (el.classList) { return el.classList.contains(cls) } else { return ` ${el.className} `.indexOf(` ${cls} `) > -1 } } /** * Add class to the element. * @param el * @param cls */ addClass(el: HTMLElement, cls: string) { if (!el) return let curCls = el.className const classes = (cls || '').split(' ') for (let i = 0, l = classes.length; i < l; i++) { const clsName = classes[i] if (!clsName) continue if (el.classList) { el.classList.add(clsName) } else { if (!this.hasClass(el, clsName)) { curCls += ` ${clsName}` } } } if (!el.classList) el.className = curCls } /** * Delete the specified class name in the element. * @param el * @param cls */ removeClass(el: HTMLElement, cls: string) { if (!el || !cls) return const classes = cls.split(' ') let curCls = ` ${el.className} ` for (let i = 0, l = classes.length; i < l; i++) { const clsName = classes[i] if (!clsName) continue if (el.classList) { el.classList.remove(clsName) } else { if (this.hasClass(el, clsName)) { curCls = curCls.replace(` ${clsName} `, '') } } } if (!el.classList) el.className = this.trim(curCls) } /** * errors. * @param name */ importError(name: string) { throw new Error( `[${name}] must be required. Please import and install [${name}] before makeit-admin-pro\r\n` ) } /** * Event binding. * @param element * @param event * @param listener * @param useCapture */ on( element: Window | HTMLElement, event: keyof HTMLElementEventMap, listener: ( this: HTMLDivElement, evt: HTMLElementEventMap[keyof HTMLElementEventMap] ) => any, useCapture = false ) { if (!!document.addEventListener) { if (element && event && listener) element.addEventListener(event, listener, useCapture) } else { if (element && event && listener) (element as any).attachEvent(`on${event}`, listener) } } /** * Event unbind. * @param element * @param event * @param listener * @param useCapture */ off( element: Window | HTMLElement, event: keyof HTMLElementEventMap, listener: ( this: HTMLDivElement, evt: HTMLElementEventMap[keyof HTMLElementEventMap] ) => any, useCapture = false ) { if (!!document.addEventListener) { if (element && event && listener) element.removeEventListener(event, listener, useCapture) } else { if (element && event && listener) (element as any).detachEvent(`on${event}`, listener) } } /** * Format string content. * @param str * @param formatter */ formatEmpty(str?: string, formatter?: string): string { if (this.isEmpty(str)) return formatter ?? '-' return str } /** * Whether the string content is empty. * @param str * @param format */ isEmpty(str: any, format = false): boolean | string { let result: any = str === null || str == '' || typeof str === 'undefined' if (format) result = this.formatEmpty(str) return result } /** * parsing url parameters. * @param url * @param params */ parseUrl(url: string, params = {}) { if (Object.keys(params).length > 0) { for (const i in params) { if (params.hasOwnProperty(i)) { const reg = new RegExp('{' + i + '}', 'gi') url = url.replace(reg, params[i]) } } } return url } /** * Scroll to top. * @param el * @param from * @param to * @param duration * @param endCallback */ scrollTop(el: any, from = 0, to: number, duration = 500, endCallback?: any) { if (!window.requestAnimationFrame) { const w = window as any w.requestAnimationFrame = w.webkitRequestAnimationFrame || w.mozRequestAnimationFrame || w.msRequestAnimationFrame || function (callback: any) { return w.setTimeout(callback, 1000 / 60) } } const difference = Math.abs(from - to) const step = Math.ceil((difference / duration) * 50) function scroll(start: number, end: number, step: number) { if (start === end) { endCallback && endCallback() return } let d = start + step > end ? end : start + step if (start > end) d = start - step < end ? end : start - step if (el === window) window.scrollTo(d, d) else el.scrollTop = d window.requestAnimationFrame(() => scroll(d, end, step)) } scroll(from, to, step) } /** * Back to top ( default `document.body` ). * @param offset * @param time */ backtoTop(offset = 0, time = 1000) { const top = this.isEmpty(offset) ? document.documentElement.scrollTop || document.body.scrollTop : offset this.scrollTop(document.body, top, 0, this.isEmpty(time) ? 1000 : time) } /** * Find Node. * @param instance */ findDOMNode(instance: any) { let node = instance && (instance.$el || instance) while (node && !node.tagName) node = node.nextSibling return node } /** * Unit conversion. * @param value * @param base */ pxToRem(value: number, base = 16) { return Math.round((value / base) * 100) / 100 } /** * Gets the actual height of the element from the top of the document. * @param el */ getElementActualTopLeft(el: HTMLElement, pos = 'top') { let actual = pos === 'left' ? el.offsetLeft : el.offsetTop let current = el.offsetParent as HTMLElement while (current !== null) { actual += pos === 'left' ? current.offsetLeft : current.offsetTop current = current.offsetParent as HTMLElement } return actual } /** * Clone Node. * @param vNode * @param nodeProps * @param override * @param mergeRef */ cloneElement(vNode: any, nodeProps = {}, override = true, mergeRef = false) { let elem = vNode if (Array.isArray(vNode)) { elem = this.filterEmpty(vNode)[0] } if (!elem) return null const node = cloneVNode(elem, nodeProps, mergeRef) node.props = override ? { ...node.props, ...nodeProps } : node.props return node } /** * Whether the element is empty. * @param elem */ isEmptyElement(elem: any) { return ( elem.type === Comment || (elem.type === Fragment && elem.children.length === 0) || (elem.type === Text && elem.children.trim() == '') ) } /** * Filter the empty element. * @param children */ filterEmpty(children = []) { const res = [] children.forEach((child) => { if (Array.isArray(child)) { res.push(...child) } else if (child.type === Fragment) { res.push(...child.children) } else { res.push(child) } }) return res.filter((c) => !this.isEmptyElement(c)) } /** * Request Animation Polyfill. */ requestAnimationFramePolyfill() { let lastTime = 0 return function (callback: any) { const currTime = new Date().getTime() const timeToCall = Math.max(0, 16 - (currTime - lastTime)) const id = window.setTimeout(function () { callback(currTime + timeToCall) }, timeToCall) lastTime = currTime + timeToCall return id } } /** * Get Request Animation Frame. */ getRequestAnimationFrame() { if (typeof window === 'undefined') return () => {} if (window.requestAnimationFrame) return window.requestAnimationFrame.bind(window) const prefix = availablePrefixs.filter((key) => `${key}RequestAnimationFrame` in window)[0] return prefix ? window[`${prefix}RequestAnimationFrame`] : this.requestAnimationFramePolyfill() } /** * Request Animation. * @param callback * @param delay */ createRequestAnimationFrame(callback: any, delay: number) { const start = Date.now() const graf = this.getRequestAnimationFrame() const timeout = () => { if (Date.now() - start >= delay) callback.call() else frame.id = graf(timeout) } const frame = { id: graf(timeout) } return frame } /** * Cancel request animation. * @param id */ cancelRequestAnimationFrame(id: any) { if (typeof window === 'undefined') return null if (window.cancelAnimationFrame) return window.cancelAnimationFrame(id) const prefix = availablePrefixs.filter( (key) => `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window )[0] return prefix ? ( window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`] ).call(this, id) : clearTimeout(id) } /** * convert color. * @param color * @param opacity */ colorHexToRgba(color: string, opacity = 1): string { const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/ if (reg.test(color)) { if (color.length === 4) { let newColor = '#' for (let i = 1; i < 4; i++) { newColor += color.slice(i, i + 1).concat(color.slice(i, i + 1)) } color = newColor } const changeColor: number[] = [] for (let i = 1; i < 7; i += 2) { changeColor.push(parseInt('0x' + color.slice(i, i + 2))) } return `rgba(${changeColor.join(',')}, ${opacity})` } else { return color } } /** * convert color. * @param color */ colorRgbToHex(color: string) { const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/ if (/^(rgb|RGB)/.test(color)) { const aColor = color.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',') let strHex = '#' for (let i = 0; i < aColor.length; i++) { let hex = Number(aColor[i]).toString(16) if (hex === '0') hex += hex strHex += hex } if (strHex.length !== 7) strHex = color return strHex } else if (reg.test(color)) { const aNum = color.replace(/#/, '').split('') if (aNum.length === 6) { return color } else if (aNum.length === 3) { let numHex = '#' for (let i = 0; i < aNum.length; i += 1) { numHex += aNum[i] + aNum[i] } return numHex } } else { return color } } /** * Transfer. * @param html */ htmlEncode(html: string) { let temp = document.createElement('div') as HTMLDivElement temp.textContent != null ? (temp.textContent = html) : (temp.innerText = html) const output = temp.innerHTML temp = null return output } /** * The theme of light-fresh. * @param theme */ setThemeVariables(theme = 'dark') { const id = `${$g.prefix}theme-variables` const last = document.getElementById(id) if (last) last.remove() let variables: any if (theme === 'light') { variables = this.parseVariables(`@mi-theme-color: #2F9688; @mi-body-color: #f5f7f9; @mi-header-bg-color: #2F9688; @mi-header-logo-bg-color: #226a62; @mi-header-logo-text-color: #ffffff; @mi-header-logo-border-bottom-color: #ffffff; @mi-header-trigger-hover-color: rgba(0, 0, 0, 0.1); @mi-header-paletter-item-border-color: #e1e1e1; @mi-breadcrumb-last-child-color: #999; @mi-table-color: #e4e4e4; @mi-table-text-color: #333; @mi-table-td-color: #ffffff; @mi-table-td-hover-color: #ffffff; @mi-table-border-color: #f1f1f1; @mi-sider-color: #fff; @mi-sider-shadow-color: rgba(175, 175, 175, 0.35); @mi-sider-border-color: #4c4c4c; @mi-anchor-bg-color: #fff; @mi-anchor-link-color: #7b7b7b; @mi-anchor-icon-color: #7b7b7b; @mi-anchor-stick-bg-color: #fff; @mi-menu-color: #666; @mi-menu-active-color: rgba(47, 150, 136, .2); @mi-menu-sub-color: #ccc; @mi-menu-sub-bg-color: #fff; @mi-menu-active-sub-color: rgba(47, 150, 136, .6); @mi-history-bg-color: #dedede; @mi-history-item-bg-color: #fff; @mi-history-item-text-color: #666; @mi-dropdown-bg-color: #fff; @mi-dropdown-text-color: #666; @mi-dropdown-item-hover-color: rgba(47, 150, 136, .2); @mi-modal-bg-color: #fff; @mi-modal-text-color: #333; @mi-modal-content-color: rgba(51, 51, 51, 0.85); @mi-modal-border-inline-color: #f3f3f3; @mi-modal-shadow-color: rgba(47, 150, 136, 0.15); @mi-modal-btn-primary-color: #ffffff; @mi-passport-color: #ffffff; @mi-passport-line-color: #3f3f3f; @mi-passport-bg-color: #212121; @mi-passport-icon-color: #9F9F9F; @mi-passport-text-color: #333; @mi-passport-strength-color: #999; @mi-passport-mask-bg-color: #ffffff; @mi-passport-remember-color: #ffffff; @mi-passport-submit-color: #ffffff; @mi-passport-submit-gradual-start-color: #000000; @mi-passport-submit-gradual-end-color: #2F9688; @mi-tab-nav-color: #999; @mi-tab-nav-border-bottom-color: rgba(162, 162, 162, 0.15); @mi-selection-color: #ffffff; @mi-selection-bg-color: #dedede; @mi-captcha-success-bg-color: rgba(47, 150, 136, .2); @mi-card-tab-color: #333; @mi-popover-bg-color: #ffffff; @mi-notice-title-color: #000000; @mi-notice-text-color: #666; @mi-notice-time-color: #b6b6b6; @mi-notice-content-color: rgba(0, 0, 0, 0.6); @mi-content-text-color: #333; @mi-footer-color: #666; @mi-radio-text-color: #333; @mi-btn-default-color: #666; @mi-btn-defaul-bg-color: #ffffff; @mi-btn-defaul-border-color: #e3e3e3; @mi-btn-ghost-border-color: #b5b5b5; @mi-btn-ghost-text-color: #666; @mi-subsidiary-color: #808695; @mi-form-label-color: #999; @mi-error-color: #ed4014; @mi-danger-color: #ff4d4f; @mi-success-color: #2F9688; @mi-warning-color: #ff9900; @mi-info-color: #2db7f5; @mi-font-color: #fff; @mi-link-color: #2F9688; @mi-primary-color: #2F9688; @mi-captcha-bg-color: #636363;`) const style = document.createElement('style') as any style.id = id style.setAttribute('type', 'text/css') if (style.styleSheet) { style.styleSheet.cssText = ` :root { ${variables.join(';')} } ` } else { const content = document.createTextNode(` :root { ${variables.join(';')} } `) style.appendChild(content) } document.head.appendChild(style) } if (theme === 'dark' || theme === 'light') { $g.theme = theme $cookie.set($g.caches.cookies.theme, $g.theme) } } private parseVariables(variables: string): string[] { const arr = this.trim(variables).split(';') if (arr.length > 0) { for (let i = 0, l = arr.length; i < l; i++) { const item = this.trim(arr[i]).split(':') if (item && item.length === 2) { const name = this.trim(item[0]).replace('@', '--') arr[i] = this.trim(`${name}:${this.trim(item[1])}`) } } } return arr } } export const $tools: MiTools = new MiTools() const tools = { install(app: App) { app.config.globalProperties.$tools = $tools } } export default tools
the_stack
import { BSQRegex } from "../../ast/bsqregex"; import { SymbolicActionMode } from "../../compiler/mir_assembly"; import { MIRResolvedTypeKey } from "../../compiler/mir_ops"; import { SMTExp, SMTTypeInfo, VerifierOptions } from "./smt_exp"; type SMT2FileInfo = { TYPE_TAG_DECLS: string[], ORDINAL_TYPE_TAG_DECLS: string[], ABSTRACT_TYPE_TAG_DECLS: string[], INDEX_TAG_DECLS: string[], PROPERTY_TAG_DECLS: string[], SUBTYPE_DECLS: string[], TUPLE_HAS_INDEX_DECLS: string[], RECORD_HAS_PROPERTY_DECLS: string[], STRING_TYPE_ALIAS: string, OF_TYPE_DECLS: string[], KEY_BOX_OPS: string[], TUPLE_INFO: { decls: string[], constructors: string[], boxing: string[] }, RECORD_INFO: { decls: string[], constructors: string[], boxing: string[] }, TYPE_INFO: { decls: string[], constructors: string[], boxing: string[] } EPHEMERAL_DECLS: { decls: string[], constructors: string[] }, RESULT_INFO: { decls: string[], constructors: string[] }, MASK_INFO: { decls: string[], constructors: string[] }, V_MIN_MAX: string[], GLOBAL_DECLS: string[], UF_DECLS: string[], FUNCTION_DECLS: string[], GLOBAL_DEFINITIONS: string[], ACTION: string[] }; class SMTFunction { readonly fname: string; readonly args: { vname: string, vtype: SMTTypeInfo }[]; readonly maskname: string | undefined; readonly masksize: number; readonly result: SMTTypeInfo; readonly body: SMTExp; readonly implicitlambdas: string[] | undefined; constructor(fname: string, args: { vname: string, vtype: SMTTypeInfo }[], maskname: string | undefined, masksize: number, result: SMTTypeInfo, body: SMTExp, implicitlambdas: string[] | undefined) { this.fname = fname; this.args = args; this.maskname = maskname; this.masksize = masksize; this.result = result; this.body = body; this.implicitlambdas = implicitlambdas; } static create(fname: string, args: { vname: string, vtype: SMTTypeInfo }[], result: SMTTypeInfo, body: SMTExp): SMTFunction { return new SMTFunction(fname, args, undefined, 0, result, body, undefined); } static createWithImplicitLambdas(fname: string, args: { vname: string, vtype: SMTTypeInfo }[], result: SMTTypeInfo, body: SMTExp, implicitlambdas: string[]): SMTFunction { return new SMTFunction(fname, args, undefined, 0, result, body, implicitlambdas); } static createWithMask(fname: string, args: { vname: string, vtype: SMTTypeInfo }[], maskname: string, masksize: number, result: SMTTypeInfo, body: SMTExp): SMTFunction { return new SMTFunction(fname, args, maskname, masksize, result, body, undefined); } emitSMT2(): string { const args = this.args.map((arg) => `(${arg.vname} ${arg.vtype.smttypename})`); const body = this.body.emitSMT2(" "); if(this.maskname === undefined) { return `(define-fun ${this.fname} (${args.join(" ")}) ${this.result.smttypename}\n${body}\n)`; } else { return `(define-fun ${this.fname} (${args.join(" ")} (${this.maskname} $Mask_${this.masksize})) ${this.result.smttypename}\n${body}\n)`; } } emitSMT2_DeclOnly(): string { const args = this.args.map((arg) => `(${arg.vname} ${arg.vtype.smttypename})`); if(this.maskname === undefined) { return `(${this.fname} (${args.join(" ")}) ${this.result.smttypename})`; } else { return `(${this.fname} (${args.join(" ")} (${this.maskname} $Mask_${this.masksize})) ${this.result.smttypename})`; } } emitSMT2_SingleDeclOnly(): string { const args = this.args.map((arg) => `(${arg.vname} ${arg.vtype.smttypename})`); if(this.maskname === undefined) { return `${this.fname} (${args.join(" ")}) ${this.result.smttypename}`; } else { return `${this.fname} (${args.join(" ")} (${this.maskname} $Mask_${this.masksize})) ${this.result.smttypename}`; } } } class SMTFunctionUninterpreted { readonly fname: string; readonly args: SMTTypeInfo[]; readonly result: SMTTypeInfo; constructor(fname: string, args: SMTTypeInfo[], result: SMTTypeInfo) { this.fname = fname; this.args = args; this.result = result; } emitSMT2(): string { return `(declare-fun ${this.fname} (${this.args.map((arg) => arg.smttypename).join(" ")}) ${this.result.smttypename})`; } static areDuplicates(f1: SMTFunctionUninterpreted, f2: SMTFunctionUninterpreted): boolean { if (f1.fname !== f2.fname || f1.args.length !== f2.args.length) { return false; } if (f1.result.smttypename !== f2.result.smttypename) { return false; } for (let i = 0; i < f1.args.length; ++i) { if (f1.args[i].smttypename !== f2.args[i].smttypename) { return false; } } return true; } } class SMTEntityDecl { readonly iskeytype: boolean; readonly smtname: string; readonly typetag: string; readonly boxf: string; readonly ubf: string; constructor(iskeytype: boolean, smtname: string, typetag: string, boxf: string, ubf: string) { this.iskeytype = iskeytype; this.smtname = smtname; this.typetag = typetag; this.boxf = boxf; this.ubf = ubf; } } class SMTEntityOfTypeDecl extends SMTEntityDecl { readonly ofsmttype: string; constructor(iskeytype: boolean, smtname: string, typetag: string, boxf: string, ubf: string, ofsmttype: string) { super(iskeytype, smtname, typetag, boxf, ubf); this.ofsmttype = ofsmttype; } } class SMTEntityInternalOfTypeDecl extends SMTEntityDecl { readonly ofsmttype: string; constructor(smtname: string, typetag: string, boxf: string, ubf: string, ofsmttype: string) { super(false, smtname, typetag, boxf, ubf); this.ofsmttype = ofsmttype; } } class SMTEntityCollectionEntryTypeDecl extends SMTEntityDecl { readonly consf: { cname: string, cargs: { fname: string, ftype: string }[] }; readonly emptyf: string; constructor(smtname: string, typetag: string, consf: { cname: string, cargs: { fname: string, ftype: string }[] }, emptyf: string) { super(false, smtname, typetag, "INVALID_SPECIAL", "INVALID_SPECIAL"); this.consf = consf; this.emptyf = emptyf; } } class SMTEntityCollectionTypeDecl extends SMTEntityDecl { readonly consf: { cname: string, cargs: { fname: string, ftype: string }[] }; readonly emptyconst: {fkind: string, fname: string, fexp: string}; readonly entrydecl: SMTEntityCollectionEntryTypeDecl | undefined; constructor(smtname: string, typetag: string, consf: { cname: string, cargs: { fname: string, ftype: string }[] }, boxf: string, ubf: string, emptyconst: {fkind: string, fname: string, fexp: string}, entrydecl: SMTEntityCollectionEntryTypeDecl | undefined) { super(false, smtname, typetag, boxf, ubf); this.consf = consf; this.emptyconst = emptyconst; this.entrydecl = entrydecl; } } class SMTEntityStdDecl extends SMTEntityDecl { readonly consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }; constructor(smtname: string, typetag: string, consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }, boxf: string, ubf: string) { super(false, smtname, typetag, boxf, ubf); this.consf = consf; } } class SMTTupleDecl { readonly smtname: string; readonly typetag: string; readonly consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }; readonly boxf: string; readonly ubf: string; constructor(smtname: string, typetag: string, consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }, boxf: string, ubf: string) { this.smtname = smtname; this.typetag = typetag; this.consf = consf; this.boxf = boxf; this.ubf = ubf; } } class SMTRecordDecl { readonly smtname: string; readonly typetag: string; readonly consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }; readonly boxf: string; readonly ubf: string; constructor(smtname: string, typetag: string, consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }, boxf: string, ubf: string) { this.smtname = smtname; this.typetag = typetag; this.consf = consf; this.boxf = boxf; this.ubf = ubf; } } class SMTEphemeralListDecl { readonly smtname: string; readonly consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }; constructor(smtname: string, consf: { cname: string, cargs: { fname: string, ftype: SMTTypeInfo }[] }) { this.smtname = smtname; this.consf = consf; } } class SMTConstantDecl { readonly gkey: string; readonly optenumname: [MIRResolvedTypeKey, string] | undefined; readonly ctype: SMTTypeInfo; readonly consfinv: string; readonly consfexp: SMTExp; readonly checkf: SMTExp | undefined; constructor(gkey: string, optenumname: [MIRResolvedTypeKey, string] | undefined, ctype: SMTTypeInfo, consfinv: string, consfexp: SMTExp, checkf: SMTExp | undefined) { this.gkey = gkey; this.optenumname = optenumname; this.ctype = ctype; this.consfinv = consfinv; this.consfexp = consfexp; this.checkf = checkf; } } class SMTModelState { readonly arginits: { vname: string, vtype: SMTTypeInfo, vchk: SMTExp | undefined, vinit: SMTExp, callexp: SMTExp }[]; readonly resinit: { vname: string, vtype: SMTTypeInfo, vchk: SMTExp | undefined, vinit: SMTExp, callexp: SMTExp } | undefined; readonly argchk: SMTExp[] | undefined; readonly checktype: SMTTypeInfo; readonly fcheck: SMTExp; readonly targeterrorcheck: SMTExp; readonly isvaluecheck: SMTExp; readonly isvaluefalsechk: SMTExp; constructor(arginits: { vname: string, vtype: SMTTypeInfo, vchk: SMTExp | undefined, vinit: SMTExp, callexp: SMTExp }[], resinit: { vname: string, vtype: SMTTypeInfo, vchk: SMTExp | undefined, vinit: SMTExp, callexp: SMTExp } | undefined, argchk: SMTExp[] | undefined, checktype: SMTTypeInfo, echeck: SMTExp, targeterrorcheck: SMTExp, isvaluecheck: SMTExp, isvaluefalsechk: SMTExp) { this.arginits = arginits; this.resinit = resinit; this.argchk = argchk; this.checktype = checktype; this.fcheck = echeck; this.targeterrorcheck = targeterrorcheck; this.isvaluecheck = isvaluecheck; this.isvaluefalsechk = isvaluefalsechk; } } type SMTCallGNode = { invoke: string, callees: Set<string>, callers: Set<string> }; type SMTCallGInfo = { invokes: Map<string, SMTCallGNode>, topologicalOrder: SMTCallGNode[], roots: SMTCallGNode[], recursive: (Set<string>)[] }; class SMTAssembly { readonly vopts: VerifierOptions; allErrors: { file: string, line: number, pos: number, msg: string }[] = []; entityDecls: SMTEntityDecl[] = []; tupleDecls: SMTTupleDecl[] = []; recordDecls: SMTRecordDecl[] = []; ephemeralDecls: SMTEphemeralListDecl[] = []; typeTags: string[] = [ "TypeTag_None", "TypeTag_Nothing", "TypeTag_Bool", "TypeTag_Int", "TypeTag_Nat", "TypeTag_BigInt", "TypeTag_BigNat", "TypeTag_Float", "TypeTag_Decimal", "TypeTag_Rational", "TypeTag_String", "TypeTag_ByteBuffer", "TypeTag_DateTime", "TypeTag_TickTime", "TypeTag_LogicalTime", "TypeTag_UUID", "TypeTag_ContentHash", "TypeTag_Regex" ]; keytypeTags: string[] = [ "TypeTag_None", "TypeTag_Bool", "TypeTag_Int", "TypeTag_Nat", "TypeTag_BigInt", "TypeTag_BigNat", "TypeTag_String", "TypeTag_DateTime", "TypeTag_LogicalTime", "TypeTag_UUID", "TypeTag_ContentHash" ]; abstractTypes: string[] = []; indexTags: string[] = []; propertyTags: string[] = []; subtypeRelation: { ttype: string, atype: string, value: boolean }[] = []; hasIndexRelation: { idxtag: string, atype: string, value: boolean }[] = []; hasPropertyRelation: { pnametag: string, atype: string, value: boolean }[] = []; literalRegexs: BSQRegex[] = []; validatorRegexs: Map<string, BSQRegex> = new Map<string, BSQRegex>(); constantDecls: SMTConstantDecl[] = []; uninterpfunctions: SMTFunctionUninterpreted[] = []; maskSizes: Set<number> = new Set<number>(); resultTypes: { hasFlag: boolean, rtname: string, ctype: SMTTypeInfo }[] = []; functions: SMTFunction[] = []; entrypoint: string; havocfuncs: Set<string> = new Set<string>(); model: SMTModelState | undefined = undefined; constructor(vopts: VerifierOptions, entrypoint: string) { this.vopts = vopts; this.entrypoint = entrypoint; } private static sccVisit(cn: SMTCallGNode, scc: Set<string>, marked: Set<string>, invokes: Map<string, SMTCallGNode>) { if (marked.has(cn.invoke)) { return; } scc.add(cn.invoke); marked.add(cn.invoke); cn.callers.forEach((pred) => SMTAssembly.sccVisit(invokes.get(pred) as SMTCallGNode, scc, marked, invokes)); } private static topoVisit(cn: SMTCallGNode, pending: SMTCallGNode[], tordered: SMTCallGNode[], invokes: Map<string, SMTCallGNode>) { if (pending.findIndex((vn) => vn.invoke === cn.invoke) !== -1 || tordered.findIndex((vn) => vn.invoke === cn.invoke) !== -1) { return; } pending.push(cn); cn.callees.forEach((succ) => (invokes.get(succ) as SMTCallGNode).callers.add(cn.invoke)); cn.callees.forEach((succ) => SMTAssembly.topoVisit(invokes.get(succ) as SMTCallGNode, pending, tordered, invokes)); tordered.push(cn); } private static processBodyInfo(bkey: string, binfo: SMTExp, invokes: Set<string>): SMTCallGNode { let cn = { invoke: bkey, callees: new Set<string>(), callers: new Set<string>() }; let ac = new Set<string>(); binfo.computeCallees(ac); ac.forEach((cc) => { if(invokes.has(cc)) { cn.callees.add(cc); } }); return cn; } private static constructCallGraphInfo(entryPoints: string[], assembly: SMTAssembly): SMTCallGInfo { let invokes = new Map<string, SMTCallGNode>(); const okinv = new Set<string>(assembly.functions.map((f) => f.fname)); assembly.functions.forEach((smtfun) => { const cn = SMTAssembly.processBodyInfo(smtfun.fname, smtfun.body, okinv); if(smtfun.implicitlambdas !== undefined) { smtfun.implicitlambdas.forEach((cc) => { if(okinv.has(cc)) { cn.callees.add(cc); } }); } invokes.set(smtfun.fname, cn); }); let roots: SMTCallGNode[] = []; let tordered: SMTCallGNode[] = []; entryPoints.forEach((ivk) => { roots.push(invokes.get(ivk) as SMTCallGNode); SMTAssembly.topoVisit(invokes.get(ivk) as SMTCallGNode, [], tordered, invokes); }); assembly.constantDecls.forEach((cdecl) => { roots.push(invokes.get(cdecl.consfinv) as SMTCallGNode); SMTAssembly.topoVisit(invokes.get(cdecl.consfinv) as SMTCallGNode, [], tordered, invokes); }); tordered = tordered.reverse(); let marked = new Set<string>(); let recursive: (Set<string>)[] = []; for (let i = 0; i < tordered.length; ++i) { let scc = new Set<string>(); SMTAssembly.sccVisit(tordered[i], scc, marked, invokes); if (scc.size > 1 || tordered[i].callees.has(tordered[i].invoke)) { recursive.push(scc); } } return { invokes: invokes, topologicalOrder: tordered, roots: roots, recursive: recursive }; } generateSMT2AssemblyInfo(): SMT2FileInfo { const subtypeasserts = this.subtypeRelation.map((tc) => tc.value ? `(assert (SubtypeOf@ ${tc.ttype} ${tc.atype}))` : `(assert (not (SubtypeOf@ ${tc.ttype} ${tc.atype})))`).sort(); const indexasserts = this.hasIndexRelation.map((hi) => hi.value ? `(assert (HasIndex@ ${hi.idxtag} ${hi.atype}))` : `(assert (not (HasIndex@ ${hi.idxtag} ${hi.atype})))`).sort(); const propertyasserts = this.hasPropertyRelation.map((hp) => hp.value ? `(assert (HasProperty@ ${hp.pnametag} ${hp.atype}))` : `(assert (not (HasProperty@ ${hp.pnametag} ${hp.atype})))`).sort(); const keytypeorder: string[] = [...this.keytypeTags].sort().map((ktt, i) => `(assert (= (TypeTag_OrdinalOf ${ktt}) ${i}))`); const v_min_max: string[] = [ `(declare-const @BINTMIN Int) (assert (= @BINTMIN ${this.vopts.INT_MIN}))`, `(declare-const @BINTMAX Int) (assert (= @BINTMAX ${this.vopts.INT_MAX}))`, `(declare-const @SLENMAX Int) (assert (= @SLENMAX ${this.vopts.SLEN_MAX}))`, `(declare-const @BLENMAX Int) (assert (= @BLENMAX ${this.vopts.BLEN_MAX}))`, `(declare-const @CONTAINERMAX Int) (assert (= @CONTAINERMAX ${this.vopts.CONTAINER_MAX}))` ]; const termtupleinfo = this.tupleDecls .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((kt) => { return { decl: `(${kt.smtname} 0)`, consf: `( (${kt.consf.cname} ${kt.consf.cargs.map((ke) => `(${ke.fname} ${ke.ftype.smttypename})`).join(" ")}) )`, boxf: `(${kt.boxf} (${kt.ubf} ${kt.smtname}))` }; }); const termrecordinfo = this.recordDecls .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((kt) => { return { decl: `(${kt.smtname} 0)`, consf: `( (${kt.consf.cname} ${kt.consf.cargs.map((ke) => `(${ke.fname} ${ke.ftype.smttypename})`).join(" ")}) )`, boxf: `(${kt.boxf} (${kt.ubf} ${kt.smtname}))` }; }); const keytypeinfo = this.entityDecls .filter((et) => (et instanceof SMTEntityOfTypeDecl) && et.iskeytype) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((kt) => { return { decl: `(define-sort ${kt.smtname} () ${(kt as SMTEntityOfTypeDecl).ofsmttype})`, boxf: `(${kt.boxf} (${kt.ubf} ${kt.smtname}))` }; }); const oftypeinfo = this.entityDecls .filter((et) => (et instanceof SMTEntityOfTypeDecl) && !et.iskeytype) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((kt) => { return { decl: `(define-sort ${kt.smtname} () ${(kt as SMTEntityOfTypeDecl).ofsmttype})`, boxf: `(${kt.boxf} (${kt.ubf} ${kt.smtname}))` }; }); const termtypeinfo = this.entityDecls .filter((et) => et instanceof SMTEntityStdDecl) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((tt) => { return { decl: `(${tt.smtname} 0)`, consf: `( (${(tt as SMTEntityStdDecl).consf.cname} ${(tt as SMTEntityStdDecl).consf.cargs.map((te) => `(${te.fname} ${te.ftype.smttypename})`).join(" ")}) )`, boxf: `(${tt.boxf} (${tt.ubf} ${tt.smtname}))` }; }); const ofinternaltypeinfo = this.entityDecls .filter((et) => et instanceof SMTEntityInternalOfTypeDecl) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((tt) => { return { boxf: `(${tt.boxf} (${tt.ubf} ${(tt as SMTEntityInternalOfTypeDecl).ofsmttype}))` }; }); const collectiontypeinfo = this.entityDecls .filter((et) => (et instanceof SMTEntityCollectionTypeDecl)) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((tt) => { const ctype = tt as SMTEntityCollectionTypeDecl; return { decl: `(${tt.smtname} 0)`, consf: `( (${ctype.consf.cname} ${ctype.consf.cargs.map((te) => `(${te.fname} ${te.ftype})`).join(" ")}) )`, boxf: `(${tt.boxf} (${tt.ubf} ${tt.smtname}))` }; }); const collectiontypeinfoconsts = this.entityDecls .filter((et) => (et instanceof SMTEntityCollectionTypeDecl)) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((tt) => { const ctype = tt as SMTEntityCollectionTypeDecl; return `(declare-const ${ctype.emptyconst.fname} ${ctype.emptyconst.fkind}) (assert (= ${ctype.emptyconst.fname} ${ctype.emptyconst.fexp}))`; }); const collectionentrytypeinfo = this.entityDecls .filter((et) => (et instanceof SMTEntityCollectionTypeDecl) && (et as SMTEntityCollectionTypeDecl).entrydecl !== undefined) .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((tt) => { const einfo = (tt as SMTEntityCollectionTypeDecl).entrydecl as SMTEntityCollectionEntryTypeDecl; return { decl: `(${einfo.smtname} 0)`, consf: `( (${einfo.consf.cname} ${einfo.consf.cargs.map((te) => `(${te.fname} ${te.ftype})`).join(" ")}) (${einfo.emptyf}) )` }; }); const etypeinfo = this.ephemeralDecls .sort((t1, t2) => t1.smtname.localeCompare(t2.smtname)) .map((et) => { return { decl: `(${et.smtname} 0)`, consf: `( (${et.consf.cname} ${et.consf.cargs.map((ke) => `(${ke.fname} ${ke.ftype.smttypename})`).join(" ")}) )` }; }); const rtypeinfo = this.resultTypes .sort((t1, t2) => (t1.hasFlag !== t2.hasFlag) ? (t1.hasFlag ? 1 : -1) : t1.rtname.localeCompare(t2.rtname)) .map((rt) => { if (rt.hasFlag) { return { decl: `($GuardResult_${rt.ctype.smttypename} 0)`, consf: `( ($GuardResult_${rt.ctype.smttypename}@cons ($GuardResult_${rt.ctype.smttypename}@result ${rt.ctype.smttypename}) ($GuardResult_${rt.ctype.smttypename}@flag Bool)) )` }; } else { return { decl: `($Result_${rt.ctype.smttypename} 0)`, consf: `( ($Result_${rt.ctype.smttypename}@success ($Result_${rt.ctype.smttypename}@success_value ${rt.ctype.smttypename})) ($Result_${rt.ctype.smttypename}@error ($Result_${rt.ctype.smttypename}@error_value ErrorID)) )` }; } }); const maskinfo = [...this.maskSizes] .sort() .map((msize) => { let entries: string[] = []; for(let i = 0; i < msize; ++i) { entries.push(`($Mask_${msize}@${i} Bool)`); } return { decl: `($Mask_${msize} 0)`, consf: `( ($Mask_${msize}@cons ${entries.join(" ")}) )` }; }); const gdecls = this.constantDecls .sort((c1, c2) => c1.gkey.localeCompare(c2.gkey)) .map((c) => `(declare-const ${c.gkey} ${c.ctype.smttypename})`); const ufdecls = this.uninterpfunctions .sort((uf1, uf2) => uf1.fname.localeCompare(uf2.fname)) .map((uf) => uf.emitSMT2()); const gdefs = this.constantDecls .sort((c1, c2) => c1.gkey.localeCompare(c2.gkey)) .map((c) => { if (c.checkf === undefined) { return `(assert (= ${c.gkey} ${c.consfexp.emitSMT2(undefined)}))`; } else { return `(assert ${c.checkf.emitSMT2(undefined)}) (assert (= ${c.gkey} ${c.consfexp.emitSMT2(undefined)}))`; } }); const mmodel = this.model as SMTModelState; let action: string[] = []; mmodel.arginits.map((iarg) => { action.push(`(declare-const ${iarg.vname} ${iarg.vtype.smttypename})`); action.push(`(assert (= ${iarg.vname} ${iarg.vinit.emitSMT2(undefined)}))`); if(iarg.vchk !== undefined) { action.push(`(assert ${iarg.vchk.emitSMT2(undefined)})`); } }); if(mmodel.argchk !== undefined) { action.push(...mmodel.argchk.map((chk) => `(assert ${chk.emitSMT2(undefined)})`)); } action.push(`(declare-const _@smtres@ ${mmodel.checktype.smttypename})`); action.push(`(assert (= _@smtres@ ${mmodel.fcheck.emitSMT2(undefined)}))`); if (this.vopts.ActionMode === SymbolicActionMode.ErrTestSymbolic) { action.push(`(assert ${mmodel.targeterrorcheck.emitSMT2(undefined)})`); } else if(this.vopts.ActionMode === SymbolicActionMode.ChkTestSymbolic) { action.push(`(assert ${mmodel.isvaluecheck.emitSMT2(undefined)})`); action.push(`(assert ${mmodel.isvaluefalsechk.emitSMT2(undefined)})`) } else { action.push(`(assert ${mmodel.isvaluecheck.emitSMT2(undefined)})`); const resi = mmodel.resinit as { vname: string, vtype: SMTTypeInfo, vchk: SMTExp | undefined, vinit: SMTExp, callexp: SMTExp }; action.push(`(declare-const ${resi.vname} ${resi.vtype.smttypename})`); action.push(`(assert (= ${resi.vname} ${resi.vinit.emitSMT2(undefined)}))`); if(resi.vchk !== undefined) { action.push(`(assert ${resi.vchk.emitSMT2(undefined)})`); } action.push(`(assert (= ${resi.vname} _@smtres@))`); } let foutput: string[] = []; let doneset: Set<string> = new Set<string>(); const cginfo = SMTAssembly.constructCallGraphInfo([this.entrypoint, ...this.havocfuncs], this); const rcg = [...cginfo.topologicalOrder]; for (let i = 0; i < rcg.length; ++i) { const cn = rcg[i]; if(doneset.has(cn.invoke)) { continue; } const rf = this.functions.find((f) => f.fname === cn.invoke) as SMTFunction; const cscc = cginfo.recursive.find((scc) => scc.has(cn.invoke)); if(cscc === undefined) { doneset.add(cn.invoke); foutput.push(rf.emitSMT2()); } else { let worklist = [...cscc].sort(); if(worklist.length === 1) { const cf = worklist.shift() as string; const crf = this.functions.find((f) => f.fname === cf) as SMTFunction; const decl = crf.emitSMT2_SingleDeclOnly(); const impl = crf.body.emitSMT2(" "); if (cscc !== undefined) { cscc.forEach((v) => doneset.add(v)); } foutput.push(`(define-fun-rec ${decl}\n ${impl}\n)`); } else { let decls: string[] = []; let impls: string[] = []; while (worklist.length !== 0) { const cf = worklist.shift() as string; const crf = this.functions.find((f) => f.fname === cf) as SMTFunction; decls.push(crf.emitSMT2_DeclOnly()); impls.push(crf.body.emitSMT2(" ")); } if (cscc !== undefined) { cscc.forEach((v) => doneset.add(v)); } foutput.push(`(define-funs-rec (\n ${decls.join("\n ")}\n) (\n${impls.join("\n")}))`); } } } return { TYPE_TAG_DECLS: this.typeTags.sort().map((tt) => `(${tt})`), ORDINAL_TYPE_TAG_DECLS: keytypeorder, ABSTRACT_TYPE_TAG_DECLS: this.abstractTypes.sort().map((tt) => `(${tt})`), INDEX_TAG_DECLS: this.indexTags.sort().map((tt) => `(${tt})`), PROPERTY_TAG_DECLS: this.propertyTags.sort().map((tt) => `(${tt})`), SUBTYPE_DECLS: subtypeasserts, TUPLE_HAS_INDEX_DECLS: indexasserts, RECORD_HAS_PROPERTY_DECLS: propertyasserts, STRING_TYPE_ALIAS: "(define-sort BString () String)", OF_TYPE_DECLS: [...keytypeinfo.map((kd) => kd.decl), ...oftypeinfo.map((td) => td.decl)], KEY_BOX_OPS: [...keytypeinfo.map((kd) => kd.boxf), ...oftypeinfo.map((td) => td.boxf)], TUPLE_INFO: { decls: termtupleinfo.map((kti) => kti.decl), constructors: termtupleinfo.map((kti) => kti.consf), boxing: termtupleinfo.map((kti) => kti.boxf) }, RECORD_INFO: { decls: termrecordinfo.map((kti) => kti.decl), constructors: termrecordinfo.map((kti) => kti.consf), boxing: termrecordinfo.map((kti) => kti.boxf) }, TYPE_INFO: { decls: [ ...termtypeinfo.filter((tti) => tti.decl !== undefined).map((tti) => tti.decl as string), ...collectiontypeinfo.map((clti) => clti.decl), ...collectionentrytypeinfo.map((clti) => clti.decl) ], constructors: [ ...termtypeinfo.filter((tti) => tti.consf !== undefined).map((tti) => tti.consf as string), ...collectiontypeinfo.map((clti) => clti.consf), ...collectionentrytypeinfo.map((clti) => clti.consf) ], boxing: [ ...termtypeinfo.map((tti) => tti.boxf), ...ofinternaltypeinfo.map((ttofi) => ttofi.boxf), ...collectiontypeinfo.map((cti) => cti.boxf) ] }, EPHEMERAL_DECLS: { decls: etypeinfo.map((kti) => kti.decl), constructors: etypeinfo.map((kti) => kti.consf) }, RESULT_INFO: { decls: rtypeinfo.map((kti) => kti.decl), constructors: rtypeinfo.map((kti) => kti.consf) }, MASK_INFO: { decls: maskinfo.map((mi) => mi.decl), constructors: maskinfo.map((mi) => mi.consf) }, V_MIN_MAX: v_min_max, GLOBAL_DECLS: [ ...collectiontypeinfoconsts, ...gdecls ], UF_DECLS: ufdecls, FUNCTION_DECLS: foutput.reverse(), GLOBAL_DEFINITIONS: gdefs, ACTION: action }; } buildSMT2file(smtruntime: string): string { const sfileinfo = this.generateSMT2AssemblyInfo(); function joinWithIndent(data: string[], indent: string): string { if (data.length === 0) { return ";;NO DATA;;" } else { return data.map((d, i) => (i === 0 ? "" : indent) + d).join("\n"); } } const contents = smtruntime .replace(";;TYPE_TAG_DECLS;;", joinWithIndent(sfileinfo.TYPE_TAG_DECLS, " ")) .replace(";;ORDINAL_TAG_DECLS;;", joinWithIndent(sfileinfo.ORDINAL_TYPE_TAG_DECLS, "")) .replace(";;ABSTRACT_TYPE_TAG_DECLS;;", joinWithIndent(sfileinfo.ABSTRACT_TYPE_TAG_DECLS, " ")) .replace(";;INDEX_TAG_DECLS;;", joinWithIndent(sfileinfo.INDEX_TAG_DECLS, " ")) .replace(";;PROPERTY_TAG_DECLS;;", joinWithIndent(sfileinfo.PROPERTY_TAG_DECLS, " ")) .replace(";;SUBTYPE_DECLS;;", joinWithIndent(sfileinfo.SUBTYPE_DECLS, "")) .replace(";;TUPLE_HAS_INDEX_DECLS;;", joinWithIndent(sfileinfo.TUPLE_HAS_INDEX_DECLS, "")) .replace(";;RECORD_HAS_PROPERTY_DECLS;;", joinWithIndent(sfileinfo.RECORD_HAS_PROPERTY_DECLS, "")) .replace(";;BSTRING_TYPE_ALIAS;;", sfileinfo.STRING_TYPE_ALIAS) .replace(";;OF_TYPE_DECLS;;", joinWithIndent(sfileinfo.OF_TYPE_DECLS, "")) .replace(";;KEY_BOX_OPS;;", joinWithIndent(sfileinfo.KEY_BOX_OPS, " ")) .replace(";;TUPLE_DECLS;;", joinWithIndent(sfileinfo.TUPLE_INFO.decls, " ")) .replace(";;RECORD_DECLS;;", joinWithIndent(sfileinfo.RECORD_INFO.decls, " ")) .replace(";;TYPE_DECLS;;", joinWithIndent(sfileinfo.TYPE_INFO.decls, " ")) .replace(";;TUPLE_TYPE_CONSTRUCTORS;;", joinWithIndent(sfileinfo.TUPLE_INFO.constructors, " ")) .replace(";;RECORD_TYPE_CONSTRUCTORS;;", joinWithIndent(sfileinfo.RECORD_INFO.constructors, " ")) .replace(";;TYPE_CONSTRUCTORS;;", joinWithIndent(sfileinfo.TYPE_INFO.constructors, " ")) .replace(";;TUPLE_TYPE_BOXING;;", joinWithIndent(sfileinfo.TUPLE_INFO.boxing, " ")) .replace(";;RECORD_TYPE_BOXING;;", joinWithIndent(sfileinfo.RECORD_INFO.boxing, " ")) .replace(";;TYPE_BOXING;;", joinWithIndent(sfileinfo.TYPE_INFO.boxing, " ")) .replace(";;EPHEMERAL_DECLS;;", joinWithIndent(sfileinfo.EPHEMERAL_DECLS.decls, " ")) .replace(";;EPHEMERAL_CONSTRUCTORS;;", joinWithIndent(sfileinfo.EPHEMERAL_DECLS.constructors, " ")) .replace(";;RESULT_DECLS;;", joinWithIndent(sfileinfo.RESULT_INFO.decls, " ")) .replace(";;MASK_DECLS;;", joinWithIndent(sfileinfo.MASK_INFO.decls, " ")) .replace(";;RESULTS;;", joinWithIndent(sfileinfo.RESULT_INFO.constructors, " ")) .replace(";;MASKS;;", joinWithIndent(sfileinfo.MASK_INFO.constructors, " ")) .replace(";;V_MIN_MAX;;", joinWithIndent(sfileinfo.V_MIN_MAX, "")) .replace(";;GLOBAL_DECLS;;", joinWithIndent(sfileinfo.GLOBAL_DECLS, "")) .replace(";;UF_DECLS;;", joinWithIndent(sfileinfo.UF_DECLS, "\n")) .replace(";;FUNCTION_DECLS;;", joinWithIndent(sfileinfo.FUNCTION_DECLS, "\n")) .replace(";;GLOBAL_DEFINITIONS;;", joinWithIndent(sfileinfo.GLOBAL_DEFINITIONS, "")) .replace(";;ACTION;;", joinWithIndent(sfileinfo.ACTION, "")); return contents; } } export { SMTEntityDecl, SMTEntityOfTypeDecl, SMTEntityInternalOfTypeDecl, SMTEntityCollectionTypeDecl, SMTEntityCollectionEntryTypeDecl, SMTEntityStdDecl, SMTTupleDecl, SMTRecordDecl, SMTEphemeralListDecl, SMTConstantDecl, SMTFunction, SMTFunctionUninterpreted, SMTAssembly, SMTModelState, SMT2FileInfo };
the_stack
import { logger } from '../util' import { NetworkCryptoConfigPeerOrgType, NetworkCreatePeerOrgType, NetworkPeerPortType } from '../model/type/network.type' import CryptoConfigYaml from '../model/yaml/network/cryptoConfigYaml' import PeerDockerComposeYaml from '../model/yaml/docker-compose/peerDockerComposeYaml' import PeerInstance from '../instance/peer' import ConnectionProfileYaml from '../model/yaml/network/connectionProfileYaml' import ConfigtxYaml from '../model/yaml/network/configtx' import FabricTools from '../instance/fabricTools' import Channel from './channel' import { PeerUpType, PeerDownType, PeerAddType, PeerAddOrgToChannelType, PeerAddOrgToSystemChannelType } from '../model/type/peer.type' import { InfraRunnerResultType } from '../instance/infra/InfraRunner.interface' import { OrgPeerCreateType } from '../model/type/org.type' import { AbstractService } from './Service.abstract' import Org from './org' export default class Peer extends AbstractService { /** * @description 啟動 peer 的機器 */ public async up (dto: PeerUpType): Promise<InfraRunnerResultType> { logger.debug(`Peer up: ${dto.peerHostname}`) return await (new PeerInstance(dto.peerHostname, this.config, this.infra)).up() } /** * @description 關閉 peer 的機器並且刪除其 volume 的資料 */ public async down (dto: PeerDownType): Promise<InfraRunnerResultType> { logger.debug(`Peer down: ${dto.peerHostname}`) return await (new PeerInstance(dto.peerHostname, this.config, this.infra).down()) } /** * @description 由 cryptogen 產生 peer org 的憑證和私鑰 * @returns 憑證和私鑰(~/.bdk/[blockchain network 名稱]/peerOrganizations/[peer org 的名稱] 資料夾底下) */ public async cryptogen (dto: OrgPeerCreateType) { const { peerOrgs } = dto logger.debug('Peer create cryptogen') const cryptoConfigYaml = new CryptoConfigYaml() const peerOrgCryptoConfigYaml = this.createCryptoConfigYaml(peerOrgs) if (peerOrgCryptoConfigYaml && peerOrgCryptoConfigYaml.value.PeerOrgs) { cryptoConfigYaml.setPeerOrgs(peerOrgCryptoConfigYaml.value.PeerOrgs) } this.bdkFile.createCryptoConfigYaml(cryptoConfigYaml) await (new FabricTools(this.config, this.infra)).cryptogenGenerateCryptoConfig() } /** * @description 由 peer org 的 configtx.yaml 產生 peer org 設定的 json 檔案 * @returns peer org 設定的 json 檔案(在 ~/.bdk/[blockchain network 名稱]/org-json) */ public async createPeerOrgConfigtxJSON (dto: OrgPeerCreateType) { const { peerOrgs } = dto for (const peerOrg of peerOrgs) { logger.debug(`Peer create configtx: ${peerOrg.name}`) const configtxYaml = new ConfigtxYaml() const newOrg = configtxYaml.addPeerOrg({ name: peerOrg.name, mspDir: `${this.config.infraConfig.dockerPath}/peerOrganizations/${peerOrg.domain}/msp`, domain: peerOrg.domain, anchorPeers: [{ hostname: `${this.config.hostname}.${this.config.orgDomainName}`, port: peerOrg?.ports?.[+(this.config.hostname.slice(4, 0))]?.port }], }) this.bdkFile.createConfigtxPeerOrg(newOrg) await (new Org(this.config, this.infra)).createOrgDefinitionJson(peerOrg.name, configtxYaml) } } /** * @description 複製 TLS CA 到 blockchain network 底下指定的資料夾 * @returns 複製 TLS CA 到 blockchain network 底下的資料夾 tlsca/[peer hostname 的名稱].[domain 的名稱]/ca.crt */ public copyTLSCa (dto: OrgPeerCreateType) { const { peerOrgs } = dto peerOrgs.forEach((peerOrg: NetworkCreatePeerOrgType) => { logger.debug(`Peer create copyTLSCa: ${peerOrg.name}`) for (let i = 0; i < peerOrg.peerCount; i++) { this.bdkFile.copyPeerOrgTLSCa(`peer${i}`, peerOrg.domain) } }) } /** * @description 產生 peer org 的連線設定 yaml 檔案 * @returns peer org 連線設定的 yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/peerOrganizations/[domain 的名稱]/connection-[peer org 的名稱].yaml) */ public createConnectionProfileYaml (dto: OrgPeerCreateType) { const { peerOrgs } = dto peerOrgs.forEach((peerOrg) => { logger.debug(`Peer create connection config: ${peerOrg.name}`) const connectionProfileYaml = new ConnectionProfileYaml() connectionProfileYaml.setName(`${this.config.networkName}-${peerOrg.name}`) connectionProfileYaml.setClientOrganization(peerOrg.name) for (let i = 0; i < peerOrg.peerCount; i++) { connectionProfileYaml.addPeer( peerOrg.name, `peer${i}.${peerOrg.domain}`, this.bdkFile.getPeerOrgTlsCertString(i, peerOrg.domain), peerOrg.ports?.[i]?.port, ) } this.bdkFile.createConnectionFile(peerOrg.name, peerOrg.domain, connectionProfileYaml) }) } /** * @description 在 peer org 新增 peer * @returns peer org 的 docker compose yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/docker-compose/[domain 的名稱]/docker-compose-peer-[peer 的 hostname].[peer org 的名稱].yaml) */ public add (dto: PeerAddType) { // if port[i] is not undefine, use this port and publish a container's port to the host. else use default port. logger.debug('Peer add') this.createPeerOrgDockerComposeYaml(dto.orgName || this.config.orgName, dto.orgDomain || this.config.orgDomainName, dto.peerCount, dto.ports) } /** * @description 產生多個 peer org 的 docker compose * @returns peer org 的 docker compose yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/docker-compose 底下) */ public createDockerCompose (dto: OrgPeerCreateType) { const { peerOrgs } = dto peerOrgs.forEach((peerOrg) => { logger.debug(`Peer create docker-compose: ${peerOrg.name}`) this.createPeerOrgDockerComposeYaml(peerOrg.name, peerOrg.domain, peerOrg.peerCount, peerOrg.ports) }) } /** * @description 產生 peer org 的 docker compose * @param peerName - [string] peer org 的名稱 * @param peerDomain - [string] peer org domain 的名稱 * @param peerCount - [number] peer org 中 peer 的個數 * @param ports - [{@link NetworkPeerPortType} array] peer org 中 port 設定 * @returns peer org 的 docker compose yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/docker-compose/[domain 的名稱]/docker-compose-peer-[peer 的 hostname].[peer org 的名稱].yaml) */ public createPeerOrgDockerComposeYaml (peerName: string, peerDomain: string, peerCount: number, ports?: NetworkPeerPortType[]) { for (let i = 0; i < peerCount; i++) { const bootstrapPeerNumber = (i + 1) % peerCount const peerDockerComposeYaml = new PeerDockerComposeYaml() peerDockerComposeYaml.addNetwork(this.config.networkName, { name: this.config.networkName, external: true }) peerDockerComposeYaml.addPeer(this.config, peerName, peerDomain, i, bootstrapPeerNumber, ports?.[bootstrapPeerNumber]?.port, ports?.[i]?.port, ports?.[i]?.operationPort, ports?.[i]?.isPublishPort, ports?.[i]?.isPublishOperationPort) this.bdkFile.createDockerComposeYaml(`peer${i}.${peerDomain}`, peerDockerComposeYaml) this.bdkFile.createOrgConfigEnv(`peer-peer${i}.${peerDomain}`, peerDockerComposeYaml.getPeerOrgEnv(this.config, peerName, i, peerDomain, ports?.[i]?.port)) } } /** * @description 產生 crypto config 所需的文字 * @returns null | crypto config 所需的文字 */ public createCryptoConfigYaml (cryptoConfigPeerOrg: NetworkCryptoConfigPeerOrgType[]) { const cryptConfigYaml = new CryptoConfigYaml() cryptoConfigPeerOrg.forEach(x => cryptConfigYaml.addPeerOrg({ Name: x.name, Domain: x.domain, EnableNodeOUs: x.enableNodeOUs, Template: { Count: x.peerCount, }, Users: { Count: x.userCount, }, })) return cryptoConfigPeerOrg.length === 0 ? null : cryptConfigYaml } /** * @description 在 channel 中加入 peer org */ public async addOrgToChannel (dto: PeerAddOrgToChannelType): Promise<void> { await this.addOrgToChannelSteps().fetchChannelConfig(dto) await this.addOrgToChannelSteps().computeUpdateConfigTx(dto) } /** * @ignore */ public addOrgToChannelSteps () { return { fetchChannelConfig: async (dto: PeerAddOrgToChannelType): Promise<InfraRunnerResultType> => { logger.debug('add org to channel step1 (fetchChannelConfig)') return await (new Channel(this.config, this.infra)).fetchChannelConfig(dto.channelName) }, computeUpdateConfigTx: async (dto: PeerAddOrgToChannelType) => { logger.debug('add org to channel step2 (orgConfigComputeUpdateAndSignConfigTx)') const { channelName, orgName } = dto const newOrg = JSON.parse(this.bdkFile.getOrgConfigJson(orgName)) const updateFunction = (configBlock: any) => { const modifiedConfigBlock = JSON.parse(JSON.stringify(configBlock)) modifiedConfigBlock.channel_group.groups.Application.groups = { ...modifiedConfigBlock.channel_group.groups.Application.groups, [orgName]: newOrg, } return modifiedConfigBlock } return await (new Channel(this.config, this.infra)).computeUpdateConfigTx(channelName, updateFunction) }, } } /** * @description 在 system-channel 中加入 peer org */ public async addOrgToSystemChannel (dto: PeerAddOrgToSystemChannelType): Promise<void> { await this.addOrgToSystemChannelSteps().fetchChannelConfig(dto) await this.addOrgToSystemChannelSteps().computeUpdateConfigTx(dto) } /** * @ignore */ public addOrgToSystemChannelSteps () { return { fetchChannelConfig: async (dto: PeerAddOrgToSystemChannelType): Promise<InfraRunnerResultType> => { logger.debug('add org to system channel step1 (fetchChannelConfig)') return await (new Channel(this.config, this.infra)).fetchChannelConfig(dto.channelName, dto.orderer) }, computeUpdateConfigTx: async (dto: PeerAddOrgToSystemChannelType) => { logger.debug('add org to system channel step2 (orgConfigComputeUpdateAndSignConfigTx)') const { channelName, orgName } = dto const newOrg = JSON.parse(this.bdkFile.getOrgConfigJson(orgName)) const updateFunction = (configBlock: any) => { const modifiedConfigBlock = JSON.parse(JSON.stringify(configBlock)) modifiedConfigBlock.channel_group.groups.Consortiums.groups.AllOrganizationsConsortium.groups = { ...modifiedConfigBlock.channel_group.groups.Consortiums.groups.AllOrganizationsConsortium.groups, [orgName]: newOrg, } return modifiedConfigBlock } return await (new Channel(this.config, this.infra)).computeUpdateConfigTx(channelName, updateFunction) }, } } }
the_stack
module Helper._CommandingSurface { "use strict"; var _Constants = Helper.require("WinJS/Controls/CommandingSurface/_Constants"); var _CommandingSurface = <typeof WinJS.UI.PrivateCommandingSurface> Helper.require("WinJS/Controls/CommandingSurface/_CommandingSurface")._CommandingSurface; export interface ISizeForCommandsArgs { closedDisplayMode: string; numStandardCommandsShownInActionArea: number; numSeparatorsShownInActionArea: number; widthOfContentCommandsShownInActionArea: number; isACommandVisbleInTheOverflowArea: boolean; /* * Any additonal free space that we would like available in the action area. */ additionalFreeSpace: number; }; export function sizeForCommands(controlElement: HTMLElement, args: ISizeForCommandsArgs) { // Sizes the width of the control to have enough available space in the // action area to be able to fit the values specified in args. // Automatically detects whether or not an overflow button will be needed // and adds additional space inside the controlElement to cover it. var closedDisplayMode = args.closedDisplayMode; var widthForStandardCommands = (args.numStandardCommandsShownInActionArea || 0) * _Constants.actionAreaCommandWidth; var widthForSeparators = (args.numSeparatorsShownInActionArea || 0) * _Constants.actionAreaSeparatorWidth; var widthForContentCommands = (args.widthOfContentCommandsShownInActionArea || 0); var additionalFreeSpace = args.additionalFreeSpace || 0; var isACommandVisbleInTheOverflowArea = args.isACommandVisbleInTheOverflowArea || false; var widthForPrimaryCommands = widthForStandardCommands + widthForSeparators + widthForContentCommands; // Determine if the control will want to display an overflowButton. var needsOverflowButton = (isACommandVisbleInTheOverflowArea || Helper._CommandingSurface.isActionAreaExpandable(closedDisplayMode) && widthForPrimaryCommands > 0); var widthForOverflowButton = needsOverflowButton ? _Constants.actionAreaOverflowButtonWidth : 0; var totalWidth = widthForPrimaryCommands + widthForOverflowButton + additionalFreeSpace; controlElement.style.width = totalWidth + "px"; } export function isActionAreaExpandable(closedDisplayMode: string): boolean { var result; var mode = closedDisplayMode; switch (mode) { case _CommandingSurface.ClosedDisplayMode.none: case _CommandingSurface.ClosedDisplayMode.minimal: case _CommandingSurface.ClosedDisplayMode.compact: // These ClosedDisplayModes have an expandable actionarea when shown. result = true; break; case _CommandingSurface.ClosedDisplayMode.full: // These ClosedDisplayModes do not have an expandable actionarea when shown. result = false; break; default: LiveUnit.Assert.fail("TEST ERROR: Unknown ClosedDisplayMode enum value: " + mode); break; } return result; } export function useSynchronousAnimations(commandingSurface: WinJS.UI.PrivateCommandingSurface) { commandingSurface.createOpenAnimation = function () { return { execute(): WinJS.Promise<any> { return WinJS.Promise.wrap(); } }; }; commandingSurface.createCloseAnimation = function () { return { execute(): WinJS.Promise<any> { return WinJS.Promise.wrap(); } }; }; } export function useSynchronousDataRendering(commandingSurface: WinJS.UI.PrivateCommandingSurface) { // Remove delay for batching edits, and render changes synchronously. commandingSurface._batchDataUpdates = (updateFn) => { updateFn(); } } export function getVisibleCommandsInElement(element: HTMLElement) { var result: HTMLElement[] = []; var commands = element.querySelectorAll(_Constants.commandSelector); for (var i = 0, len = commands.length; i < len; i++) { if (getComputedStyle(<Element>commands[i]).display !== "none") { result.push(<HTMLElement>commands[i]); } } return result; } export function getProjectedCommandFromOriginalCommand(commandingSurface, originalCommand: WinJS.UI.ICommand): WinJS.UI.PrivateMenuCommand { // Given an ICommand in the CommandingSurface, find and return its MenuCommand projection from the overflowarea, if such a projection exists. var projectedCommands = getVisibleCommandsInElement(commandingSurface._dom.overflowArea).map(function (element) { return element.winControl; }); var matches = projectedCommands.filter(function (projection) { return originalCommand === projection["_originalICommand"]; }); if (matches.length > 1) { LiveUnit.Assert.fail("TEST ERROR: CommandingSurface should not project more than 1 MenuCommand into the overflowarea for each ICommand in the actionarea."); } return matches[0]; }; export function verifyOverflowMenuContent(visibleElements: HTMLElement[], expectedLabels: string[]): void { var labelIndex = 0; for (var i = 0, len = visibleElements.length; i < len; i++) { if (visibleElements[i]["winControl"].type === _Constants.typeSeparator) { LiveUnit.Assert.areEqual(expectedLabels[labelIndex], _Constants.typeSeparator); } else { LiveUnit.Assert.areEqual(expectedLabels[labelIndex], visibleElements[i]["winControl"].label); } labelIndex++; } } export function verifyActionAreaVisibleCommandsLabels(commandingSurface: WinJS.UI.PrivateCommandingSurface, labels: string[]) { var commands = getVisibleCommandsInElement((<WinJS.UI.PrivateCommandingSurface>commandingSurface.element.winControl)._dom.actionArea); LiveUnit.Assert.areEqual(labels.length, commands.length); labels.forEach((label, index) => { LiveUnit.Assert.areEqual(label, commands[index].winControl.label); }); } export function verifyOverflowAreaCommandsLabels(commandingSurface: WinJS.UI.PrivateCommandingSurface, labels: string[]) { var control = <WinJS.UI.PrivateCommandingSurface>commandingSurface.element.winControl; var commands = getVisibleCommandsInElement(control._dom.overflowArea); LiveUnit.Assert.areEqual(labels.length, commands.length); labels.forEach((label, index) => { LiveUnit.Assert.areEqual(label, commands[index].winControl.label); }); } // // Verify correct rendered states for opened and closed _CommandingSurface // function verifyActionArea_FullyExpanded(commandingSurface: WinJS.UI.PrivateCommandingSurface){ // We expect the action area to be fully expanded whenever the _CommandingSurface is closed with closedDisplayMode: full, // or whenever the _CommandingSurface is opened, regardless of closedDidsplayMode. var commandElements = Helper._CommandingSurface.getVisibleCommandsInElement(commandingSurface._dom.actionArea); var commandingSurfaceTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface.element); var actionAreaTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface._dom.actionArea); var actionAreaContentBoxHeight = WinJS.Utilities._getPreciseContentHeight(commandingSurface._dom.actionArea); var isOverflowButtonVisible = (commandingSurface._dom.overflowButton.style.display === "none") ? false : true; var overflowButtonTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface._dom.overflowButton); var heightOfTallestChildElement: number = Array.prototype.reduce.call(commandingSurface._dom.actionArea.children, function (tallest, element) { return Math.max(tallest, WinJS.Utilities._getPreciseTotalHeight(element)); }, 0); LiveUnit.Assert.areEqual(actionAreaTotalHeight, commandingSurfaceTotalHeight, "Height of CommandingSurface should size to its actionarea."); LiveUnit.Assert.areEqual(heightOfTallestChildElement, actionAreaContentBoxHeight, "Actionarea height should be fully expanded and size to the heights of its content"); if (isOverflowButtonVisible) { LiveUnit.Assert.areEqual(actionAreaTotalHeight, overflowButtonTotalHeight, "overflowButton should stretch to the height of the actionarea"); } // Verify commands are displayed. if (Array.prototype.some.call(commandElements, function (commandEl) { return getComputedStyle(commandEl).display === "none"; })) { LiveUnit.Assert.fail("Opened actionarea should always display primary commands."); } // Verify command labels are displayed. if (Array.prototype.some.call(commandElements, function (commandEl) { var label = commandEl.querySelector(".win-label"); return (label && getComputedStyle(label).display == "none"); })) { LiveUnit.Assert.fail("Opened actionarea should display primary command labels"); } } export function verifyRenderedOpened(commandingSurface: WinJS.UI.PrivateCommandingSurface) { // Verifies actionarea and overflowarea are opened. // Currently only works if there is at least one command in the actionarea and overflow area. verifyOpened_actionArea(commandingSurface); verifyOpened_overflowArea(commandingSurface); }; function verifyOpened_actionArea(commandingSurface: WinJS.UI.PrivateCommandingSurface) { verifyActionArea_FullyExpanded(commandingSurface); // Verify overflow button aria-expanded var overflowButton_AriaExpanded = commandingSurface._dom.overflowButton.getAttribute("aria-expanded"); LiveUnit.Assert.areEqual("true", overflowButton_AriaExpanded); }; function verifyOpened_overflowArea(commandingSurface: WinJS.UI.PrivateCommandingSurface) { LiveUnit.Assert.areNotEqual("none", getComputedStyle(commandingSurface._dom.overflowArea).display); var overflowAreaTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface._dom.overflowArea); var overflowCommands = getVisibleCommandsInElement(commandingSurface._dom.overflowArea); if (overflowCommands.length) { LiveUnit.Assert.isTrue(0 < overflowAreaTotalHeight); } else { LiveUnit.Assert.isTrue(0 === overflowAreaTotalHeight, "Opened overflowArea should not be visible if there are no overflow commands"); } }; export function verifyRenderedClosed(commandingSurface: WinJS.UI.PrivateCommandingSurface) { // Verifies actionarea and overflowarea are closed. // Currently only works if their is at least one command in the actionarea and overflow area. verifyClosed_actionArea(commandingSurface); verifyClosed_oveflowArea(commandingSurface); }; function verifyClosed_actionArea(commandingSurface: WinJS.UI.PrivateCommandingSurface) { var closedDisplayMode = commandingSurface.closedDisplayMode; var commandElements = Helper._CommandingSurface.getVisibleCommandsInElement(commandingSurface._dom.actionArea), commandingSurfaceTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface.element), actionAreaTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface._dom.actionArea), actionAreaContentBoxHeight = WinJS.Utilities._getPreciseContentHeight(commandingSurface._dom.actionArea), overflowButtonTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface._dom.overflowButton); switch (closedDisplayMode) { case _CommandingSurface.ClosedDisplayMode.none: LiveUnit.Assert.areEqual("none", getComputedStyle(commandingSurface.element).display); LiveUnit.Assert.areEqual(0, actionAreaTotalHeight); LiveUnit.Assert.areEqual(0, overflowButtonTotalHeight); break; case _CommandingSurface.ClosedDisplayMode.minimal: LiveUnit.Assert.areEqual(actionAreaTotalHeight, commandingSurfaceTotalHeight, "Height of CommandingSurface should size to its actionarea."); LiveUnit.Assert.areEqual(_Constants.heightOfMinimal, actionAreaContentBoxHeight, "invalid ActionArea content height for 'minimal' closedDisplayMode"); LiveUnit.Assert.areEqual(actionAreaContentBoxHeight, overflowButtonTotalHeight, "overflowButton should stretch to the height of the actionarea"); // Verify commands are not displayed. if (Array.prototype.some.call(commandElements, function (commandEl) { return getComputedStyle(commandEl).display !== "none"; })) { LiveUnit.Assert.fail("CommandingSurface with 'minimal' closedDisplayMode should not display primary commands."); } break; case _CommandingSurface.ClosedDisplayMode.compact: LiveUnit.Assert.areEqual(actionAreaTotalHeight, commandingSurfaceTotalHeight, "Height of CommandingSurface should size to its actionarea."); LiveUnit.Assert.areEqual(_Constants.heightOfCompact, actionAreaContentBoxHeight, "invalid ActionArea content height for 'compact' closedDisplayMode"); LiveUnit.Assert.areEqual(actionAreaContentBoxHeight, overflowButtonTotalHeight, "overflowButton should stretch to the height of the actionarea"); // Verify commands are displayed. if (Array.prototype.some.call(commandElements, function (commandEl) { return getComputedStyle(commandEl).display === "none"; })) { LiveUnit.Assert.fail("CommandingSurface with 'compact' closedDisplayMode should display primary commands."); } // Verify command labels are not displayed. if (Array.prototype.some.call(commandElements, function (commandEl) { var label = commandEl.querySelector(".win-label"); return (label && getComputedStyle(label).display !== "none"); })) { LiveUnit.Assert.fail("CommandingSurface with 'compact' closedDisplayMode should not display primary command labels."); } break; case _CommandingSurface.ClosedDisplayMode.full: // closedDisplayMode: full should render the action area fully expanded. verifyActionArea_FullyExpanded(commandingSurface); break; default: LiveUnit.Assert.fail("TEST ERROR: Encountered unknown ClosedDisplayMode enum value: " + closedDisplayMode); break; } // Verify overflow button aria-expanded var overflowButton_AriaExpanded = commandingSurface._dom.overflowButton.getAttribute("aria-expanded"); LiveUnit.Assert.areEqual("false", overflowButton_AriaExpanded) } function verifyClosed_oveflowArea(commandingSurface: WinJS.UI.PrivateCommandingSurface) { var overflowAreaTotalHeight = WinJS.Utilities._getPreciseTotalHeight(commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(0, overflowAreaTotalHeight); }; };
the_stack
namespace LiteMol.Plugin.Views.Transform.Molecule { "use strict"; import Transformer = Bootstrap.Entity.Transformer export class CreateFromData extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateFromDataParams>> { protected renderControls() { let params = this.params; return <div> <Controls.OptionsGroup options={LiteMol.Core.Formats.Molecule.SupportedFormats.All} caption={s => s.name} current={params.format} onChange={(o) => this.updateParams({ format: o }) } label='Format' /> </div> } } export class DownloadFromUrl extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.DownloadMoleculeSourceParams>> { protected renderControls() { let params = this.params; return <div> <Controls.OptionsGroup options={LiteMol.Core.Formats.Molecule.SupportedFormats.All} caption={s => s.name} current={params.format} onChange={(o) => this.updateParams({ format: o }) } label='Format' /> <Controls.TextBoxGroup value={params.id!} onChange={(v) => this.updateParams({ id: v })} label='URL' onEnter={e => this.applyEnter(e) } placeholder='Enter url...' /> </div> } } export class OpenFile extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.OpenMoleculeFromFileParams>> { protected renderControls() { let params = this.params; let state = this.controller.latestState; let extensions = LiteMol.Core.Formats.FormatInfo.formatFileFilters(LiteMol.Core.Formats.Molecule.SupportedFormats.All); return <div> <div className='lm-btn lm-btn-block lm-btn-action lm-loader-lm-btn-file' style={{marginTop: '1px'}}> {params.file ? params.file.name : 'Select a file...'} <input disabled={state.isBusy} type='file' accept={extensions} onChange={ evt => this.updateParams({ file: (evt.target as any).files[0] }) } multiple={false} /> </div> </div> } } export class InitCoordinateStreaming extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CoordinateStreaming.InitStreamingParams>> { protected renderControls() { let params = this.params; return <div> <Controls.TextBoxGroup value={params.id!} onChange={(v) => this.updateParams({ id: v })} label='Id' onEnter={e => this.applyEnter(e) } placeholder='Enter pdb id...' /> <Controls.TextBoxGroup value={params.server!} onChange={(v) => this.updateParams({ server: v })} label='Server' onEnter={e => this.applyEnter(e) } placeholder='Server url...' /> </div> } } export class CreateFromMmCif extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateFromMmCifParams>> { protected renderControls() { let cif = this.transformSourceEntity as Bootstrap.Entity.Data.CifDictionary; let options = cif.props.dictionary.dataBlocks.map((b, i) => ({ b: b.header, i }) ); return <div> <Controls.OptionsGroup options={options} caption={s => s.b} current={options[this.params.blockIndex!]} onChange={(o) => this.updateParams({ blockIndex: o.i }) } label='Source' /> </div> } } export class CreateModel extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateModelParams>> { protected renderControls() { let modelCount = (this.transformSourceEntity as Bootstrap.Entity.Molecule.Molecule).props.molecule.models.length; return <div> <Controls.Slider label='Index' onChange={v => this.updateParams({ modelIndex: v - 1 })} min={1} max={modelCount} step={1} value={ (this.params.modelIndex | 0) + 1 } title='Index of the model.' /> </div> } } export class CreateAssembly extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateAssemblyParams>> { protected renderControls() { let params = this.params; //let model = this.isUpdate ? Bootstrap.Utils.Molecule.findModel(this.transformSourceEntity) : this.entity as Bootstrap.Entity.Molecule.Model; let model = Bootstrap.Utils.Molecule.findModel(this.transformSourceEntity)!; let asm = model.props.model.data.assemblyInfo; if (!asm) return void 0; let names = asm.assemblies.map(a => a.name); return <div> <Controls.OptionsGroup options={names} current={params.name} onChange={(o) => this.updateParams({ name: o }) } label='Name' /> </div> } } export class CreateSymmetryMates extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateSymmetryMatesParams>> { protected renderControls() { let params = this.params; let options: (typeof params.type)[] = ['Mates', 'Interaction']; return <div> <Controls.OptionsGroup options={options} current={params.type} onChange={(o) => this.updateParams({ type: o }) } label='Type' title='Mates: copies whole asymetric unit. Interaction: Includes only residues that are no more than `radius` from the asymetric unit.' /> <Controls.Slider label='Radius' onChange={v => this.updateParams({ radius: v })} min={0} max={25} step={0.1} value={params.radius!} title='Interaction radius.' /> </div> } } export class CreateSelection extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateSelectionParams>> { protected renderControls() { let params = this.params; return <div> <Controls.TextBoxGroup value={params.name!} onChange={(v) => this.updateParams({ name: v })} label='Name' onEnter={e => this.applyEnter(e) } placeholder='Optional name...' /> <Controls.QueryEditor value={params.queryString!} onChange={(v) => this.updateParams({ queryString: v })} onEnter={e => this.applyEnter(e) } /> </div> //<Controls.TextBoxGroup value={params.queryString} onChange={(v) => this.updateParams({ queryString: v })} onEnter={e => this.applyEnter(e) } label='Query' placeholder='Enter a query...' /> } } export class CreateMacromoleculeVisual extends Transform.ControllerBase<Bootstrap.Components.Transform.Controller<Transformer.Molecule.CreateMacromoleculeVisualParams>> { protected renderControls() { let params = this.params; return <div> <Controls.Toggle onChange={v => this.updateParams({ polymer: v })} value={params.polymer!} label='Polymer' /> <Controls.Toggle onChange={v => this.updateParams({ het: v })} value={params.het!} label='HET' /> <Controls.Toggle onChange={v => this.updateParams({ water: v })} value={params.water!} label='Water' /> </div>; } } export class CreateVisual extends Transform.ControllerBase<Bootstrap.Components.Transform.MoleculeVisual> { private detail() { let p = this.params.style!.params as Bootstrap.Visualization.Molecule.DetailParams; return [<Controls.OptionsGroup options={Bootstrap.Visualization.Molecule.DetailTypes} caption={s => s} current={p.detail} onChange={(o) => this.controller.updateStyleParams({ detail: o }) } label='Detail' />]; } private cartoons() { let p = this.params.style!.params as Bootstrap.Visualization.Molecule.CartoonParams; return [ <Controls.Toggle key={0} onChange={v => this.controller.updateStyleParams({ showDirectionCone: v }) } value={p.showDirectionCone} label='Dir. Cones' />, <Controls.OptionsGroup key={1} options={Bootstrap.Visualization.Molecule.DetailTypes} caption={s => s} current={p.detail} onChange={(o) => this.controller.updateStyleParams({ detail: o }) } label='Detail' />]; } private ballsAndSticks() { let p = this.params.style!.params as Bootstrap.Visualization.Molecule.BallsAndSticksParams; let controls: any[] = []; let key = 0; controls.push(<Controls.Toggle title='Scale atoms using their VDW radius.' onChange={v => this.controller.updateStyleParams({ useVDW: v }) } value={p.useVDW!} label='VDW' />); if (p.useVDW) { controls.push(<Controls.Slider key={key++} label='Scale' onChange={v => this.controller.updateStyleParams({ vdwScaling: v }) } min={0.1} max={1} step={0.01} value={p.vdwScaling!} title='VDW scale factor.' />); } else { controls.push(<Controls.Slider key={key++} label='Atom Rds' onChange={v => this.controller.updateStyleParams({ atomRadius: v }) } min={0.05} max={2} step={0.01} value={p.atomRadius!} title='Atom Radius' />); } controls.push(<Controls.Slider key={key++} label='Bond Rds' onChange={v => this.controller.updateStyleParams({ bondRadius: v }) } min={0.05} max={1} step={0.01} value={p.bondRadius!} title='Bond Radius' />); const maxHbondLength = p.customMaxBondLengths && p.customMaxBondLengths['H'] ? p.customMaxBondLengths['H'] : 1.15; controls.push(<Controls.Slider key={key++} label='H Bond Len' onChange={v => this.controller.updateStyleParams({ customMaxBondLengths: { ...p.customMaxBondLengths, 'H': v } }) } min={0.9} max={1.5} step={0.01} value={maxHbondLength} title='Maximum H bond length' />); controls.push(<Controls.Toggle key={key++} onChange={v => this.controller.updateStyleParams({ hideHydrogens: v }) } value={p.hideHydrogens!} label='Hide H' />); controls.push(<Controls.OptionsGroup key={key++} options={Bootstrap.Visualization.Molecule.DetailTypes} caption={s => s} current={p.detail} onChange={(o) => this.controller.updateStyleParams({ detail: o }) } label='Detail' />); return controls; } private surface() { let params = this.params.style!.params as Bootstrap.Visualization.Molecule.SurfaceParams; let key = 0; return [ <Controls.Slider key={key++} label='Probe Radius' onChange={v => this.controller.updateStyleParams({ probeRadius: v })} min={0} max={6} step={0.1} value={params.probeRadius!} />, <Controls.Slider key={key++} label='Smoothing' onChange={v => this.controller.updateStyleParams({ smoothing: v })} min={0} max={20} step={1} value={params.smoothing!} title='Number of laplacian smoothing itrations.' />, <Controls.Toggle key={key++} onChange={v => this.controller.updateStyleParams({ automaticDensity: v }) } value={params.automaticDensity!} label='Auto Detail' />, (params.automaticDensity ? void 0 : <Controls.Slider key={key++} label='Detail' onChange={v => this.controller.updateStyleParams({ density: v })} min={0.1} max={3} step={0.1} value={params.density!} title='Determines the size of a grid cell (size = 1/detail).' />), <Controls.Toggle key={key++} onChange={v => this.controller.updateStyleParams({ isWireframe: v }) } value={params.isWireframe!} label='Wireframe' /> ]; } private createColors() { let theme = this.params.style!.theme!; let isBallsAndSticks = this.params.style!.type === 'BallsAndSticks'; let controls = theme.colors! .filter((c, n) => !isBallsAndSticks ? n !== 'Bond' : true) .map((c, n) => <Controls.ToggleColorPicker key={n} label={n!} color={c!} onChange={c => this.controller.updateThemeColor(n!, c) } />).toArray(); controls.push(<TransparencyControl definition={theme.transparency!} onChange={d => this.controller.updateThemeTransparency(d) } />); // controls.push(<Controls.Toggle // onChange={v => this.controller.updateStyleTheme({ wireframe: v }) } value={theme.wireframe} label='Wireframe' />); return controls; } protected renderControls() { let params = this.params; let controls: any; switch (params.style!.type) { case 'Surface': controls = this.surface(); break; case 'BallsAndSticks': controls = this.ballsAndSticks(); break; case 'Cartoons': controls = this.cartoons(); break; default: controls = this.detail(); break; } let desc = (key: Bootstrap.Visualization.Molecule.Type) => Bootstrap.Visualization.Molecule.TypeDescriptions[key]; let showTypeOptions = this.getPersistentState('showTypeOptions', false); let showThemeOptions = this.getPersistentState('showThemeOptions', false); return <div> <Controls.ExpandableGroup select={<Controls.OptionsGroup options={Bootstrap.Visualization.Molecule.Types} caption={k => desc(k).label} current={params.style!.type} onChange={(o) => this.controller.updateTemplate(o, Bootstrap.Visualization.Molecule.Default.ForType) } label='Type' />} expander={<Controls.ControlGroupExpander isExpanded={showTypeOptions} onChange={e => this.setPersistentState('showTypeOptions', e) } />} options={controls} isExpanded={showTypeOptions} /> <Controls.ExpandableGroup select={<Controls.OptionsGroup options={Bootstrap.Visualization.Molecule.Default.Themes} caption={(k: Bootstrap.Visualization.Theme.Template) => k.name} current={params.style!.theme!.template} onChange={(o) => this.controller.updateThemeDefinition(o) } label='Coloring' />} expander={<Controls.ControlGroupExpander isExpanded={showThemeOptions} onChange={e => this.setPersistentState('showThemeOptions', e) } />} options={this.createColors()} isExpanded={showThemeOptions} /> </div> } } export class CreateLabels extends Transform.ControllerBase<Bootstrap.Components.Transform.MoleculeLabels> { renderControls() { const style = this.controller.latestState.params.style; const select = <Controls.OptionsGroup options={Bootstrap.Utils.Molecule.Labels3DKinds} caption={(k: string) => Bootstrap.Utils.Molecule.Labels3DKindLabels[k]} current={style.params.kind} onChange={(o) => this.controller.updateStyleParams({ kind: o }) } label='Kind' /> const showOptions = this.getPersistentState('showOptions', false); return <div> <Controls.ExpandableGroup select={select} expander={<Controls.ControlGroupExpander isExpanded={showOptions} onChange={e => this.setPersistentState('showOptions', e) } />} options={Labels.optionsControls(this.controller)} isExpanded={showOptions} /> </div>; } } }
the_stack
import { KeyboardEvents } from '../src/keyboard'; import { extend } from '../src/util'; import { createElement } from '../src/dom'; let ele: HTMLElement; let objKeyConfig: any; ele = createElement('div', { id: 'keytest' }); // Spec for KeyConfig Framework describe('KeyConfig', (): void => { describe('instance creation', () => { it('with default option', () => { let ele1: HTMLElement = createElement('div', { id: 'keytest' }); let kbEvt: KeyboardEvents = new KeyboardEvents( ele1, { keyConfigs: { selectAll: 'ctrl+a' }, keyAction: (): void => { /** Empty */ } }); //Cover onPropertyChanged function kbEvt.onPropertyChanged({}, {}); expect(kbEvt.element.classList.contains('e-keyboard')).toEqual(true); }); it('without default option', () => { ele = createElement('div', { id: 'keytest' }); objKeyConfig = new KeyboardEvents(ele); objKeyConfig.keyConfigs = { selectAll: 'ctrl+a' }; objKeyConfig.keyAction = () => { /** Empty */ }; //Cover the code since its not used. objKeyConfig.getModuleName(); expect(objKeyConfig.element.classList.contains('e-keyboard')).toEqual(true); }) }); describe('Action', () => { beforeAll(function () { spyOn(objKeyConfig, 'keyAction'); }); beforeEach(function () { objKeyConfig.keyAction.calls.reset(); }); it('single special key (ESC)', () => { let eventArgs: any = { which: 27, altKey: false, ctrlKey: false, shiftKey: false }; objKeyConfig.keyConfigs = { close: 'escape' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'close'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('single character key (A)', () => { let eventArgs: any = { which: 65, altKey: false, ctrlKey: false, shiftKey: false }; objKeyConfig.keyConfigs = { close: 'A' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'close'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('two key combination (Ctrl + A)', () => { let eventArgs: any = { which: 65, altKey: false, ctrlKey: true, shiftKey: false }; objKeyConfig.keyConfigs = { selectAll: 'ctrl+a' } objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'selectAll'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('three key combination (Ctrl + Shift + Delete)', () => { let eventArgs: any = { which: 46, altKey: false, ctrlKey: true, shiftKey: true }; objKeyConfig.keyConfigs = { permanentDelete: 'ctrl+shift+delete' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'permanentDelete'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('unhandled key code 202', () => { let eventArgs: any = { which: 202, altKey: true, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+a' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('multiple key config', () => { let eventArgs1: any = { which: 65, altKey: true, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+a', open: 'enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs1)); let eventArgs2: any = { which: 13, altKey: false, ctrlKey: false, shiftKey: false }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs2)); expect(objKeyConfig.keyAction).toHaveBeenCalledTimes(2); eventArgs1.action = 'maximize'; eventArgs2.action = 'open'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs1); expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs2); }); it('single action with multiple config', () => { let eventArgs1: any = { which: 40, altKey: false, ctrlKey: false, shiftKey: false }; let eventArgs2: any = { which: 40, altKey: false, ctrlKey: true, shiftKey: false }; let eventArgs3: any = { which: 38, altKey: false, ctrlKey: false, shiftKey: false }; let eventArgs4: any = { which: 38, altKey: false, ctrlKey: true, shiftKey: false }; objKeyConfig.keyConfigs = { down: 'downarrow,ctrl+downarrow', up: 'uparrow,ctrl+uparrow' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs1)); objKeyConfig.keyPressHandler(extend({}, {}, eventArgs2)); objKeyConfig.keyPressHandler(extend({}, {}, eventArgs3)); objKeyConfig.keyPressHandler(extend({}, {}, eventArgs4)); expect(objKeyConfig.keyAction).toHaveBeenCalledTimes(4); eventArgs1.action = 'down'; eventArgs2.action = 'down'; eventArgs3.action = 'up'; eventArgs4.action = 'up'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs1); expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs2); expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs3); expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs4); }); }); describe('Control Keys', () => { beforeEach(function () { objKeyConfig.keyAction.calls.reset(); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (true,true,true)', () => { let eventArgs: any = { which: 13, altKey: true, ctrlKey: true, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (false,true,true)', () => { let eventArgs: any = { which: 13, altKey: false, ctrlKey: true, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (true,true,false)', () => { let eventArgs: any = { which: 13, altKey: true, ctrlKey: true, shiftKey: false }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (true,false,true)', () => { let eventArgs: any = { which: 13, altKey: true, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'maximize'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (false,false,true)', () => { let eventArgs: any = { which: 13, altKey: false, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (false,true,false)', () => { let eventArgs: any = { which: 13, altKey: false, ctrlKey: true, shiftKey: false }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('key (Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (true,false,false)', () => { let eventArgs: any = { which: 13, altKey: true, ctrlKey: false, shiftKey: false }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'maximize'; expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); it('key ( Alt + Shift + Enter) with key (Alt,Ctrl,Shift) => (false,false,true)', () => { let eventArgs: any = { which: 13, altKey: false, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+enter' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); expect(objKeyConfig.keyAction).not.toHaveBeenCalled(); }); }); describe('Key Code', () => { beforeEach(function () { objKeyConfig.keyAction.calls.reset(); }); it('single key code (67)', () => { let eventArgs: any = { which: 67, altKey: false, ctrlKey: true, shiftKey: false }; objKeyConfig.keyConfigs = { maximize: 'ctrl+67' } objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'maximize'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('single special key code 202', () => { let eventArgs: any = { which: 202, altKey: false, ctrlKey: false, shiftKey: false }; objKeyConfig.keyConfigs = { maximize: '202' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'maximize'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('two key combination with keycode (Ctrl + 65)', () => { let eventArgs: any = { which: 65, altKey: false, ctrlKey: true, shiftKey: false }; objKeyConfig.keyConfigs = { selectAll: 'ctrl+65' } objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'selectAll'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); it('three key combination with keycode (Alt + Shift + 13) ', () => { let eventArgs: any = { which: 13, altKey: true, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+13' }; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'maximize'; expect(objKeyConfig.keyAction).toHaveBeenCalledWith(eventArgs); }); }); describe('API/Method', () => { it('keyAction handler test', () => { let eventArgs: any = { which: 13, altKey: true, ctrlKey: false, shiftKey: true }; objKeyConfig.keyConfigs = { maximize: 'alt+shift+13' }; let spyFun = jasmine.createSpy('keyAction') objKeyConfig.keyAction = spyFun; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); objKeyConfig.keyAction = null; objKeyConfig.keyPressHandler(extend({}, {}, eventArgs)); eventArgs.action = 'maximize'; expect(spyFun).toHaveBeenCalledTimes(1); expect(spyFun).toHaveBeenCalledWith(eventArgs); }); it('destroy class test', () => { expect(ele.classList.contains('e-keyboard')).toEqual(true); objKeyConfig.destroy(); expect(ele.classList.contains('e-keyboard')).toEqual(false); }); }); });
the_stack
import { SagaIterator } from 'redux-saga'; import { call, put, select } from 'redux-saga/effects'; import { ADD_NEW_USERS_TO_COURSE, CREATE_COURSE } from 'src/features/academy/AcademyTypes'; import { UsernameRoleGroup } from 'src/pages/academy/adminPanel/subcomponents/AddUserPanel'; import { OverallState, Role } from '../../commons/application/ApplicationTypes'; import { Assessment, AssessmentConfiguration, AssessmentOverview, AssessmentStatuses, FETCH_ASSESSMENT_OVERVIEWS, Question, SUBMIT_ASSESSMENT } from '../../commons/assessment/AssessmentTypes'; import { Notification, NotificationFilterFunction } from '../../commons/notificationBadge/NotificationBadgeTypes'; import { CHANGE_SUBLANGUAGE, WorkspaceLocation } from '../../commons/workspace/WorkspaceTypes'; import { FETCH_GROUP_GRADING_SUMMARY, GradingSummary } from '../../features/dashboard/DashboardTypes'; import { Grading, GradingOverview, GradingQuestion } from '../../features/grading/GradingTypes'; import { CHANGE_DATE_ASSESSMENT, DELETE_ASSESSMENT, PUBLISH_ASSESSMENT, UPLOAD_ASSESSMENT } from '../../features/groundControl/GroundControlTypes'; import { FETCH_SOURCECAST_INDEX } from '../../features/sourceRecorder/sourcecast/SourcecastTypes'; import { SAVE_SOURCECAST_DATA, SourcecastData } from '../../features/sourceRecorder/SourceRecorderTypes'; import { DELETE_SOURCECAST_ENTRY } from '../../features/sourceRecorder/sourcereel/SourcereelTypes'; import { ACKNOWLEDGE_NOTIFICATIONS, AdminPanelCourseRegistration, CourseConfiguration, CourseRegistration, DELETE_ASSESSMENT_CONFIG, DELETE_USER_COURSE_REGISTRATION, FETCH_ADMIN_PANEL_COURSE_REGISTRATIONS, FETCH_ASSESSMENT, FETCH_ASSESSMENT_CONFIGS, FETCH_AUTH, FETCH_COURSE_CONFIG, FETCH_GRADING, FETCH_GRADING_OVERVIEWS, FETCH_NOTIFICATIONS, FETCH_USER_AND_COURSE, REAUTOGRADE_ANSWER, REAUTOGRADE_SUBMISSION, SUBMIT_ANSWER, SUBMIT_GRADING, SUBMIT_GRADING_AND_CONTINUE, Tokens, UNSUBMIT_SUBMISSION, UPDATE_ASSESSMENT_CONFIGS, UPDATE_COURSE_CONFIG, UPDATE_COURSE_RESEARCH_AGREEMENT, UPDATE_LATEST_VIEWED_COURSE, UPDATE_USER_ROLE, UpdateCourseConfiguration, User } from '../application/types/SessionTypes'; import { actions } from '../utils/ActionsHelper'; import { computeRedirectUri, getClientId, getDefaultProvider } from '../utils/AuthHelper'; import { history } from '../utils/HistoryHelper'; import { showSuccessMessage, showWarningMessage } from '../utils/NotificationsHelper'; import { deleteAssessment, deleteSourcecastEntry, getAssessment, getAssessmentConfigs, getAssessmentOverviews, getCourseConfig, getGrading, getGradingOverviews, getGradingSummary, getLatestCourseRegistrationAndConfiguration, getNotifications, getSourcecastIndex, getUser, getUserCourseRegistrations, handleResponseError, postAcknowledgeNotifications, postAnswer, postAssessment, postAuth, postCreateCourse, postGrading, postReautogradeAnswer, postReautogradeSubmission, postSourcecast, postUnsubmit, putAssessmentConfigs, putCourseConfig, putCourseResearchAgreement, putLatestViewedCourse, putNewUsers, putUserRole, removeAssessmentConfig, removeUserCourseRegistration, updateAssessment, uploadAssessment } from './RequestsSaga'; import { safeTakeEvery as takeEvery } from './SafeEffects'; function selectTokens() { return select((state: OverallState) => ({ accessToken: state.session.accessToken, refreshToken: state.session.refreshToken })); } function* BackendSaga(): SagaIterator { yield takeEvery(FETCH_AUTH, function* (action: ReturnType<typeof actions.fetchAuth>): any { const { code, providerId: payloadProviderId } = action.payload; const providerId = payloadProviderId || (getDefaultProvider() || [null])[0]; if (!providerId) { yield call( showWarningMessage, 'Could not log in; invalid provider or no providers configured.' ); return yield history.push('/'); } const clientId = getClientId(providerId); const redirectUrl = computeRedirectUri(providerId); const tokens: Tokens | null = yield call(postAuth, code, providerId, clientId, redirectUrl); if (!tokens) { return yield history.push('/'); } yield put(actions.setTokens(tokens)); // Note: courseRegistration, courseConfiguration and assessmentConfigurations // are either all null OR all not null const { user, courseRegistration, courseConfiguration, assessmentConfigurations }: { user: User | null; courseRegistration: CourseRegistration | null; courseConfiguration: CourseConfiguration | null; assessmentConfigurations: AssessmentConfiguration[] | null; } = yield call(getUser, tokens); if (!user) { return; } yield put(actions.setUser(user)); // Handle case where user does not have a latest viewed course in the backend // but is enrolled in some course (this happens occationally due to e.g. removal from a course) if (courseConfiguration === null && user.courses.length > 0) { yield put(actions.updateLatestViewedCourse(user.courses[0].courseId)); } if (courseRegistration && courseConfiguration && assessmentConfigurations) { yield put(actions.setCourseRegistration(courseRegistration)); yield put(actions.setCourseConfiguration(courseConfiguration)); yield put(actions.setAssessmentConfigurations(assessmentConfigurations)); return yield history.push(`/courses/${courseRegistration.courseId}`); } return yield history.push(`/welcome`); }); yield takeEvery( FETCH_USER_AND_COURSE, function* (action: ReturnType<typeof actions.fetchUserAndCourse>): any { const tokens = yield selectTokens(); const { user, courseRegistration, courseConfiguration, assessmentConfigurations }: { user: User | null; courseRegistration: CourseRegistration | null; courseConfiguration: CourseConfiguration | null; assessmentConfigurations: AssessmentConfiguration[] | null; } = yield call(getUser, tokens); if (!user) { return; } yield put(actions.setUser(user)); // Handle case where user does not have a latest viewed course in the backend // but is enrolled in some course (this happens occationally due to e.g. removal from a course) if (courseConfiguration === null && user.courses.length > 0) { yield put(actions.updateLatestViewedCourse(user.courses[0].courseId)); } if (courseRegistration && courseConfiguration && assessmentConfigurations) { yield put(actions.setCourseRegistration(courseRegistration)); yield put(actions.setCourseConfiguration(courseConfiguration)); yield put(actions.setAssessmentConfigurations(assessmentConfigurations)); } } ); yield takeEvery(FETCH_COURSE_CONFIG, function* () { const tokens: Tokens = yield selectTokens(); const { config }: { config: CourseConfiguration | null } = yield call(getCourseConfig, tokens); if (config) { yield put(actions.setCourseConfiguration(config)); } }); yield takeEvery(FETCH_ASSESSMENT_OVERVIEWS, function* () { const tokens: Tokens = yield selectTokens(); const assessmentOverviews: AssessmentOverview[] | null = yield call( getAssessmentOverviews, tokens ); if (assessmentOverviews) { yield put(actions.updateAssessmentOverviews(assessmentOverviews)); } }); yield takeEvery(FETCH_ASSESSMENT, function* (action: ReturnType<typeof actions.fetchAssessment>) { const tokens: Tokens = yield selectTokens(); const id = action.payload; const assessment: Assessment | null = yield call(getAssessment, id, tokens); if (assessment) { yield put(actions.updateAssessment(assessment)); } }); yield takeEvery(SUBMIT_ANSWER, function* (action: ReturnType<typeof actions.submitAnswer>): any { const tokens: Tokens = yield selectTokens(); const questionId = action.payload.id; const answer = action.payload.answer; const resp: Response | null = yield call(postAnswer, questionId, answer, tokens); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield call(showSuccessMessage, 'Saved!', 1000); // Now, update the answer for the question in the assessment in the store const assessmentId: number = yield select( (state: OverallState) => state.workspaces.assessment.currentAssessment! ); const assessment: any = yield select((state: OverallState) => state.session.assessments.get(assessmentId) ); const newQuestions = assessment.questions.slice().map((question: Question) => { if (question.id === questionId) { return { ...question, answer }; } return question; }); const newAssessment = { ...assessment, questions: newQuestions }; yield put(actions.updateAssessment(newAssessment)); return yield put(actions.updateHasUnsavedChanges('assessment' as WorkspaceLocation, false)); }); yield takeEvery( SUBMIT_ASSESSMENT, function* (action: ReturnType<typeof actions.submitAssessment>): any { const tokens: Tokens = yield selectTokens(); const assessmentId = action.payload; const resp: Response | null = yield call(postAssessment, assessmentId, tokens); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield call(showSuccessMessage, 'Submitted!', 2000); // Now, update the status of the assessment overview in the store const overviews: AssessmentOverview[] = yield select( (state: OverallState) => state.session.assessmentOverviews ); const newOverviews = overviews.map(overview => { if (overview.id === assessmentId) { return { ...overview, status: AssessmentStatuses.submitted }; } return overview; }); return yield put(actions.updateAssessmentOverviews(newOverviews)); } ); yield takeEvery( FETCH_GRADING_OVERVIEWS, function* (action: ReturnType<typeof actions.fetchGradingOverviews>) { const tokens: Tokens = yield selectTokens(); const filterToGroup = action.payload; const gradingOverviews: GradingOverview[] | null = yield call( getGradingOverviews, tokens, filterToGroup ); if (gradingOverviews) { yield put(actions.updateGradingOverviews(gradingOverviews)); } } ); yield takeEvery(FETCH_GRADING, function* (action: ReturnType<typeof actions.fetchGrading>) { const tokens: Tokens = yield selectTokens(); const id = action.payload; const grading: Grading | null = yield call(getGrading, id, tokens); if (grading) { yield put(actions.updateGrading(id, grading)); } }); /** * Unsubmits the submission and updates the grading overviews of the new status. */ yield takeEvery( UNSUBMIT_SUBMISSION, function* (action: ReturnType<typeof actions.unsubmitSubmission>): any { const tokens: Tokens = yield selectTokens(); const { submissionId } = action.payload; const resp: Response | null = yield postUnsubmit(submissionId, tokens); if (!resp || !resp.ok) { return yield handleResponseError(resp); } const overviews: GradingOverview[] = yield select( (state: OverallState) => state.session.gradingOverviews || [] ); const newOverviews = overviews.map(overview => { if (overview.submissionId === submissionId) { return { ...overview, submissionStatus: 'attempted' }; } return overview; }); yield call(showSuccessMessage, 'Unsubmit successful', 1000); yield put(actions.updateGradingOverviews(newOverviews)); } ); const sendGrade = function* ( action: | ReturnType<typeof actions.submitGrading> | ReturnType<typeof actions.submitGradingAndContinue> ): any { const role: Role = yield select((state: OverallState) => state.session.role!); if (role === Role.Student) { return yield call(showWarningMessage, 'Only staff can submit answers.'); } const { submissionId, questionId, xpAdjustment, comments } = action.payload; const tokens: Tokens = yield selectTokens(); const resp: Response | null = yield postGrading( submissionId, questionId, xpAdjustment, tokens, comments ); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield call(showSuccessMessage, 'Submitted!', 1000); // Now, update the grade for the question in the Grading in the store const grading: Grading = yield select((state: OverallState) => state.session.gradings.get(submissionId) ); const newGrading = grading.slice().map((gradingQuestion: GradingQuestion) => { if (gradingQuestion.question.id === questionId) { gradingQuestion.grade = { xpAdjustment, xp: gradingQuestion.grade.xp, comments }; } return gradingQuestion; }); yield put(actions.updateGrading(submissionId, newGrading)); }; const sendGradeAndContinue = function* ( action: ReturnType<typeof actions.submitGradingAndContinue> ) { yield* sendGrade(action); const { submissionId } = action.payload; const [currentQuestion, courseId]: [number | undefined, number] = yield select( (state: OverallState) => [state.workspaces.grading.currentQuestion, state.session.courseId!] ); /** * Move to next question for grading: this only works because the * SUBMIT_GRADING_AND_CONTINUE Redux action is currently only * used in the Grading Workspace * * If the questionId is out of bounds, the componentDidUpdate callback of * GradingWorkspace will cause a redirect back to '/academy/grading' */ yield history.push( `/courses/${courseId}/grading/${submissionId}/${(currentQuestion || 0) + 1}` ); }; yield takeEvery(SUBMIT_GRADING, sendGrade); yield takeEvery(SUBMIT_GRADING_AND_CONTINUE, sendGradeAndContinue); yield takeEvery( REAUTOGRADE_SUBMISSION, function* (action: ReturnType<typeof actions.reautogradeSubmission>) { const submissionId = action.payload; const tokens: Tokens = yield selectTokens(); const resp: Response | null = yield call(postReautogradeSubmission, submissionId, tokens); yield call(handleReautogradeResponse, resp); } ); yield takeEvery( REAUTOGRADE_ANSWER, function* (action: ReturnType<typeof actions.reautogradeAnswer>) { const { submissionId, questionId } = action.payload; const tokens: Tokens = yield selectTokens(); const resp: Response | null = yield call( postReautogradeAnswer, submissionId, questionId, tokens ); yield call(handleReautogradeResponse, resp); } ); yield takeEvery( FETCH_NOTIFICATIONS, function* (action: ReturnType<typeof actions.fetchNotifications>) { const tokens: Tokens = yield selectTokens(); const notifications: Notification[] = yield call(getNotifications, tokens); yield put(actions.updateNotifications(notifications)); } ); yield takeEvery( ACKNOWLEDGE_NOTIFICATIONS, function* (action: ReturnType<typeof actions.acknowledgeNotifications>): any { const tokens: Tokens = yield selectTokens(); const notificationFilter: NotificationFilterFunction | undefined = action.payload.withFilter; const notifications: Notification[] = yield select( (state: OverallState) => state.session.notifications ); let notificationsToAcknowledge = notifications; if (notificationFilter) { notificationsToAcknowledge = notificationFilter(notifications); } if (notificationsToAcknowledge.length === 0) { return; } const ids = notificationsToAcknowledge.map(n => n.id); const newNotifications: Notification[] = notifications.filter( notification => !ids.includes(notification.id) ); yield put(actions.updateNotifications(newNotifications)); const resp: Response | null = yield call(postAcknowledgeNotifications, tokens, ids); if (!resp || !resp.ok) { return yield handleResponseError(resp); } } ); yield takeEvery( DELETE_SOURCECAST_ENTRY, function* (action: ReturnType<typeof actions.deleteSourcecastEntry>): any { const role: Role = yield select((state: OverallState) => state.session.role!); if (role === Role.Student) { return yield call(showWarningMessage, 'Only staff can delete sourcecasts.'); } const tokens: Tokens = yield selectTokens(); const { id } = action.payload; const resp: Response | null = yield deleteSourcecastEntry(id, tokens); if (!resp || !resp.ok) { return yield handleResponseError(resp); } const sourcecastIndex: SourcecastData[] | null = yield call(getSourcecastIndex, tokens); if (sourcecastIndex) { yield put(actions.updateSourcecastIndex(sourcecastIndex, action.payload.workspaceLocation)); } yield call(showSuccessMessage, 'Deleted successfully!', 1000); } ); yield takeEvery( FETCH_SOURCECAST_INDEX, function* (action: ReturnType<typeof actions.fetchSourcecastIndex>) { const tokens: Tokens = yield selectTokens(); const sourcecastIndex: SourcecastData[] | null = yield call(getSourcecastIndex, tokens); if (sourcecastIndex) { yield put(actions.updateSourcecastIndex(sourcecastIndex, action.payload.workspaceLocation)); } } ); yield takeEvery( SAVE_SOURCECAST_DATA, function* (action: ReturnType<typeof actions.saveSourcecastData>): any { const [role, courseId]: [Role, number | undefined] = yield select((state: OverallState) => [ state.session.role!, state.session.courseId ]); if (role === Role.Student) { return yield call(showWarningMessage, 'Only staff can save sourcecasts.'); } const { title, description, uid, audio, playbackData } = action.payload; const tokens: Tokens = yield selectTokens(); const resp: Response | null = yield postSourcecast( title, description, uid, audio, playbackData, tokens ); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield call(showSuccessMessage, 'Saved successfully!', 1000); yield history.push(`/courses/${courseId}/sourcecast`); } ); yield takeEvery( CHANGE_SUBLANGUAGE, function* (action: ReturnType<typeof actions.changeSublanguage>): any { const tokens: Tokens = yield selectTokens(); const { sublang } = action.payload; const resp: Response | null = yield call(putCourseConfig, tokens, { sourceChapter: sublang.chapter, sourceVariant: sublang.variant }); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put( actions.setCourseConfiguration({ sourceChapter: sublang.chapter, sourceVariant: sublang.variant }) ); yield call(showSuccessMessage, 'Updated successfully!', 1000); } ); yield takeEvery( UPDATE_LATEST_VIEWED_COURSE, function* (action: ReturnType<typeof actions.updateLatestViewedCourse>): any { const tokens: Tokens = yield selectTokens(); const { courseId } = action.payload; const resp: Response | null = yield call(putLatestViewedCourse, tokens, courseId); if (!resp || !resp.ok) { return yield handleResponseError(resp); } const { courseRegistration, courseConfiguration, assessmentConfigurations }: { courseRegistration: CourseRegistration | null; courseConfiguration: CourseConfiguration | null; assessmentConfigurations: AssessmentConfiguration[] | null; } = yield call(getLatestCourseRegistrationAndConfiguration, tokens); if (!courseRegistration || !courseConfiguration || !assessmentConfigurations) { yield call(showWarningMessage, `Failed to load course!`); return yield history.push('/welcome'); } yield put(actions.setCourseConfiguration(courseConfiguration)); yield put(actions.setAssessmentConfigurations(assessmentConfigurations)); yield put(actions.setCourseRegistration(courseRegistration)); yield call(showSuccessMessage, `Switched to ${courseConfiguration.courseName}!`, 5000); } ); yield takeEvery( UPDATE_COURSE_CONFIG, function* (action: ReturnType<typeof actions.updateCourseConfig>): any { const tokens: Tokens = yield selectTokens(); const courseConfig: UpdateCourseConfiguration = action.payload; const resp: Response | null = yield call(putCourseConfig, tokens, courseConfig); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.setCourseConfiguration(courseConfig)); yield call(showSuccessMessage, 'Updated successfully!', 1000); } ); yield takeEvery(FETCH_ASSESSMENT_CONFIGS, function* (): any { const tokens: Tokens = yield selectTokens(); const assessmentConfigs: AssessmentConfiguration[] | null = yield call( getAssessmentConfigs, tokens ); if (assessmentConfigs) { yield put(actions.setAssessmentConfigurations(assessmentConfigs)); } }); yield takeEvery( UPDATE_ASSESSMENT_CONFIGS, function* (action: ReturnType<typeof actions.updateAssessmentConfigs>): any { const tokens: Tokens = yield selectTokens(); const assessmentConfigs: AssessmentConfiguration[] = action.payload; const resp: Response | null = yield call(putAssessmentConfigs, tokens, assessmentConfigs); if (!resp || !resp.ok) { return yield handleResponseError(resp); } const updatedAssessmentConfigs: AssessmentConfiguration[] | null = yield call( getAssessmentConfigs, tokens ); if (updatedAssessmentConfigs) { yield put(actions.setAssessmentConfigurations(updatedAssessmentConfigs)); } yield call(showSuccessMessage, 'Updated successfully!', 1000); } ); yield takeEvery( DELETE_ASSESSMENT_CONFIG, function* (action: ReturnType<typeof actions.deleteAssessmentConfig>): any { const tokens: Tokens = yield selectTokens(); const assessmentConfig: AssessmentConfiguration = action.payload; const resp: Response | null = yield call(removeAssessmentConfig, tokens, assessmentConfig); if (!resp || !resp.ok) { return yield handleResponseError(resp); } } ); yield takeEvery( FETCH_ADMIN_PANEL_COURSE_REGISTRATIONS, function* (action: ReturnType<typeof actions.fetchAdminPanelCourseRegistrations>) { const tokens: Tokens = yield selectTokens(); const courseRegistrations: AdminPanelCourseRegistration[] | null = yield call( getUserCourseRegistrations, tokens ); if (courseRegistrations) { yield put(actions.setAdminPanelCourseRegistrations(courseRegistrations)); } } ); yield takeEvery(CREATE_COURSE, function* (action: ReturnType<typeof actions.createCourse>): any { const tokens: Tokens = yield selectTokens(); const courseConfig: UpdateCourseConfiguration = action.payload; const resp: Response | null = yield call(postCreateCourse, tokens, courseConfig); if (!resp || !resp.ok) { return yield handleResponseError(resp); } const { user, courseRegistration, courseConfiguration }: { user: User | null; courseRegistration: CourseRegistration | null; courseConfiguration: CourseConfiguration | null; assessmentConfigurations: AssessmentConfiguration[] | null; } = yield call(getUser, tokens); if (!user || !courseRegistration || !courseConfiguration) { return yield showWarningMessage('An error occurred. Please try again.'); } /** * setUser updates the Dropdown course selection menu with the updated courses * * Setting the role here handles an edge case where a user creates his first ever course. * Without it, the history.push below would not work as the /courses routes will not be rendered * (see Application.tsx) */ yield put(actions.setUser(user)); yield put(actions.setCourseRegistration({ role: Role.Student })); const placeholderAssessmentConfig = [ { type: 'Missions', assessmentConfigId: -1, isManuallyGraded: true, displayInDashboard: true, hoursBeforeEarlyXpDecay: 0, earlySubmissionXp: 0 } ]; const resp1: Response | null = yield call( putAssessmentConfigs, tokens, placeholderAssessmentConfig, courseRegistration.courseId ); if (!resp1 || !resp1.ok) { return yield handleResponseError(resp); } yield call(showSuccessMessage, 'Successfully created your new course!'); yield call([history, 'push'], `/courses/${courseRegistration.courseId}`); }); yield takeEvery( ADD_NEW_USERS_TO_COURSE, function* (action: ReturnType<typeof actions.addNewUsersToCourse>): any { const tokens: Tokens = yield selectTokens(); const { users, provider }: { users: UsernameRoleGroup[]; provider: string } = action.payload; const resp: Response | null = yield call(putNewUsers, tokens, users, provider); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.fetchAdminPanelCourseRegistrations()); yield call(showSuccessMessage, 'Users added!'); } ); yield takeEvery( UPDATE_USER_ROLE, function* (action: ReturnType<typeof actions.updateUserRole>): any { const tokens: Tokens = yield selectTokens(); const { courseRegId, role }: { courseRegId: number; role: Role } = action.payload; const resp: Response | null = yield call(putUserRole, tokens, courseRegId, role); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.fetchAdminPanelCourseRegistrations()); yield call(showSuccessMessage, 'Role updated!'); } ); yield takeEvery( UPDATE_COURSE_RESEARCH_AGREEMENT, function* (action: ReturnType<typeof actions.updateCourseResearchAgreement>): any { const tokens: Tokens = yield selectTokens(); const { agreedToResearch } = action.payload; const resp: Response | null = yield call( putCourseResearchAgreement, tokens, agreedToResearch ); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.setCourseRegistration({ agreedToResearch })); yield call(showSuccessMessage, 'Research preference saved!'); } ); yield takeEvery( DELETE_USER_COURSE_REGISTRATION, function* (action: ReturnType<typeof actions.deleteUserCourseRegistration>): any { const tokens: Tokens = yield selectTokens(); const { courseRegId }: { courseRegId: number } = action.payload; const resp: Response | null = yield call(removeUserCourseRegistration, tokens, courseRegId); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.fetchAdminPanelCourseRegistrations()); yield call(showSuccessMessage, 'User deleted!'); } ); yield takeEvery( FETCH_GROUP_GRADING_SUMMARY, function* (action: ReturnType<typeof actions.fetchGroupGradingSummary>) { const tokens: Tokens = yield selectTokens(); const groupOverviews: GradingSummary | null = yield call(getGradingSummary, tokens); if (groupOverviews) { yield put(actions.updateGroupGradingSummary(groupOverviews)); } } ); yield takeEvery( CHANGE_DATE_ASSESSMENT, function* (action: ReturnType<typeof actions.changeDateAssessment>): any { const tokens: Tokens = yield selectTokens(); const id = action.payload.id; const closeAt = action.payload.closeAt; const openAt = action.payload.openAt; const resp: Response | null = yield updateAssessment(id, { openAt, closeAt }, tokens); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.fetchAssessmentOverviews()); yield call(showSuccessMessage, 'Updated successfully!', 1000); } ); yield takeEvery( DELETE_ASSESSMENT, function* (action: ReturnType<typeof actions.deleteAssessment>): any { const tokens: Tokens = yield selectTokens(); const id = action.payload; const resp: Response | null = yield deleteAssessment(id, tokens); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.fetchAssessmentOverviews()); yield call(showSuccessMessage, 'Deleted successfully!', 1000); } ); yield takeEvery( PUBLISH_ASSESSMENT, function* (action: ReturnType<typeof actions.publishAssessment>): any { const tokens: Tokens = yield selectTokens(); const id = action.payload.id; const togglePublishTo = action.payload.togglePublishTo; const resp: Response | null = yield updateAssessment( id, { isPublished: togglePublishTo }, tokens ); if (!resp || !resp.ok) { return yield handleResponseError(resp); } yield put(actions.fetchAssessmentOverviews()); if (togglePublishTo) { yield call(showSuccessMessage, 'Published successfully!', 1000); } else { yield call(showSuccessMessage, 'Unpublished successfully!', 1000); } } ); yield takeEvery( UPLOAD_ASSESSMENT, function* (action: ReturnType<typeof actions.uploadAssessment>): any { const tokens: Tokens = yield selectTokens(); const { file, forceUpdate, assessmentConfigId } = action.payload; const resp: Response | null = yield uploadAssessment( file, tokens, forceUpdate, assessmentConfigId ); if (!resp || !resp.ok) { return yield handleResponseError(resp); } const respText: string = yield resp.text(); if (respText === 'OK') { yield call(showSuccessMessage, 'Uploaded successfully!', 2000); } else if (respText === 'Force Update OK') { yield call(showSuccessMessage, 'Assessment force updated successfully!', 2000); } yield put(actions.fetchAssessmentOverviews()); } ); } function* handleReautogradeResponse(resp: Response | null): any { if (resp && resp.ok) { return yield call(showSuccessMessage, 'Autograde job queued successfully.'); } if (resp && resp.status === 400) { return yield call(showWarningMessage, 'Cannot reautograde non-submitted submission.'); } return yield call(showWarningMessage, 'Failed to queue autograde job.'); } export default BackendSaga;
the_stack
import React from 'react' import Utils from '../../../utils/utils' import { CanvasPoint, CanvasRectangle, CanvasVector } from '../../../core/shared/math-utils' import { ElementPath } from '../../../core/shared/project-file-types' import { Guideline, Guidelines, XAxisGuideline, YAxisGuideline } from '../guideline' //TODO: switch to functional component and make use of 'useColorTheme': import { colorTheme } from '../../../uuiui' const StrokeColor = colorTheme.canvasLayoutStroke.value const LineEndSegmentSize = 3.5 type GuidelineWithDistance = { guideline: Guideline distance: number } function guidelinesClosestToDragOrFrame( frame: CanvasRectangle, guidelines: Array<Guideline>, includeCentre: boolean, ): Array<Guideline> { let xAxisGuideline: GuidelineWithDistance | null = null let yAxisGuideline: GuidelineWithDistance | null = null for (const guideline of guidelines) { const { distance } = Guidelines.distanceFromFrameToGuideline(frame, guideline, includeCentre) switch (guideline.type) { case 'XAxisGuideline': if (xAxisGuideline == null) { xAxisGuideline = { guideline: guideline, distance: distance } } else if (distance < xAxisGuideline.distance) { xAxisGuideline = { guideline: guideline, distance: distance } } break case 'YAxisGuideline': if (yAxisGuideline == null) { yAxisGuideline = { guideline: guideline, distance: distance } } else if (distance < yAxisGuideline.distance) { yAxisGuideline = { guideline: guideline, distance: distance } } break case 'CornerGuideline': // Skip these for now. break default: const _exhaustiveCheck: never = guideline throw new Error(`Unhandled guideline ${JSON.stringify(guideline)}`) } } // We want corner guidelines to take precendence over the edge guidelines. // This means we don't awkward snap to a corner and an edge. Utils.fastForEach(guidelines, (guideline) => { switch (guideline.type) { case 'CornerGuideline': const { distance } = Guidelines.distanceFromFrameToGuideline( frame, guideline, includeCentre, ) const willSetToX = xAxisGuideline == null || distance < xAxisGuideline.distance const willSetToY = yAxisGuideline == null || distance < yAxisGuideline.distance if (willSetToX || willSetToY) { xAxisGuideline = { guideline: guideline, distance: distance } yAxisGuideline = { guideline: guideline, distance: distance } } break case 'XAxisGuideline': case 'YAxisGuideline': // We've already handled these. break default: const _exhaustiveCheck: never = guideline throw new Error(`Unhandled guideline ${JSON.stringify(guideline)}`) } }) if (xAxisGuideline == null) { if (yAxisGuideline == null) { return [] } else { return [yAxisGuideline.guideline] } } else { if (yAxisGuideline == null) { return [xAxisGuideline.guideline] } else { return [xAxisGuideline.guideline, yAxisGuideline.guideline] } } } interface DistanceGuidelineProps { canvasOffset: CanvasVector scale: number selectedViews: Array<ElementPath> highlightedViews: Array<ElementPath> boundingBox: CanvasRectangle guidelines: Array<Guideline> } export class DistanceGuideline extends React.Component<DistanceGuidelineProps> { getNewControlForDistance( distance: number, from: CanvasPoint, to: CanvasPoint, id: string, ): Array<JSX.Element> { const horizontal = from.y === to.y const isFromBottomRight = from.x > to.x || from.y > to.y // it looks like this: |---| // the closing end is shifted with 1px to make it appear on the edge not after return [ this.getLineEndControl(from, horizontal, `${id}-start`, isFromBottomRight), this.getLineControl(from, to, id, horizontal), this.getLineEndControl(to, horizontal, `${id}-end`, !isFromBottomRight), this.getDistanceTextControl(from, to, distance, horizontal, `${id}-label`), ] } getDistanceTextControl( from: CanvasPoint, to: CanvasPoint, distance: number, isHorizontal: boolean, id: string, ): JSX.Element { const fontSize = 11 / this.props.scale let position: CanvasPoint let width: undefined | number if (isHorizontal) { position = { x: Math.min(from.x, to.x), y: Math.min(from.y, to.y), } as CanvasPoint width = Math.abs(from.x - to.x) } else { const offset = { x: 2 / this.props.scale, y: -fontSize / 2, } as CanvasPoint const middle = { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2, } as CanvasPoint position = Utils.offsetPoint(middle, offset) } return ( <div key={id} style={{ position: 'absolute', left: this.props.canvasOffset.x + position.x, top: this.props.canvasOffset.y + position.y, width: width, textAlign: 'center', fontFamily: '-apple-system, BlinkMacSystemFont, Helvetica, "Segoe UI", Roboto, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"', fontSize: fontSize, color: StrokeColor, pointerEvents: 'none', }} > {`${distance.toFixed(0)}`} </div> ) } getLineControl(from: CanvasPoint, to: CanvasPoint, id: string, horizontal: boolean): any { const topLeft = { x: Math.min(from.x, to.x), y: Math.min(from.y, to.y), } as CanvasPoint const strokeWidth = 1 / this.props.scale // offset with half of the strokewidth to make the line centered const strokeWidthOffset = { x: horizontal ? 0 : -strokeWidth / 2, y: horizontal ? -strokeWidth / 2 : 0, } as CanvasPoint const position = Utils.offsetPoint(topLeft, strokeWidthOffset) return ( <div key={id} style={{ left: this.props.canvasOffset.x + position.x, top: this.props.canvasOffset.y + position.y, position: 'absolute', width: horizontal ? Math.abs(to.x - from.x) : strokeWidth, height: horizontal ? strokeWidth : Math.abs(to.y - from.y), backgroundColor: StrokeColor, pointerEvents: 'none', }} /> ) } getLineEndControl( origin: CanvasPoint, horizontal: boolean, id: string, needsStrokeWidthOffset: boolean, ): any { const segmentSize = LineEndSegmentSize const horizontalSize = horizontal ? 0 : segmentSize / this.props.scale const verticalSize = horizontal ? segmentSize / this.props.scale : 0 const topLeft = { x: -horizontalSize, y: -verticalSize, } as CanvasPoint const strokeWidth = 1 / this.props.scale const strokeWidthOffset = { x: horizontal ? -strokeWidth : 0, y: horizontal ? 0 : -strokeWidth, } as CanvasPoint const position = needsStrokeWidthOffset ? Utils.offsetPoint(Utils.offsetPoint(origin, topLeft), strokeWidthOffset) : Utils.offsetPoint(origin, topLeft) return ( <div key={id} style={{ left: this.props.canvasOffset.x + position.x, top: this.props.canvasOffset.y + position.y, position: 'absolute', width: horizontal ? strokeWidth : horizontalSize * 2, height: horizontal ? verticalSize * 2 : strokeWidth, backgroundColor: StrokeColor, pointerEvents: 'none', }} /> ) } distanceControlsFor( guidelines: Array<Guideline>, closestGuidelines: Array<Guideline>, isDragging: boolean, frame: CanvasRectangle, bothAxesOverlap: boolean, ): Array<JSX.Element> { if (bothAxesOverlap) { const xAxisGuidelines = guidelines.filter((g) => g.type === 'XAxisGuideline') as Array< XAxisGuideline > const yAxisGuidelines = guidelines.filter((g) => g.type === 'YAxisGuideline') as Array< YAxisGuideline > const guidelineXs = xAxisGuidelines.map((g) => g.x) const guidelineYs = yAxisGuidelines.map((g) => g.y) const leftGuidelineX = Math.min(...guidelineXs) const rightGuidelineX = Math.max(...guidelineXs) const topGuidelineY = Math.min(...guidelineYs) const bottomGuidelineY = Math.max(...guidelineYs) const midX = frame.x + frame.width / 2 const midY = frame.y + frame.height / 2 const leftStart = { x: leftGuidelineX, y: midY } as CanvasPoint const leftEnd = { x: frame.x, y: midY } as CanvasPoint const rightStart = { x: rightGuidelineX, y: midY } as CanvasPoint const rightEnd = { x: frame.x + frame.width, y: midY } as CanvasPoint const topStart = { x: midX, y: topGuidelineY } as CanvasPoint const topEnd = { x: midX, y: frame.y } as CanvasPoint const bottomStart = { x: midX, y: bottomGuidelineY } as CanvasPoint const bottomEnd = { x: midX, y: frame.y + frame.height } as CanvasPoint return [ ...this.getNewControlForDistance( Math.abs(frame.x - leftGuidelineX), leftStart, leftEnd, 'distance-left', ), ...this.getNewControlForDistance( Math.abs(frame.x + frame.width - rightGuidelineX), rightStart, rightEnd, 'distance-right', ), ...this.getNewControlForDistance( Math.abs(frame.y - topGuidelineY), topStart, topEnd, 'distance-top', ), ...this.getNewControlForDistance( Math.abs(frame.y + frame.height - bottomGuidelineY), bottomStart, bottomEnd, 'distance', ), ] } else { return closestGuidelines.flatMap((guideline, i) => { const { distance, from, to } = Guidelines.distanceFromFrameToGuideline( frame, guideline, isDragging, ) return this.getNewControlForDistance(distance, from, to, `distance-${i}`) }) } } static doBothAxesOverlap(guidelines: Array<Guideline>, boundingRectangle: CanvasRectangle) { function leftOfRightEdge(guideline: Guideline) { return ( guideline.type === 'XAxisGuideline' && guideline.x < boundingRectangle.x + boundingRectangle.width ) } function rightOfLeftEdge(guideline: Guideline) { return guideline.type === 'XAxisGuideline' && guideline.x > boundingRectangle.x } function belowTopEdge(guideline: Guideline) { return guideline.type === 'YAxisGuideline' && guideline.y > boundingRectangle.y } function aboveBottomEdge(guideline: Guideline) { return ( guideline.type === 'YAxisGuideline' && guideline.y < boundingRectangle.y + boundingRectangle.height ) } const xAxisOverlaps = guidelines.some(leftOfRightEdge) && guidelines.some(rightOfLeftEdge) const yAxisOverlaps = guidelines.some(belowTopEdge) && guidelines.some(aboveBottomEdge) return xAxisOverlaps && yAxisOverlaps } render() { const closestGuidelines = guidelinesClosestToDragOrFrame( this.props.boundingBox, this.props.guidelines, false, ) const bothAxesOverlap = DistanceGuideline.doBothAxesOverlap( this.props.guidelines, this.props.boundingBox, ) const distanceControls = this.distanceControlsFor( this.props.guidelines, closestGuidelines, false, this.props.boundingBox, bothAxesOverlap, ) return <div className='role-distance-guidelines'>{distanceControls}</div> } }
the_stack
import _ from 'lodash'; import { AppResource, Component, ComponentDSL, Content, ContentVersion, DslSchemas, EditorEntry, ResourceType, } from '@foxpage/foxpage-server-types'; import { TYPE } from '../../../config/constant'; import * as Model from '../../models'; import { ComponentContentInfo, ComponentInfo, ComponentNameVersion } from '../../types/component-types'; import { AppNameVersion, AppTypeContent, ComponentRecursive, ContentLiveVersion, ContentVersionString, NameVersion, NameVersionContent, NameVersionPackage, } from '../../types/content-types'; import { TRecord } from '../../types/index-types'; import { BaseService } from '../base-service'; import * as Service from '../index'; export class ComponentContentService extends BaseService<Content> { private static _instance: ComponentContentService; constructor() { super(Model.content); } /** * Single instance * @returns ContentService */ public static getInstance (): ComponentContentService { this._instance || (this._instance = new ComponentContentService()); return this._instance; } /** * Get all data information from DSL * @param {applicationId} string * @param {DslSchemas[]} schemas * @returns Promise */ async getComponentsFromDSL (applicationId: string, schemas: DslSchemas[]): Promise<Component[]> { // Get component name infos const componentInfos = this.getComponentInfoRecursive(schemas); const componentList = await this.getComponentDetails(applicationId, componentInfos); return componentList; } /** * Recursively obtain component information of all levels in the DSL * @param {DslSchemas[]} components * @returns NameVersion */ getComponentInfoRecursive (schemas: DslSchemas[]): NameVersion[] { let componentInfo: NameVersion[] = []; schemas?.forEach((schema) => { schema.name && componentInfo.push({ name: schema.name, version: schema.version || '' }); if (schema.children && schema.children.length > 0) { const children = this.getComponentInfoRecursive(schema.children); componentInfo = componentInfo.concat(children); } }); return componentInfo; } /** * Get the component details under the specified application through the component name and version * @param {string} applicationId * @param {NameVersion[]} componentInfos * @returns Promise */ async getComponentDetails ( applicationId: string, componentInfos: NameVersion[], showLiveVersion: boolean = true, ): Promise<Component[]> { // Get the file corresponding to the component const fileList = await Service.file.info.find({ applicationId, name: { $in: _.map(componentInfos, 'name') }, deleted: false, }); // replace reference component fileList.forEach(file => { if (file.tags && file.tags.length > 0) { const referTag = _.find(file.tags, { type: 'reference' }); referTag?.reference && (file.id = referTag.reference.id || ''); } }); // Get the corresponding contentIds under the file let contentVersionString: ContentVersionString[] = []; let contentVersionNumber: ContentLiveVersion[] = []; const contentList = await Service.content.file.getContentByFileIds(_.map(fileList, 'id')); const contentNameObject: Record<string, Content> = _.keyBy(contentList, 'title'); componentInfos.forEach((component) => { if (contentNameObject[component.name] && component.version) { contentVersionString.push({ contentId: contentNameObject[component.name].id, version: component.version, }); } else { contentVersionNumber.push(_.pick(contentNameObject[component.name], ['id', 'liveVersionNumber'])); } }); // Get content containing different versions of the same component const versionList = await Promise.all([ Service.version.list.getContentInfoByIdAndNumber(contentVersionNumber), Service.version.list.getContentInfoByIdAndVersion(contentVersionString), ]); const contentIdObject: Record<string, Content> = _.keyBy(contentList, 'id'); const liveVersionObject: Record<string, ContentLiveVersion> = _.keyBy(contentVersionNumber, 'id'); const componentList: Component[] = _.flatten(versionList).map((version) => { return Object.assign( { name: contentIdObject[version.contentId].title, version: showLiveVersion || version.versionNumber !== liveVersionObject[version.contentId]?.liveVersionNumber ? version.version : '', type: TYPE.COMPONENT, }, version.content, ); }); return componentList; } /** * Get the resource ids set by the component from the component list * @param {ContentVersion[]} componentList * @returns Promise */ getComponentResourceIds (componentList: Component[]): string[] { let componentIds: string[] = []; componentList.forEach((component) => { const item = <Record<string, string>>component?.resource?.entry || {}; componentIds = componentIds.concat(_.pull(_.values(item), '')); }); return _.filter(componentIds, (id) => _.isString(id)); } /** * Replace the resource id in the component with the resource details * @param {ContentVersion[]} componentList * @param {Record<string} resourceObject * @param {} object> * @returns ContentVersion */ replaceComponentResourceIdWithContent ( componentList: Component[], resourceObject: TRecord<TRecord<string>>, contentResource: Record<string, AppResource> = {}, ): Component[] { let newComponentList: Component[] = _.cloneDeep(componentList); newComponentList.forEach((component) => { const item = <Record<string, string>>component?.resource?.entry || {}; (Object.keys(item) as ResourceType[]).forEach((typeKey) => { const path = resourceObject[item[typeKey]]?.realPath || ''; const contentId = item[typeKey] || ''; item[typeKey] = contentId ? ({ host: contentResource?.[contentId]?.detail.host || '', downloadHost: contentResource?.[contentId]?.detail.downloadHost || '', path: _.pull(path.split('/'), '').join('/'), contentId, } as any) : {}; }); }); return newComponentList; } /** * Get the id of the component editor from the component details, version * @param {Component[]} componentList * @returns string */ getComponentEditors (componentList: Component[]): EditorEntry[] { let editorIdVersion: EditorEntry[] = []; componentList.forEach((component) => { editorIdVersion = editorIdVersion.concat(component?.resource?.['editor-entry'] || []); }); return editorIdVersion; } /** * Get the editor information from the component, and return the component details of the editor * @param {string} applicationId * @param {Component[]} componentList * @returns Promise */ async getEditorDetailFromComponent ( applicationId: string, componentList: Component[], ): Promise<Component[]> { const editorIdVersion = Service.content.component.getComponentEditors(componentList); const editorFileObject = await Service.file.list.getContentFileByIds(_.map(editorIdVersion, 'id')); const editorComponentIds = _.pull(_.map(_.toArray(editorFileObject), 'id'), ''); if (editorComponentIds.length > 0) { editorIdVersion.forEach((editor) => (editor.name = editorFileObject[editor.id]?.name || '')); } return Service.content.component.getComponentDetails(applicationId, editorIdVersion as NameVersion[]); } /** * Recursively get the details of the component, * Check the validity of the components * Check whether the component has a circular dependency * @param {string} applicationId * @param {NameVersion[]} componentInfos * @param {Record<string} componentDependents * @param {} string[]>={} * @returns Promise */ async getComponentDetailRecursive ( applicationId: string, componentInfos: NameVersion[], componentDependents: Record<string, string[]> = {}, ): Promise<ComponentRecursive> { let componentList = await Service.version.info.getVersionDetailByFileNameVersion( applicationId, TYPE.COMPONENT, componentInfos, ); // Check the component, whether the version is returned let missingComponents: NameVersion[] = []; const componentListObject: Record<string, NameVersionContent> = _.keyBy( componentList, (component) => component.name + component.version, ); componentInfos?.forEach((component) => { !componentListObject[component.name + component.version] && missingComponents.push(component); }); if (missingComponents.length > 0) { return { componentList, dependence: {}, recursiveItem: '', missingComponents }; } const dependence = Service.version.component.getComponentDependsFromVersions(componentList); const componentDepend = Service.content.check.checkCircularDependence(componentDependents, dependence); let dependenceObject = componentDepend.dependencies; const nextDepends: NameVersion[] = _.flatten(Object.values(dependence)).map((depend) => { return { name: depend, version: '' }; }); if (!componentDepend.recursiveItem && nextDepends.length > 0) { const dependDependence = await this.getComponentDetailRecursive( applicationId, nextDepends, dependenceObject, ); componentList = componentList.concat(dependDependence.componentList); componentDepend.recursiveItem = dependDependence.recursiveItem; dependenceObject = dependDependence.dependence; missingComponents = dependDependence.missingComponents; } componentList = _.toArray( _.keyBy(componentList, (component) => [component.name, component.version].join('_')), ); return { componentList, dependence: dependenceObject, recursiveItem: componentDepend.recursiveItem, missingComponents, }; } /** * Get the component details by name, version, * and return the object with the passed name_version as the key name * @param {ComponentNameVersion} params * @returns Promise */ async getComponentDetailByNameVersion ( params: ComponentNameVersion, ): Promise<Record<string, ComponentInfo>> { const fileList = await Service.file.info.getFileIdByNames({ applicationId: params.applicationId, fileNames: _.map(params.nameVersions, 'name'), type: params.type || [], }); // Get content information through fileId, and the version details corresponding to the specified name version const contentList = await Service.content.file.getContentByFileIds(_.map(fileList, 'id')); const [contentVersionList, contentFileObject] = await Promise.all([ Service.version.list.getContentVersionListByNameVersion(contentList, params.nameVersions), Service.file.list.getContentFileByIds(_.map(contentList, 'id')), ]); let versionObject: Record<string, ComponentContentInfo> = {}; const contentObject = _.keyBy(contentList, 'id'); let nameLive: Record<string, string> = {}; contentVersionList.forEach((version) => { const componentName = contentFileObject[version.contentId]?.name || ''; const liveVersion = contentObject[version.contentId]?.liveVersionNumber || 0; if (componentName) { nameLive[componentName] = version.versionNumber === liveVersion ? version.version : ''; versionObject[[componentName, version.version].join('_')] = Object.assign( { name: componentName, type: contentFileObject[version.contentId]?.type || '', isLive: version.versionNumber === liveVersion, version: version.version, }, version.content || {}, ); } }); let nameVersionDetail: Record<string, ComponentInfo> = {}; params.nameVersions.forEach((item) => { const key = [item.name, item.version].join('_'); if (item.version) { nameVersionDetail[key] = Object.assign(item, { content: versionObject[key] || {} }); } else { nameVersionDetail[key] = Object.assign(item, { content: versionObject[[item.name, nameLive[item.name]].join('_')] || {}, }); } }); return nameVersionDetail; } /** * Get the content version details of the component through the content name and version, * the same name has different versions of data * Prerequisite: The content name is the same as the file name (for example: component type content), * and there is only 1 content information under the file * * Get the versionNumber of the content with the version, * and get the versionNumber of the live if there is no version, * Get content details through contentId, versionNumber * @param {AppNameVersion} params * @returns {NameVersionPackage[]} Promise */ async getAppComponentByNameVersion (params: AppNameVersion): Promise<NameVersionPackage[]> { // Get the fileIds of the specified name of the specified application const fileList = await Service.file.info.getFileIdByNames({ applicationId: params.applicationId, type: params.type || '', fileNames: _.map(params.contentNameVersion, 'name'), }); // Get content information through fileId const contentList = await Service.content.file.getContentByFileIds(_.map(fileList, 'id')); // Get the version details corresponding to the specified name version const contentVersionList = await Service.version.list.getContentVersionListByNameVersion( contentList, params.contentNameVersion, ); // Get the details corresponding to different versions of contentId, // including live details with contentId as the key const contentVersionObject = Service.version.info.mappingContentVersionInfo( contentList, contentVersionList, ); // Match data let contentId: string = ''; let version: string = ''; let componentContentList: NameVersionPackage[] = []; const fileObject = _.keyBy(fileList, 'id'); const contentIdObject = _.keyBy(contentList, 'id'); const contentNameObject = _.keyBy(contentList, 'title'); params.contentNameVersion.forEach((content) => { contentId = contentNameObject[content.name]?.id || ''; version = content.version || ''; if (contentVersionObject[contentId + version]) { componentContentList.push( Object.assign({ version }, content, { package: Object.assign({}, contentVersionObject[contentId + version].content, { name: content.name, version: contentVersionObject[contentId + version].version, type: fileObject[contentIdObject[contentId].fileId]?.type, }), }) as NameVersionPackage, ); } else { componentContentList.push(content); } }); return componentContentList; } /** * Get the live version details of the component content under the specified application, * and return the content version details * @param {AppTypeContent} params * @returns {NameVersionPackage[]} Promise */ async getComponentVersionLiveDetails (params: AppTypeContent): Promise<NameVersionPackage[]> { const contentIds = params.contentIds || []; let contentInfo: Content[] = []; // Get contentIds if (contentIds.length === 0) { contentInfo = await Service.content.list.getAppContentList(_.pick(params, ['applicationId', 'type'])); } else { // Check whether contentIds is under the specified appId contentInfo = await Service.content.list.getDetailByIds(contentIds); contentInfo = _.filter(contentInfo, { deleted: false }); } // Get live details let contentVersionList: ContentVersion[] = []; if (contentInfo.length > 0) { const contentLiveIds = contentInfo.map((content) => _.pick(content, ['id', 'liveVersionNumber'])); contentVersionList = await Service.version.list.getContentInfoByIdAndNumber(contentLiveIds); } const contentObject = _.keyBy(contentInfo, 'id'); // Data returned by splicing return contentVersionList.map((contentVersion) => { return Object.assign( { name: contentObject[contentVersion.contentId].title }, { version: contentVersion.version, package: contentVersion.content as ComponentDSL }, ); }); } }
the_stack
import { VerticalRefreshRateContext } from '@seorii/win32-displayconfig' import { BrowserWindow } from './browserWindow' import * as electron from 'electron' import process from 'process' import debug from './debug' function sleep(duration: number) { return new Promise<void>((resolve: () => void) => setTimeout(resolve, duration) ) } function areBoundsEqual( /*unknown*/ left: any, /*unknown*/ right: any ): boolean { return ( left.height === right.height && left.width === right.width && left.x === right.x && left.y === right.y ) } const billion = 1000 * 1000 * 1000 function hrtimeDeltaForFrequency(freq: number) { return BigInt(Math.ceil(billion / freq)) } let disableJitterFix = false // Detect if cursor is near the screen edge. Used to disable the jitter fix in 'move' event. function isInSnapZone(): boolean { const point = electron.screen.getCursorScreenPoint() const display = electron.screen.getDisplayNearestPoint(point) // Check if cursor is near the left/right edge of the active display return ( (point.x > display.bounds.x - 20 && point.x < display.bounds.x + 20) || (point.x > display.bounds.x + display.bounds.width - 20 && point.x < display.bounds.x + display.bounds.width + 20) ) } /** * Unfortunately, we have to re-implement moving and resizing. * Enabling vibrancy slows down the window's event handling loop to the * point building a mouse event backlog. If you just handle these events * in the backlog without taking the time difference into consideration, * you end up with visible movement lag. * We tried pairing 'will-move' with 'move', but Electron actually sends the * 'move' events _before_ Windows actually commits to the operation. There's * likely some queuing going on that's getting backed up. This is not the case * with 'will-resize' and 'resize', which need to use the default behavior * for compatibility with soft DPI scaling. * The ideal rate of moving and resizing is based on the vertical sync * rate: if your display is only fully updating at 120 Hz, we shouldn't * be attempting to reset positions or sizes any faster than 120 Hz. * If we were doing this in a browser context, we would just use * requestAnimationFrame and call it a day. But we're not inside of a * browser context here, so we have to resort to clever hacks. * This VerticalRefreshRateContext maps a point in screen space to the * vertical sync rate of the display(s) actually handing that point. * It handles multiple displays with varying vertical sync rates, * and changes to the display configuration while this process is running. */ export default function win10refresh( win: BrowserWindow, maximumRefreshRate: number ) { const refreshCtx = new VerticalRefreshRateContext() function getRefreshRateAtCursor( cursor: Partial<electron.Rectangle> & electron.Point ) { cursor = cursor || electron.screen.getCursorScreenPoint() return refreshCtx.findVerticalRefreshRateForDisplayPoint( cursor.x, cursor.y ) } // Ensure all movement operation is serialized, by setting up a continuous promise chain // All movement operation will take the form of // // boundsPromise = boundsPromise.then(() => { /* work */ }) // // So that there are no asynchronous race conditions. let pollingRate: number let doFollowUpQuery = false, isMoving = false, shouldMove = false let moveLastUpdate = BigInt(0), resizeLastUpdate = BigInt(0) let lastWillMoveBounds: electron.Rectangle, lastWillResizeBounds: electron.Rectangle, desiredMoveBounds: electron.Rectangle | undefined let boundsPromise: any = Promise.race([ getRefreshRateAtCursor(electron.screen.getCursorScreenPoint()).then( (rate) => { pollingRate = rate || 30 doFollowUpQuery = true } ), // Establishing the display configuration can fail; we can't // just block forever if that happens. Instead, establish // a fallback polling rate and hope for the best. sleep(2000).then(() => { pollingRate = pollingRate || 30 }), ]) async function doFollowUpQueryIfNecessary( cursor: Partial<electron.Rectangle> & electron.Point ) { if (doFollowUpQuery) { const rate = await getRefreshRateAtCursor(cursor) if (rate != pollingRate) debug(`New polling rate: ${rate}`) pollingRate = rate || 30 } } function setWindowBounds(bounds: electron.Rectangle) { if (win.isDestroyed()) return win.setBounds(bounds) desiredMoveBounds = win.getBounds() } function currentTimeBeforeNextActivityWindow( lastTime: bigint, forceFreq?: number ) { return ( process.hrtime.bigint() < lastTime + hrtimeDeltaForFrequency(forceFreq || pollingRate || 30) ) } function guardingAgainstMoveUpdate(fn: any) { if ( pollingRate === undefined || !currentTimeBeforeNextActivityWindow(moveLastUpdate) ) { moveLastUpdate = process.hrtime.bigint() fn() return true } else { return false } } win.on('will-move', (e, newBounds) => { if (win.__electron_acrylic_window__.opacityInterval) return // We get a _lot_ of duplicate bounds sent to us in this event. // This messes up our timing quite a bit. if ( lastWillMoveBounds !== undefined && areBoundsEqual(lastWillMoveBounds, newBounds) ) { e.preventDefault() return } if (lastWillMoveBounds) { newBounds.width = lastWillMoveBounds.width newBounds.height = lastWillMoveBounds.height } lastWillMoveBounds = newBounds // If we're asked to perform some move update and it's under // the refresh speed limit, we can just do it immediately. // This also catches moving windows with the keyboard. const didOptimisticMove = !isMoving && guardingAgainstMoveUpdate(() => { // Do nothing, the default behavior of the event is exactly what we want. desiredMoveBounds = undefined }) if (didOptimisticMove) { boundsPromise = boundsPromise.then(doFollowUpQueryIfNecessary) return } e.preventDefault() // Track if the user is moving the window if (win.__electron_acrylic_window__.moveTimeout) clearTimeout(win.__electron_acrylic_window__.moveTimeout) win.__electron_acrylic_window__.moveTimeout = setTimeout(() => { shouldMove = false }, 1000 / Math.min(pollingRate, maximumRefreshRate)) // Disable next event ('move') if cursor is near the screen edge disableJitterFix = isInSnapZone() // Start new behavior if not already if (!shouldMove) { shouldMove = true if (isMoving) return false isMoving = true // Get start positions const basisBounds = win.getBounds() const basisCursor = electron.screen.getCursorScreenPoint() // Handle polling at a slower interval than the setInterval handler function handleIntervalTick(moveInterval: any) { boundsPromise = boundsPromise.then(() => { if (!shouldMove) { isMoving = false clearInterval(moveInterval) return } const cursor = electron.screen.getCursorScreenPoint() const didIt = guardingAgainstMoveUpdate(() => { // Set new position if (lastWillResizeBounds && lastWillResizeBounds.width) setWindowBounds({ x: Math.floor( basisBounds.x + (cursor.x - basisCursor.x) ), y: Math.floor( basisBounds.y + (cursor.y - basisCursor.y) ), width: Math.floor( lastWillResizeBounds.width / electron.screen.getDisplayMatching( basisBounds ).scaleFactor ), height: Math.floor( lastWillResizeBounds.height / electron.screen.getDisplayMatching( basisBounds ).scaleFactor ), }) else setWindowBounds({ x: Math.floor( basisBounds.x + (cursor.x - basisCursor.x) ), y: Math.floor( basisBounds.y + (cursor.y - basisCursor.y) ), width: Math.floor( lastWillMoveBounds.width / electron.screen.getDisplayMatching( basisBounds ).scaleFactor ), height: Math.floor( lastWillMoveBounds.height / electron.screen.getDisplayMatching( basisBounds ).scaleFactor ), }) }) if (didIt) { return doFollowUpQueryIfNecessary(cursor) } }) } // Poll at 600hz while moving window const moveInterval: NodeJS.Timer = setInterval( () => handleIntervalTick(moveInterval), 1000 / 600 ) } }) win.on('move', (e: electron.Event) => { if (disableJitterFix) { return false } if (isMoving || win.isDestroyed()) { e.preventDefault() return false } // As insane as this sounds, Electron sometimes reacts to prior // move events out of order. Specifically, if you have win.setBounds() // twice, then for some reason, when you exit the move state, the second // call to win.setBounds() gets reverted to the first call to win.setBounds(). // // Again, it's nuts. But what we can do in this circumstance is thwack the // window back into place just to spite Electron. Yes, there's a shiver. // No, there's not much we can do about it until Electron gets their act together. if (desiredMoveBounds !== undefined) { const forceBounds = desiredMoveBounds desiredMoveBounds = undefined win.setBounds({ x: Math.floor(forceBounds.x), y: Math.floor(forceBounds.y), width: Math.floor(forceBounds.width), height: Math.floor(forceBounds.height), }) } }) win.on('will-resize', (e, newBounds) => { if ( lastWillResizeBounds !== undefined && areBoundsEqual(lastWillResizeBounds, newBounds) ) { e.preventDefault() return } lastWillResizeBounds = newBounds // 60 Hz ought to be enough... for resizes. // Some systems have trouble going 120 Hz, so we'll just take the lower // of the current pollingRate and 60 Hz. if ( pollingRate !== undefined && currentTimeBeforeNextActivityWindow( resizeLastUpdate, Math.min(pollingRate, maximumRefreshRate) ) ) { e.preventDefault() return false } // We have to count this twice: once before the resize, // and once after the resize. We actually don't have any // timing control around _when_ the resize happened, so // we have to be pessimistic. resizeLastUpdate = process.hrtime.bigint() }) win.on('resize', () => { resizeLastUpdate = process.hrtime.bigint() boundsPromise = boundsPromise.then(doFollowUpQueryIfNecessary) }) // Close the VerticalRefreshRateContext so Node can exit cleanly win.on('closed', refreshCtx.close) }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormAppointment { interface Header extends DevKit.Controls.IHeader { /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Shows whether the appointment is open, completed, or canceled. Completed and canceled appointments are read-only and can't be edited. */ StateCode: DevKit.Controls.OptionSet; } interface tab_appointment_Sections { appointment_description: DevKit.Controls.Section; attachments: DevKit.Controls.Section; general_information: DevKit.Controls.Section; scheduling_information: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_appointment extends DevKit.Controls.ITab { Section: tab_appointment_Sections; } interface Tabs { appointment: tab_appointment; } interface Body { Tab: Tabs; /** Type additional information to describe the purpose of the appointment. */ Description: DevKit.Controls.String; /** Select whether the appointment is an all-day event to make sure that the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.Controls.Boolean; /** Type the location where the appointment will take place, such as a conference room or customer office. */ Location: DevKit.Controls.String; /** Enter the account, contact, lead, user, or other equipment resources that are not needed at the appointment, but can optionally attend. */ OptionalAttendees: DevKit.Controls.Lookup; /** Choose the record that the appointment relates to. */ RegardingObjectId: DevKit.Controls.Lookup; /** Enter the account, contact, lead, user, or other equipment resources that are required to attend the appointment. */ requiredattendees: DevKit.Controls.Lookup; /** Shows the expected duration of the appointment, in minutes. */ ScheduledDurationMinutes: DevKit.Controls.Integer; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the appointment. */ ScheduledEnd: DevKit.Controls.DateTime; /** Enter the expected start date and time for the activity to provide details about the timing of the appointment. */ ScheduledStart: DevKit.Controls.DateTime; /** Type a short description about the objective or primary topic of the appointment. */ Subject: DevKit.Controls.String; } interface Grid { attachmentsGrid: DevKit.Controls.Grid; } } class FormAppointment extends DevKit.IForm { /** * DynamicsCrm.DevKit form Appointment * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Appointment */ Body: DevKit.FormAppointment.Body; /** The Header section of form Appointment */ Header: DevKit.FormAppointment.Header; /** The Grid of form Appointment */ Grid: DevKit.FormAppointment.Grid; } namespace FormAppointment_for_Interactive_experience { interface Header extends DevKit.Controls.IHeader { /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the appointment. */ ScheduledEnd: DevKit.Controls.DateTime; /** Shows whether the appointment is open, completed, or canceled. Completed and canceled appointments are read-only and can't be edited. */ StateCode: DevKit.Controls.OptionSet; } interface tab_tab_5_Sections { appointment_description: DevKit.Controls.Section; tab_5_section_2: DevKit.Controls.Section; tab_5_section_3: DevKit.Controls.Section; tab_5_section_5: DevKit.Controls.Section; } interface tab_tab_5 extends DevKit.Controls.ITab { Section: tab_tab_5_Sections; } interface Tabs { tab_5: tab_tab_5; } interface Body { Tab: Tabs; /** Type additional information to describe the purpose of the appointment. */ Description: DevKit.Controls.String; /** Select whether the appointment is an all-day event to make sure that the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.Controls.Boolean; /** Type the location where the appointment will take place, such as a conference room or customer office. */ Location: DevKit.Controls.String; /** Enter the account, contact, lead, user, or other equipment resources that are not needed at the appointment, but can optionally attend. */ OptionalAttendees: DevKit.Controls.Lookup; /** Choose the record that the appointment relates to. */ RegardingObjectId: DevKit.Controls.Lookup; /** Choose the record that the appointment relates to. */ RegardingObjectId_1: DevKit.Controls.Lookup; /** Enter the account, contact, lead, user, or other equipment resources that are required to attend the appointment. */ requiredattendees: DevKit.Controls.Lookup; /** Shows the expected duration of the appointment, in minutes. */ ScheduledDurationMinutes: DevKit.Controls.Integer; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the appointment. */ ScheduledEnd: DevKit.Controls.DateTime; /** Enter the expected start date and time for the activity to provide details about the timing of the appointment. */ ScheduledStart: DevKit.Controls.DateTime; /** Type a short description about the objective or primary topic of the appointment. */ Subject: DevKit.Controls.String; } interface Grid { attachmentsGrid: DevKit.Controls.Grid; } } class FormAppointment_for_Interactive_experience extends DevKit.IForm { /** * DynamicsCrm.DevKit form Appointment_for_Interactive_experience * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Appointment_for_Interactive_experience */ Body: DevKit.FormAppointment_for_Interactive_experience.Body; /** The Header section of form Appointment_for_Interactive_experience */ Header: DevKit.FormAppointment_for_Interactive_experience.Header; /** The Grid of form Appointment_for_Interactive_experience */ Grid: DevKit.FormAppointment_for_Interactive_experience.Grid; } namespace FormAppointment_Wizard { interface Header extends DevKit.Controls.IHeader { /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; } interface tab_appointment_Sections { appointment_description: DevKit.Controls.Section; attachments: DevKit.Controls.Section; general_information: DevKit.Controls.Section; Hidden_Section: DevKit.Controls.Section; scheduling_information: DevKit.Controls.Section; } interface tab_appointment extends DevKit.Controls.ITab { Section: tab_appointment_Sections; } interface Tabs { appointment: tab_appointment; } interface Body { Tab: Tabs; /** Type additional information to describe the purpose of the appointment. */ Description: DevKit.Controls.String; /** Select whether the appointment is an all-day event to make sure that the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.Controls.Boolean; /** Type the location where the appointment will take place, such as a conference room or customer office. */ Location: DevKit.Controls.String; /** Enter the account, contact, lead, user, or other equipment resources that are not needed at the appointment, but can optionally attend. */ OptionalAttendees: DevKit.Controls.Lookup; /** Choose the record that the appointment relates to. */ RegardingObjectId: DevKit.Controls.Lookup; /** Enter the account, contact, lead, user, or other equipment resources that are required to attend the appointment. */ requiredattendees: DevKit.Controls.Lookup; /** Shows the expected duration of the appointment, in minutes. */ ScheduledDurationMinutes: DevKit.Controls.Integer; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the appointment. */ ScheduledEnd: DevKit.Controls.DateTime; /** Enter the expected start date and time for the activity to provide details about the timing of the appointment. */ ScheduledStart: DevKit.Controls.DateTime; /** Select the appointment's status. */ StatusCode: DevKit.Controls.OptionSet; /** Type a short description about the objective or primary topic of the appointment. */ Subject: DevKit.Controls.String; } interface Grid { attachmentsGrid: DevKit.Controls.Grid; } } class FormAppointment_Wizard extends DevKit.IForm { /** * DynamicsCrm.DevKit form Appointment_Wizard * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Appointment_Wizard */ Body: DevKit.FormAppointment_Wizard.Body; /** The Header section of form Appointment_Wizard */ Header: DevKit.FormAppointment_Wizard.Header; /** The Grid of form Appointment_Wizard */ Grid: DevKit.FormAppointment_Wizard.Grid; } namespace FormAppointment_quick_create_form { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Type additional information to describe the purpose of the appointment. */ Description: DevKit.Controls.String; /** Select whether the appointment is an all-day event to make sure that the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.Controls.Boolean; /** Type the location where the appointment will take place, such as a conference room or customer office. */ Location: DevKit.Controls.String; /** Enter the account, contact, lead, user, or other equipment resources that are not needed at the appointment, but can optionally attend. */ OptionalAttendees: DevKit.Controls.Lookup; /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Choose the record that the appointment relates to. */ RegardingObjectId: DevKit.Controls.Lookup; /** Enter the account, contact, lead, user, or other equipment resources that are required to attend the appointment. */ requiredattendees: DevKit.Controls.Lookup; /** Shows the expected duration of the appointment, in minutes. */ ScheduledDurationMinutes: DevKit.Controls.Integer; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the appointment. */ ScheduledEnd: DevKit.Controls.DateTime; /** Enter the expected start date and time for the activity to provide details about the timing of the appointment. */ ScheduledStart: DevKit.Controls.DateTime; /** Type a short description about the objective or primary topic of the appointment. */ Subject: DevKit.Controls.String; } } class FormAppointment_quick_create_form extends DevKit.IForm { /** * DynamicsCrm.DevKit form Appointment_quick_create_form * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Appointment_quick_create_form */ Body: DevKit.FormAppointment_quick_create_form.Body; } class AppointmentApi { /** * DynamicsCrm.DevKit AppointmentApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the appointment. */ ActivityId: DevKit.WebApi.GuidValue; /** Shows the value selected in the Duration field on the appointment at the time that the appointment is closed as completed. The duration is used to report the time spent on the activity. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the actual end date and time of the appointment. By default, it displays the date and time when the activity was completed or canceled, but can be edited to capture the actual duration of the appointment. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the actual start date and time for the appointment. By default, it displays the date and time when the activity was created, but can be edited to capture the actual duration of the appointment. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the number of attachments on the appointment. */ AttachmentCount: DevKit.WebApi.IntegerValueReadonly; /** Select the error code to identify issues with the outlook item recipients or attachments, such as blocked attachments. */ AttachmentErrors: DevKit.WebApi.OptionSetValue; /** Type a category to identify the appointment type, such as sales demo, prospect call, or service call, to tie the appointment to a business group or function. */ Category: DevKit.WebApi.StringValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type additional information to describe the purpose of the appointment. */ Description: DevKit.WebApi.StringValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the ID of the appointment in Microsoft Office Outlook. The ID is used to synchronize the appointment between Microsoft Dynamics 365 and the correct Exchange account. */ GlobalObjectId: DevKit.WebApi.StringValue; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Select whether the appointment is an all-day event to make sure that the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.WebApi.BooleanValue; /** Information regarding whether the appointment was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** Information regarding whether the appointment is a draft. */ IsDraft: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** For internal use only. */ IsUnsafe: DevKit.WebApi.IntegerValueReadonly; /** Information regarding whether the appointment was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Type the location where the appointment will take place, such as a conference room or customer office. */ Location: DevKit.WebApi.StringValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ ModifiedFieldsMask: DevKit.WebApi.StringValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** The original start date of the appointment. */ OriginalStartDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the Microsoft Office Outlook appointment owner that correlates to the PR_OWNER_APPT_ID MAPI property. */ OutlookOwnerApptId: DevKit.WebApi.IntegerValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Shows the business unit that the record owner belongs to. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the appointment. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the appointment. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Shows the ID of the process. */ ProcessId: DevKit.WebApi.GuidValue; /** Choose the record that the appointment relates to. */ regardingobjectid_account_appointment: DevKit.WebApi.LookupValue; /** Choose the record that the appointment relates to. */ regardingobjectid_contact_appointment: DevKit.WebApi.LookupValue; /** Choose the record that the appointment relates to. */ regardingobjectid_knowledgearticle_appointment: DevKit.WebApi.LookupValue; /** Choose the record that the appointment relates to. */ regardingobjectid_knowledgebaserecord_appointment: DevKit.WebApi.LookupValue; /** Safe body text of the appointment. */ SafeDescription: DevKit.WebApi.StringValueReadonly; /** Shows the expected duration of the appointment, in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the appointment. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the expected start date and time for the activity to provide details about the timing of the appointment. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the ID of the recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Choose the service level agreement (SLA) that you want to apply to the appointment record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this appointment. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the ID of the stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the appointment is open, completed, or canceled. Completed and canceled appointments are read-only and can't be edited. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the appointment's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Type a subcategory to identify the appointment type and relate the activity to a specific product, sales region, business group, or other function. */ Subcategory: DevKit.WebApi.StringValue; /** Type a short description about the objective or primary topic of the appointment. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ SubscriptionId: DevKit.WebApi.GuidValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the appointment. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace Appointment { enum AttachmentErrors { /** 0 */ None, /** 1 */ The_appointment_was_saved_as_a_Microsoft_Dynamics_365_appointment_record_but_not_all_the_attachments_could_be_saved_with_it_An_attachment_cannot_be_saved_if_it_is_blocked_or_if_its_file_type_is_invalid } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open, /** 3 */ Scheduled } enum StatusCode { /** 5 */ Busy, /** 4 */ Canceled, /** 3 */ Completed, /** 1 */ Free, /** 6 */ Out_of_Office, /** 2 */ Tentative } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Appointment','Appointment for Interactive experience','Appointment quick create form.','Wizard'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { ActorSystemRef, localActorRef, LocalActorRef, LocalActorSystemRef, localTemporaryRef } from "./references"; import { Deferral } from './deferral'; import { applyOrThrowIfStopped } from './system-map'; import Queue from './vendored/denque'; import assert from './assert'; import { defaultSupervisionPolicy, SupervisionActions } from './supervision'; import { ActorPath } from "./paths"; import { Milliseconds } from "."; import { addMacrotask, clearMacrotask } from './macrotask' import { ICanAssertNotStopped, ICanDispatch, ICanHandleFault, ICanManageTempReferences, ICanQuery, ICanReset, ICanStop, IHaveChildren, IHaveName, InferResponseFromMsgFactory, QueryMsgFactory } from "./interfaces"; function unit(): void { }; export type ActorName = string; // type InferMsgFromRef<R extends Ref<any>> = R extends Ref<infer Msg> ? Msg : never; type ParentTypeFromRefType<P extends LocalActorSystemRef | LocalActorRef<any>> = P extends ActorSystemRef ? RequiredActorSystemCapabilities : (P extends LocalActorRef<infer Msg> ? (RequiredChildCapabilities & ICanDispatch<Msg> & ICanHandleFault<RequiredChildCapabilities> & IHaveChildren<RequiredChildCapabilities, RequiredActorSystemCapabilities>) : never); type RequiredChildCapabilities = ICanReset & ICanStop & IHaveChildren<RequiredChildCapabilities, RequiredActorSystemCapabilities> & IHaveName & ICanAssertNotStopped; type RequiredActorSystemCapabilities = ICanReset & ICanStop & IHaveChildren<RequiredChildCapabilities, RequiredActorSystemCapabilities> & IHaveName & ICanHandleFault<RequiredChildCapabilities> & ICanAssertNotStopped & ICanManageTempReferences; export class Actor<State, Msg, ParentRef extends LocalActorSystemRef | LocalActorRef<any>, Child extends RequiredChildCapabilities = RequiredChildCapabilities> implements ICanDispatch<Msg>, ICanStop, ICanQuery<Msg>, IHaveName, IHaveChildren<Child, RequiredActorSystemCapabilities>, ICanReset, ICanHandleFault<Child>, ICanAssertNotStopped { // TODO: Swap concreate parent class for interfaces parent: ParentTypeFromRefType<ParentRef> name: ActorName; path: ActorPath; system: RequiredActorSystemCapabilities; afterStop: (state: State, ctx: ActorContextWithMailbox<Msg, ParentRef>) => void | Promise<void>; reference: LocalActorRef<Msg>; f: ActorFunc<State, Msg, ParentRef>; stopped: boolean; // TODO: Swap concreate child classes for interfaces children: Map<any, Child>; childReferences: Map<any, LocalActorRef<unknown>>; busy: boolean; mailbox: Queue<{ message: Msg }>; immediate: number | undefined; onCrash: SupervisionActorFunc<Msg, ParentRef> | ((msg: any, err: any, ctx: any, child?: undefined | LocalActorRef<unknown>) => any); initialState: State | undefined; initialStateFunc: ((ctx: ActorContext<Msg, ParentRef>) => State) | undefined; shutdownPeriod?: Milliseconds; state: any; timeout?: Milliseconds; setTimeout: () => void; constructor( parent: ParentTypeFromRefType<ParentRef>, system: RequiredActorSystemCapabilities, f: ActorFunc<State, Msg, ParentRef>, { name, shutdownAfter, onCrash, initialState, initialStateFunc, afterStop }: ActorProps<State, Msg, ParentRef> = {}) { this.parent = parent; if (!name) { name = `anonymous-${Math.abs(Math.random() * Number.MAX_SAFE_INTEGER) | 0}`; } if (parent.children.has(name)) { throw new Error(`child actor of name ${name} already exists`); } this.name = name; this.path = ActorPath.createChildPath(parent.reference.path, this.name); this.system = system; this.afterStop = afterStop || (() => { }); this.reference = localActorRef(this.path); this.f = f; this.stopped = false; this.children = new Map(); this.childReferences = new Map(); this.busy = false; this.mailbox = new Queue(); this.immediate = undefined; this.parent.childSpawned(this); this.onCrash = onCrash || defaultSupervisionPolicy; this.initialState = initialState; this.initialStateFunc = initialStateFunc; if (shutdownAfter) { if (typeof (shutdownAfter) !== 'number') { throw new Error('Shutdown should be specified as a number in milliseconds'); } this.shutdownPeriod = Actor.getSafeTimeout(shutdownAfter); this.setTimeout = () => { this.timeout = globalThis.setTimeout(() => this.stop(), this.shutdownPeriod) as unknown as number; }; } else { this.setTimeout = unit; } this.initializeState(); this.setTimeout(); } initializeState() { if (this.initialStateFunc) { try { this.state = this.initialStateFunc(this.createContext()); } catch (e) { this.handleFault(undefined, undefined, e); } } else { this.state = this.initialState; } } reset() { [...this.children.values()].forEach(x => x.stop()); this.initializeState(); this.resume(); } clearTimeout() { globalThis.clearTimeout(this.timeout); } clearImmediate() { clearMacrotask(this.immediate); } static getSafeTimeout(timeoutDuration: any) { timeoutDuration = timeoutDuration | 0; const MAX_TIMEOUT = 2147483647; return Math.min(MAX_TIMEOUT, timeoutDuration); } assertNotStopped() { assert(!this.stopped); return true; } afterMessage() { } dispatch(message: Msg) { this.assertNotStopped(); this.clearTimeout(); if (!this.busy) { this.handleMessage(message); } else { this.mailbox.push({ message }); } return Promise.resolve(); } query<MsgCreator extends QueryMsgFactory<Msg, any>>(queryFactory: MsgCreator, timeout: Milliseconds): Promise<InferResponseFromMsgFactory<MsgCreator>> { this.assertNotStopped(); assert(timeout !== undefined && timeout !== null); const deferred = new Deferral<InferResponseFromMsgFactory<MsgCreator>>(); timeout = Actor.getSafeTimeout(timeout); const timeoutHandle = globalThis.setTimeout(() => { deferred.reject(new Error('Query Timeout ' + timeout)); }, timeout); const tempReference = localTemporaryRef(this.system.name); this.system.addTempReference(tempReference, deferred); deferred.promise.then(() => { globalThis.clearTimeout(timeoutHandle); this.system.removeTempReference(tempReference); }).catch(() => { this.system.removeTempReference(tempReference); }); const message = queryFactory(tempReference); this.dispatch(message); return deferred.promise; } childStopped(child: Child) { this.children.delete(child.name); this.childReferences.delete(child.name); } childSpawned(child: Child) { this.children.set(child.name, child); this.childReferences.set(child.name, child.reference as LocalActorRef<unknown>); } stop() { const context = this.createContextWithMailbox(); this.clearImmediate(); this.clearTimeout(); this.parent.childStopped(this); delete (this as any).parent; [...this.children.values()].forEach(x => x.stop()); this.stopped = true; addMacrotask(() => this.afterStop(this.state, context)); } processNext() { if (!this.stopped) { const nextMsg = this.mailbox.shift(); if (nextMsg) { this.handleMessage(nextMsg.message); } else { this.busy = false; // Counter is now ticking until actor is killed this.setTimeout(); } } } async handleFault(msg: unknown, error: Error | undefined, child: undefined | Child = undefined) { const ctx = this.createSupervisionContext(); const decision = await Promise.resolve(this.onCrash(msg, error, ctx, child?.reference as LocalActorRef<unknown>)); switch (decision) { // Stop Self case SupervisionActions.stop: this.stop(); break; // Stop Self and Peers case SupervisionActions.stopAll: [...this.parent.children.values()].forEach(x => x.stop()); break; // Stop Child case SupervisionActions.stopChild: assert(child, 'Expected child'); this.children.get(child.name)?.stop(); break; // Stop All Children case SupervisionActions.stopAllChildren: [...this.children.values()].forEach(x => x.stop()); break; // Resume case SupervisionActions.resume: this.resume(); break; // Reset Self case SupervisionActions.reset: this.reset(); break; // Reset Self and Peers case SupervisionActions.resetAll: this.parent.children.forEach(x => x.reset()); break; // Reset Child case SupervisionActions.resetChild: assert(child, 'Expected child'); this.children.get(child.name)?.reset(); break; // Reset all Children case SupervisionActions.resetAllChildren: [...this.children.values()].forEach(x => x.reset()); break; // Escalate to Parent case SupervisionActions.escalate: default: this.parent.handleFault(msg, error, this); break; } } resume() { this.processNext(); } createSupervisionContext() { const ctx = this.createContextWithMailbox(); return { ...ctx, ...SupervisionActions }; } createContextWithMailbox() { const ctx = this.createContext(); return { ...ctx, mailbox: this.mailbox.toArray() }; } createContext(): ActorContext<Msg, ParentRef> { return { parent: this.parent.reference as ParentRef, path: this.path, self: this.reference, name: this.name, children: new Map(this.childReferences), }; } handleMessage(message: Msg) { this.busy = true; this.immediate = addMacrotask(async () => { try { let ctx = this.createContext(); let next = await Promise.resolve(this.f.call(ctx, this.state, message, ctx)); this.state = next; this.afterMessage(); this.processNext(); } catch (e) { this.handleFault(message, e); } }); } } // Contexts export type ActorContext<Msg, ParentRef extends LocalActorRef<any> | ActorSystemRef> = { parent: ParentRef, path: ActorPath, self: LocalActorRef<Msg>, name: ActorName, children: Map<ActorName, LocalActorRef<unknown>>, }; // export type PersistentActorContext<Msg, ParentRef extends ActorSystemRef | ActorRef<any, any>> = // ActorContext<MSGesture, ParentRef> & { persist: (msg: Msg) => Promise<void> }; export type Mailbox<Msg> = { message: Msg }[]; export type ActorContextWithMailbox<Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = ActorContext<Msg, ParentRef> & { mailbox: Mailbox<Msg> }; export type SupervisionContext<Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = ActorContextWithMailbox<Msg, ParentRef> & { stop: Symbol, stopAll: Symbol, stopChild: Symbol, stopAllChildren: Symbol, escalate: Symbol, resume: Symbol, reset: Symbol, resetAll: Symbol, resetChild: Symbol, resetAllChildren: Symbol, mailbox: { message: Msg }[] }; // Functions export type ActorFunc<State, Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = (this: ActorContext<Msg, ParentRef>, state: State, msg: Msg, ctx: ActorContext<Msg, ParentRef>) => State | Promise<State>; export type StatelessActorFunc<Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = (this: ActorContext<Msg, ParentRef>, msg: Msg, ctx: ActorContext<Msg, ParentRef>) => any; export type SupervisionActorFunc<Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = (msg: unknown, err: Error | undefined, ctx: SupervisionContext<Msg, ParentRef>, child: LocalActorRef<unknown>) => Symbol | Promise<Symbol>; // Inference helpers type InferMsgFromFunc<T extends ActorFunc<any, any, any>> = T extends ActorFunc<any, infer Msg, any> ? Msg : never; type InferStateFromFunc<T extends ActorFunc<any, any, any>> = T extends ActorFunc<infer State, any, any> ? State : never; type InferMsgFromStatelessFunc<T extends StatelessActorFunc<any, any>> = T extends StatelessActorFunc<infer Msg, any> ? Msg : never; // Props export type NumberOfMessages = number; export type Json = unknown; export type ActorProps<State, Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = { name?: string, shutdownAfter?: Milliseconds, onCrash?: SupervisionActorFunc<Msg, ParentRef>, initialState?: State, initialStateFunc?: (ctx: ActorContext<Msg, ParentRef>) => State, afterStop?: (state: State, ctx: ActorContextWithMailbox<Msg, ParentRef>) => void | Promise<void> }; export type StatelessActorProps<Msg, ParentRef extends ActorSystemRef | LocalActorRef<any>> = Omit<ActorProps<any, Msg, ParentRef>, 'initialState' | 'initialStateFunc' | 'afterStop'>; export function spawn<ParentRef extends LocalActorSystemRef | LocalActorRef<any>, Func extends ActorFunc<any, any, ParentRef>>( parent: ParentRef, f: Func, propertiesOrName?: (string | ActorProps<InferStateFromFunc<Func>, InferMsgFromFunc<Func>, ParentRef>) ): LocalActorRef<InferMsgFromFunc<Func>> { return applyOrThrowIfStopped( parent, (p: ParentTypeFromRefType<ParentRef>) => p.assertNotStopped() && new Actor( p, p.system, f, (typeof propertiesOrName === 'string' ? { name: propertiesOrName } : propertiesOrName ) ).reference ); } const statelessSupervisionPolicy = (_: unknown, __: unknown, ctx: SupervisionContext<any, any>) => ctx.resume; export function spawnStateless<ParentRef extends LocalActorSystemRef | LocalActorRef<any>, Func extends StatelessActorFunc<any, ParentRef>>( parent: ParentRef, f: Func, propertiesOrName?: (string | StatelessActorProps<InferMsgFromStatelessFunc<Func>, ParentRef>) ): LocalActorRef<InferMsgFromStatelessFunc<Func>> { return spawn( parent, (_state: undefined, msg: InferMsgFromStatelessFunc<Func>, ctx: ActorContext<InferMsgFromStatelessFunc<Func>, ParentRef>): undefined => { f.call(ctx, msg, ctx); return undefined; }, { ...((typeof propertiesOrName === 'string' ? { name: propertiesOrName } : propertiesOrName) ?? {} ), onCrash: statelessSupervisionPolicy } ); }
the_stack
import type { JSX } from 'preact' import { h, Fragment } from 'preact' import { useContext, useState, useEffect, useMemo } from 'preact/hooks' import { useTitle } from 'hoofd/preact' import Modal from './util/Modal' import UserContext from './UserContext' import { Endpoints, Routes } from '../constants' import Spotify from 'simple-icons/icons/spotify.svg' import GitHub from 'simple-icons/icons/github.svg' import cutieSvg from '../assets/donate/cutie.svg?file' import blobkiss from '../assets/donate/blobkiss.png' import blobsmilehearts from '../assets/donate/blobsmilehearts.png' import blobhug from '../assets/donate/blobhug.png' import style from './account.module.css' import sharedStyle from './shared.module.css' const includes = [ 'A custom role in our server, custom badge color', 'A custom role in our server, custom badge color, custom profile badge', 'A custom role in our server, custom badge color, custom profile badge, custom server badge', ] function CutieOld ({ tier }: { tier: number }) { return ( <> <div className={style.cutieOld}> <img className={style.cutieLogoOld} src={cutieSvg} alt='Powercord Cutie'/> <div className={style.cutieContentsOld}> <span>Thank you for supporting Powercord! You are a tier {tier} patron.</span> <span>Includes: {includes[tier - 1]}.</span> </div> </div> {/* Soon! <p>You can customize your perks directly within the Discord client, if you have Powercord injected.</p> */} </> ) } function AccountOld () { useTitle('My Account') const user = useContext(UserContext)! const [ canDeleteAccount, setCanDeleteAccount ] = useState(true) const [ deletingAccount, setDeletingAccount ] = useState(false) useEffect(() => { // todo: check if the user can delete their account (or return in /@me?) setCanDeleteAccount(true) }, [ user.id ]) return ( <main> <h1>Welcome back, {user.username}#{user.discriminator}</h1> {Boolean(user.patronTier) && <CutieOld tier={user.patronTier!}/>} <h3 className={style.headerOld}>Linked Spotify account</h3> {typeof user.accounts?.spotify === 'string' // @ts-expect-error ? <p>{user.accounts.spotify} - <a href={Endpoints.UNLINK_ACCOUNT('spotify')} native>Unlink</a></p> // @ts-expect-error : <p>No account linked. <a href={Endpoints.LINK_ACCOUNT('spotify')} native>Link it now!</a></p>} <p> Linking your Spotify account gives you an enhanced experience with the Spotify plugin. It'll let you add songs to your Liked Songs, add songs to playlists, see private playlists and more. </p> <h3 className={style.headerOld}>Delete my Powercord account</h3> {canDeleteAccount ? <Fragment> <p> You can choose to permanently delete your Powercord account. This action is irreversible and will be in effect immediately. We'll drop any data we have about you, and you'll no longer be able to benefit from features requiring a Powercord account (such as enhanced Spotify plugin, settings sync, and more). </p> <p> <button className={`${sharedStyle.buttonLink} ${sharedStyle.red}`} onClick={() => setDeletingAccount(true)}> Delete my account </button> </p> </Fragment> : <Fragment> <p> You cannot delete your account as you still have items in the Store. You have to either transfer them to someone else, or mark them as deprecated in order to delete your account. </p> <p> <a href={Routes.STORE_MANAGE}>Go to the Powercord Store</a> </p> </Fragment>} {deletingAccount && ( <Modal title='Delete my account' onClose={() => setDeletingAccount(false)} onConfirm={() => (location.pathname = Endpoints.YEET_ACCOUNT)} closeText='Cancel' confirmText='Delete' color='red' > <div>Are you sure you want to delete your account? This operation is irreversible!</div> {Boolean(user.patronTier) && <p><b>Note:</b> You will lose your tier {user.patronTier} patron perks!</p>} </Modal> )} </main> ) } // ---- type LinkedAccountProps = { platform: string, icon: typeof Spotify, account?: string, explainer: string | JSX.Element } const HEARTS = [ '❤️', '🧡', '💛', '💚', '💙', '💜', '💗', '💖', '💝' ] function PowercordCutie () { const heart = useMemo(() => Math.floor(Math.random() * HEARTS.length), []) return ( <div className={style.cutieContainer}> <div className={style.cutieAd}> <div className={style.cutieAdHeader}> <img className={style.cutieAdLogo} src={cutieSvg} alt='Powercord Cutie'/> </div> <div className={style.cutieAdBody}> <h3 className={style.cutieAdTitle}>Support Powercord's Development</h3> <div className={style.cutieAdSubtitle}>And get sweet perks</div> <div className={style.cutieAdTier}> <img className={style.cutieAdIcon} src={blobkiss} alt='Tier 1 icon'/> <div> <div className={style.cutieAdPrice}>$1/month</div> <p className={style.cutieAdDescription}> Get a <b>fully customizable role</b> on Powercord's server, and <b>custom colors</b> for Powercord's profile badges. </p> </div> </div> <div className={style.cutieAdTier}> <img className={style.cutieAdIcon} src={blobsmilehearts} alt='Tier 2 icon'/> <div> <div className={style.cutieAdPrice}>$5/month</div> <p className={style.cutieAdDescription}> Get a <b>fully customizable</b> custom badge on your profile. </p> </div> </div> <div className={style.cutieAdTier}> <img className={style.cutieAdIcon} src={blobhug} alt='Tier 3 icon'/> <div> <div className={style.cutieAdPrice}>$10/month</div> <p className={style.cutieAdDescription}> Get a <b>fully customizable</b> badge for <b>one</b> of your servers. </p> </div> </div> <div className={style.cutieAdButtons}> <a href={Routes.PATREON} target='_blank' rel='noreferrer'>Donate on Patreon {HEARTS[heart]}</a> </div> </div> </div> </div> ) } function ManagePerks () { return ( <div className={style.cutieContainer}> <h2>Donator perks</h2> </div> ) } function LinkedAccount ({ platform, icon, account, explainer }: LinkedAccountProps) { return ( <div className={style.linkedAccount}> {h(icon, { className: style.linkedAccountIcon })} <div> {account // @ts-expect-error ? <div>{account} - <a native href={Endpoints.UNLINK_ACCOUNT(platform)}>Unlink</a></div> // @ts-expect-error : <div>No account linked - <a native href={Endpoints.LINK_ACCOUNT(platform)}>Link it now</a></div>} <div className={style.linkedAccountExplainer}>{explainer}</div> </div> </div> ) } function Account () { useTitle('My Account') const user = useContext(UserContext)! const [ canDeleteAccount, setCanDeleteAccount ] = useState(true) const [ deletingAccount, setDeletingAccount ] = useState(false) useEffect(() => { // todo: check if the user can delete their account setCanDeleteAccount(true) }, [ user.id ]) return ( <main> <h1>Welcome back, {user.username}</h1> <div className={style.columns}> <div className={style.linkedAccounts}> <h2>Linked accounts</h2> <LinkedAccount platform='spotify' icon={Spotify} account={user.accounts.spotify} explainer={'Linking your Spotify account gives you an enhanced experience with the Spotify plugin. It\'ll let you add songs to your Liked Songs, add songs to playlists, see private playlists and more.'} /> {import.meta.env.DEV && <LinkedAccount platform='github' icon={GitHub} account={user.accounts.github} explainer={<> Linking your GitHub is required in order to publish works (or to be collaborator on someone's work) in the <a href={Routes.STORE_PLUGINS}>Powercord Store</a>. If you are a contributor, it will be shown on the <a href={Routes.CONTRIBUTORS}>contributors page</a>. </>} />} <hr/> <h2>Delete my account</h2> {canDeleteAccount ? <Fragment> <p> You can choose to permanently delete your Powercord account. Be careful, this action is irreversible and will take effect immediately. </p> <p> We will drop any data we have about you, and you'll no longer be able to benefit from features requiring a Powercord account (such as enhanced Spotify plugin, settings sync, and more). </p> <p> <button className={`${sharedStyle.buttonLink} ${sharedStyle.red}`} onClick={() => setDeletingAccount(true)}> Delete my account </button> </p> </Fragment> : <Fragment> <p> You cannot delete your account right now as you still have items in the Store. You have to either transfer them to someone else, or mark them as deprecated in order to delete your account. </p> <p> <a href={Routes.STORE_MANAGE}>Go to the Powercord Store</a> </p> </Fragment>} {deletingAccount && ( <Modal title='Delete my account' onClose={() => setDeletingAccount(false)} onConfirm={() => (location.pathname = Endpoints.YEET_ACCOUNT)} closeText='Cancel' confirmText='Delete' color='red' > <div>Are you sure you want to delete your account? This operation is irreversible!</div> {Boolean(user.patronTier) && <p><b>Note:</b> You will lose your tier {user.patronTier} patron perks!</p>} </Modal> )} </div> {user.patronTier ? <ManagePerks/> : <PowercordCutie/>} </div> </main> ) } export default function AccountWrapper () { return import.meta.env.DEV ? <Account/> : <AccountOld/> }
the_stack
import * as O from "../src" import * as U from "./test-utils" test("isNil", () => { expect(O.isNil(undefined)).toBe(true) expect(O.isNil(null)).toBe(true) expect(O.isNil(0)).toBe(false) }) test("isUndefined", () => { expect(O.isUndefined(undefined)).toBe(true) expect(O.isUndefined(null)).toBe(false) expect(O.isUndefined(0)).toBe(false) }) test("isType", () => { const isBoolean = O.isType<boolean>("boolean") expect(isBoolean).toEqual(expect.any(Function)) expect(isBoolean).toHaveLength(1) expect(isBoolean(true)).toBe(true) expect(isBoolean(false)).toBe(true) expect(isBoolean(undefined)).toBe(false) expect(isBoolean(null)).toBe(false) expect(isBoolean("0")).toBe(false) expect(isBoolean(1)).toBe(false) }) test("isFunction", () => { function regular() { return null } const arrow = () => { return null } expect(O.isFunction(regular)).toBe(true) expect(O.isFunction(arrow)).toBe(true) expect(O.isFunction({})).toBe(false) expect(O.isFunction([])).toBe(false) expect(O.isFunction(0)).toBe(false) expect(O.isFunction("0")).toBe(false) expect(O.isFunction(null)).toBe(false) expect(O.isFunction(undefined)).toBe(false) }) test("isObject", () => { expect(O.isObject(null)).toBe(true) expect(O.isObject({})).toBe(true) expect(O.isObject([])).toBe(true) expect(O.isObject(0)).toBe(false) expect(O.isObject("0")).toBe(false) expect(O.isObject(undefined)).toBe(false) }) test("isPlainObject", () => { expect(O.isPlainObject({})).toBe(true) expect(O.isPlainObject([])).toBe(false) expect(O.isPlainObject(null)).toBe(false) expect(O.isPlainObject(undefined)).toBe(false) expect(O.isPlainObject("0")).toBe(false) expect(O.isPlainObject(0)).toBe(false) }) test("isString", () => { expect(O.isString("")).toBe(true) expect(O.isString("0")).toBe(true) expect(O.isString("foo")).toBe(true) expect(O.isString(undefined)).toBe(false) expect(O.isString(null)).toBe(false) expect(O.isString({})).toBe(false) expect(O.isString([])).toBe(false) expect(O.isString(0)).toBe(false) }) test("isNumber", () => { expect(O.isNumber(0)).toBe(true) expect(O.isNumber(1)).toBe(true) expect(O.isNumber(-1)).toBe(true) expect(O.isNumber(NaN)).toBe(false) expect(O.isNumber(undefined)).toBe(false) expect(O.isNumber(null)).toBe(false) expect(O.isNumber({})).toBe(false) expect(O.isNumber([])).toBe(false) expect(O.isNumber("0")).toBe(false) }) test("isNumberLike", () => { // Truthy expect(O.isNumberLike(0)).toBe(true) expect(O.isNumberLike(0.1)).toBe(true) expect(O.isNumberLike(.1)).toBe(true) // prettier-ignore expect(O.isNumberLike(1)).toBe(true) expect(O.isNumberLike(1.1)).toBe(true) expect(O.isNumberLike(11.1)).toBe(true) expect(O.isNumberLike(-0)).toBe(true) expect(O.isNumberLike(-0.1)).toBe(true) expect(O.isNumberLike(-.1)).toBe(true) // prettier-ignore expect(O.isNumberLike(-1)).toBe(true) expect(O.isNumberLike(-1.1)).toBe(true) expect(O.isNumberLike(-11.1)).toBe(true) expect(O.isNumberLike("0")).toBe(true) expect(O.isNumberLike("0.1")).toBe(true) expect(O.isNumberLike(".1")).toBe(true) expect(O.isNumberLike("1")).toBe(true) expect(O.isNumberLike("1.1")).toBe(true) expect(O.isNumberLike("11.1")).toBe(true) expect(O.isNumberLike("-0")).toBe(true) expect(O.isNumberLike("-0.1")).toBe(true) expect(O.isNumberLike("-.1")).toBe(true) expect(O.isNumberLike("-1")).toBe(true) expect(O.isNumberLike("-1.1")).toBe(true) expect(O.isNumberLike("-11.1")).toBe(true) // Falsey expect(O.isNumberLike(NaN)).toBe(false) expect(O.isNumberLike(null)).toBe(false) expect(O.isNumberLike(undefined)).toBe(false) expect(O.isNumberLike("")).toBe(false) expect(O.isNumberLike("-")).toBe(false) expect(O.isNumberLike("foo")).toBe(false) expect(O.isNumberLike({})).toBe(false) expect(O.isNumberLike([])).toBe(false) }) test("isUnitless", () => { // Truthy expect(O.isUnitless("0.1")).toBe(true) expect(O.isUnitless(".1")).toBe(true) expect(O.isUnitless("1")).toBe(true) expect(O.isUnitless("1.1")).toBe(true) expect(O.isUnitless("11.1")).toBe(true) expect(O.isUnitless("-0.1")).toBe(true) expect(O.isUnitless("-.1")).toBe(true) expect(O.isUnitless("-1")).toBe(true) expect(O.isUnitless("-1.1")).toBe(true) expect(O.isUnitless("-11.1")).toBe(true) // Falsey expect(O.isUnitless("0")).toBe(false) expect(O.isUnitless("-0")).toBe(false) expect(O.isUnitless("0px")).toBe(false) expect(O.isUnitless("-0px")).toBe(false) expect(O.isUnitless("1px")).toBe(false) expect(O.isUnitless("-1px")).toBe(false) }) test("isFraction", () => { expect(O.isFraction(0.1)).toBe(true) expect(O.isFraction(3 / 4)).toBe(true) expect(O.isFraction(0)).toBe(false) expect(O.isFraction(1)).toBe(false) expect(O.isFraction(null)).toBe(false) expect(O.isFraction("foo")).toBe(false) }) test("when", () => { const add1 = (n: number) => n + 1 const whenFraction = O.when(O.isFraction) const whenUnitless = O.when(O.isUnitless) expect(whenFraction(add1)(0)).toBe(0) expect(whenFraction(add1)(1)).toBe(1) expect(whenFraction(add1)(0.2)).toBe(1.2) expect(whenFraction(add1)(3 / 4)).toBe(1.75) expect(whenFraction(add1)("2px")).toBe("2px") expect(whenUnitless(add1)(0)).toBe(0) expect(whenUnitless(add1)(1)).toBe(2) expect(whenUnitless(add1)(0.2)).toBe(1.2) expect(whenUnitless(add1)(3 / 4)).toBe(1.75) expect(whenUnitless(add1)("2px")).toBe("2px") }) test("addPx", () => { expect(O.addPx(0)).toBe(0) expect(O.addPx(1)).toBe("1px") expect(O.addPx(-2)).toBe("-2px") expect(O.addPx("0")).toBe("0") expect(O.addPx("1")).toBe("1px") expect(O.addPx("-2")).toBe("-2px") expect(O.addPx("2em")).toBe("2em") }) test("addPc", () => { expect(O.addPc(0)).toBe(0) expect(O.addPc(1)).toBe(1) expect(O.addPc(0.15)).toBe("15%") expect(O.addPc(-0.25)).toBe("-25%") expect(O.addPc(3 / 4)).toBe("75%") expect(O.addPc("0")).toBe("0") expect(O.addPc("0.5")).toBe("50%") expect(O.addPc("-0.05")).toBe("-5%") expect(O.addPc("2em")).toBe("2em") }) test("addRem", () => { expect(O.addRem(0)).toBe(0) expect(O.addRem(1.5)).toBe("1.5rem") expect(O.addRem(-2)).toBe("-2rem") expect(O.addRem("2px")).toBe("2px") }) test("addPcOrPx", () => { expect(O.addPcOrPx(0)).toBe(0) expect(O.addPcOrPx(0.1)).toBe("10%") expect(O.addPcOrPx(-0.1)).toBe("-10%") expect(O.addPcOrPx(0.5)).toBe("50%") expect(O.addPcOrPx(-0.5)).toBe("-50%") expect(O.addPcOrPx(3 / 4)).toBe("75%") expect(O.addPcOrPx(-3 / 4)).toBe("-75%") expect(O.addPcOrPx(1)).toBe("1px") expect(O.addPcOrPx(2)).toBe("2px") expect(O.addPcOrPx(-1)).toBe("-1px") expect(O.addPcOrPx(-2)).toBe("-2px") expect(O.addPcOrPx("1em")).toBe("1em") expect(O.addPcOrPx("2vw")).toBe("2vw") }) test("mq", () => { expect(O.mq(320)).toMatchSnapshot() expect(O.mq("20rem")).toMatchSnapshot() }) test("toArray", () => { expect(O.toArray([1, 2, 3])).toEqual([1, 2, 3]) expect(O.toArray([[1, 2, 3], 4, 5, 6])).toEqual([1, 2, 3]) }) test("toPath", () => { expect(O.toPath(0)).toEqual([0]) expect(O.toPath(1)).toEqual([1]) expect(O.toPath("a")).toEqual(["a"]) expect(O.toPath("a.b")).toEqual(["a", "b"]) expect(O.toPath("a.1")).toEqual(["a", "1"]) expect(O.toPath("0.2")).toEqual(["0.2"]) expect(O.toPath("1.25")).toEqual(["1.25"]) expect(O.toPath("2.5em")).toEqual(["2.5em"]) expect(O.toPath("-1.4rem")).toEqual(["-1.4rem"]) expect(O.toPath("2px 4.5rem")).toEqual(["2px 4.5rem"]) }) test("get", () => { // Undefined expect(O.get()).toBeUndefined() expect(O.get("foo")).toBeUndefined() expect(O.get("zoo", U.OBJ)).toBeUndefined() expect(O.get("foo.a", U.OBJ)).toBeUndefined() // Identity expect(O.get(".", U.OBJ)).toBe(U.OBJ) expect(O.get(["."], U.OBJ)).toBe(U.OBJ) // Indexes expect(O.get(1, [1, 2, 3])).toBe(2) expect(O.get(-2, [1, 2, 3])).toBe(-3) // Strings expect(O.get("boo", U.OBJ)).toBeNull() expect(O.get("foo", U.OBJ)).toBe(U.OBJ.foo) expect(O.get("bar", U.OBJ)).toBe(U.OBJ.bar) expect(O.get("bar.a", U.OBJ)).toBe(U.OBJ.bar.a) expect(O.get("bar.b", U.OBJ)).toBe(U.OBJ.bar.b) expect(O.get("bar.c", U.OBJ)).toBe(U.OBJ.bar.c) expect(O.get("bar.d", U.OBJ)).toBe(U.OBJ.bar.d) expect(O.get("bar.d.1", U.OBJ)).toBe(U.OBJ.bar.d[1]) expect(O.get("-bar.d.2", U.OBJ)).toBe(-U.OBJ.bar.d[2]) // Arrays expect(O.get([1], [1, 2, 3])).toBe(2) expect(O.get([-2], [1, 2, 3])).toBe(-3) expect(O.get(["boo"], U.OBJ)).toBeNull() expect(O.get(["foo"], U.OBJ)).toBe(U.OBJ.foo) expect(O.get(["bar"], U.OBJ)).toBe(U.OBJ.bar) expect(O.get(["bar", "a"], U.OBJ)).toBe(U.OBJ.bar.a) expect(O.get(["bar", "b"], U.OBJ)).toBe(U.OBJ.bar.b) expect(O.get(["bar", "c"], U.OBJ)).toBe(U.OBJ.bar.c) expect(O.get(["bar", "d"], U.OBJ)).toBe(U.OBJ.bar.d) expect(O.get(["bar", "d", 1], U.OBJ)).toBe(U.OBJ.bar.d[1]) expect(O.get(["bar", "d", "2"], U.OBJ)).toBe(U.OBJ.bar.d[2]) expect(O.get(["-bar", "d", 1], U.OBJ)).toBe(-U.OBJ.bar.d[1]) expect(O.get(["-bar", "d", "2"], U.OBJ)).toBe(-U.OBJ.bar.d[2]) // Aliases expect(O.get("baz.0", U.OBJ)).toBeUndefined() expect(O.get("baz.A0", U.OBJ)).toBeUndefined() expect(O.get("baz.1", U.OBJ)).toBe(U.OBJ.baz[1]) // { value: "V1" } expect(O.get("baz.A1", U.OBJ)).toBeUndefined() expect(O.get("baz.2", U.OBJ)).toBe("V2") expect(O.get("baz.A2", U.OBJ)).toBe("V2") expect(O.get("baz.3", U.OBJ)).toBe(0) expect(O.get("baz.A3", U.OBJ)).toBe(0) expect(O.get("baz.4", U.OBJ)).toBe("V4") expect(O.get("baz.A4", U.OBJ)).toBeUndefined() expect(O.get("baz.5", U.OBJ)).toBe(0) expect(O.get("baz.A5", U.OBJ)).toBeUndefined() }) test("resolve", () => { // Undefined expect(O.resolve()).toBeUndefined() expect(O.resolve([])).toBeUndefined() expect(O.resolve([], U.OBJ)).toBeUndefined() expect(O.resolve(["zoo"], U.OBJ)).toBeUndefined() expect(O.resolve(["foo.a"], U.OBJ)).toBeUndefined() // Identity expect(O.resolve(["."], U.OBJ)).toBe(U.OBJ) expect(O.resolve(["zoo", "."], U.OBJ)).toBe(U.OBJ) // Resolve expect(O.resolve(["boo"], U.OBJ)).toBeNull() expect(O.resolve(["foo"], U.OBJ)).toBe(U.OBJ.foo) expect(O.resolve(["bar"], U.OBJ)).toBe(U.OBJ.bar) expect(O.resolve(["bar.a"], U.OBJ)).toBe(U.OBJ.bar.a) expect(O.resolve(["bar.b"], U.OBJ)).toBe(U.OBJ.bar.b) expect(O.resolve(["bar.c"], U.OBJ)).toBe(U.OBJ.bar.c) expect(O.resolve(["bar.d"], U.OBJ)).toBe(U.OBJ.bar.d) expect(O.resolve(["bar.d.1"], U.OBJ)).toBe(U.OBJ.bar.d[1]) // Priority expect(O.resolve(["foo", "bar"], U.OBJ)).toBe(U.OBJ.foo) expect(O.resolve(["bar", "foo"], U.OBJ)).toBe(U.OBJ.bar) // Fallback expect(O.resolve(["foo.a", "bar.a"], U.OBJ)).toBe(U.OBJ.bar.a) expect(O.resolve(["foo.a", "bar.e"], U.OBJ)).toBeUndefined() // Aliases expect(O.resolve(["baz.0"], U.OBJ)).toBeUndefined() expect(O.resolve(["baz.A0"], U.OBJ)).toBeUndefined() expect(O.resolve(["baz.1"], U.OBJ)).toBe(U.OBJ.baz[1]) // { value: "V1" } expect(O.resolve(["baz.A1"], U.OBJ)).toBeUndefined() expect(O.resolve(["baz.2"], U.OBJ)).toBe("V2") expect(O.resolve(["baz.A2"], U.OBJ)).toBe("V2") expect(O.resolve(["baz.3"], U.OBJ)).toBe(0) expect(O.resolve(["baz.A3"], U.OBJ)).toBe(0) expect(O.resolve(["baz.4"], U.OBJ)).toBe("V4") expect(O.resolve(["baz.A4"], U.OBJ)).toBeUndefined() expect(O.resolve(["baz.5"], U.OBJ)).toBe(0) expect(O.resolve(["baz.A5"], U.OBJ)).toBeUndefined() }) test("merge", () => { interface Test { a?: number b?: number c?: number d?: number } expect(O.merge<Test>([])).toEqual({}) expect(O.merge<Test | null>([null, { a: 1 }, null])).toEqual({ a: 1 }) expect(O.merge<Test>([{ a: 1 }, { a: 2 }])).toEqual({ a: 2 }) expect(O.merge<Test>([{ a: 1 }, { b: 2 }])).toEqual({ a: 1, b: 2 }) expect(O.merge<Test>([{ a: 1 }, { b: 2 }], { c: 3 })).toEqual({ a: 1, b: 2, c: 3 }) expect(O.merge<Test>([{ a: 1 }, [{ b: 2 }, [{ c: 3 }]]], { d: 4 })).toEqual({ a: 1, b: 2, c: 3, d: 4 }) const array = [{ a: 1 }, [{ a: 2 }, [{ a: 3 }, [{ a: 4 }]]]] expect(O.merge<Test>(array, { b: 2 })).toEqual({ a: 4, b: 2 }) })
the_stack